# Entry point for the site's front end (MicroPython under PyScript, loaded by Base.astro).
# The HTML is complete without it: every island enhances markup Astro already rendered.
from js import window
import asyncio.core


class _Js:
    # MicroPython's asyncio wakes itself with js.setTimeout. On PyScript's main thread that
    # call can run with the wrong `this` ("Illegal invocation", the trap dom.py describes):
    # the scheduler dies and an awaited fetch never resumes - the index's search stayed
    # empty after a field was focused and left. Bound to the real window, the timer holds.
    def __init__(self):
        self.setTimeout = window.setTimeout.bind(window)
        self.clearTimeout = window.clearTimeout.bind(window)

    def __getattr__(self, name):
        return getattr(window, name)


asyncio.core.js = _Js()

from w76 import origami, nav, letter, fold, contact, atlas, footer
from w76.dom import qsa

# Islands: a component that Python takes over carries data-island="<module>" on its root
# (src/components/PyIsland.astro is the wrapper for new markup). Only the islands present on
# this page are mounted, in this order (origami first: the others call it), and each is
# marked data-ready="true" once live, so CSS can tell Astro's HTML from live Python.
MODULES = (("origami", origami), ("nav", nav), ("letter", letter), ("fold", fold),
           ("contact", contact), ("atlas", atlas), ("footer", footer))
present = {el.getAttribute("data-island") for el in qsa("[data-island]")}
for name, module in MODULES:
    if name not in present:
        continue
    try:
        module.mount()
        for el in qsa('[data-island="{}"]'.format(name)):
            el.setAttribute("data-ready", "true")
    except Exception as e:
        # One broken island must not take the others down with it.
        print("w76:", name, "failed:", e)

# Base.astro holds any form submit that arrives before this point (instead of letting it
# fall through as a native GET); from here on the contact module owns submit.
window.__w76py = True
