"""
Entry point: wires all top-level DOM events after Brython starts.
100% vibe coded by Claude Code.
"""
from browser import document, window
import uuid as _uuid_mod

from sections import add_section
from preview import schedule_preview, download_yaml, copy_yaml
from import_yaml import init_import
from resize import init_resize


def _gen_uuid(ev):
    document["field-uuid"].value = str(_uuid_mod.uuid4())
    schedule_preview()


def _on_form_input(ev):
    schedule_preview()


def init():
    document["btn-add-section"].bind("click", lambda ev: add_section())
    document["btn-generate-uuid"].bind("click", _gen_uuid)
    document["btn-download"].bind("click", lambda ev: download_yaml())
    document["btn-copy"].bind("click", lambda ev: copy_yaml())

    # Live preview: any input/change inside the form triggers a debounced update
    document["main-form"].bind("input", _on_form_input)
    document["main-form"].bind("change", _on_form_input)

    init_import()
    init_resize()


def _restore_from_local_storage():
    import json
    from import_yaml import _populate_form
    try:
        saved = window.localStorage.getItem("fs_template")
        if saved:
            _populate_form(json.loads(saved))
    except Exception:
        pass


init()
_restore_from_local_storage()
