// Loads the product's own files and publishes window.HearthApp.
//
// Three details worth keeping (shared with the other templates here):
//   1. The global is published SYNCHRONOUSLY as a stub that re-renders itself
//      when the real App lands. <x-import component-from-global-scope> resolves
//      the global with a bounded wait, and on a cold cache the load below takes
//      longer than that window — the placeholder never retries.
//   2. React, ReactDOM and Babel are NOT fetched when the page is a Design
//      Component: the DC runtime puts its own copies on window, and a second
//      React breaks every hook. We wait, and fall back to the CDN only if
//      nothing else provides them.
//   3. Each file is evaluated in its own function scope rather than appended as
//      a <script>, so the loader can be re-run against a rebuilt document.
(() => {
  const base = new URL(".", document.currentScript.src).href;
  const READY = "hearth:ready";
  if (!window.HearthApp) {
    window.HearthApp = function HearthAppStub(props) {
      const [, bump] = window.React.useState(0);
      window.React.useEffect(() => {
        if (window.__hearthReal) return undefined;
        const on = () => bump((n) => n + 1);
        window.addEventListener(READY, on);
        return () => window.removeEventListener(READY, on);
      }, []);
      const Real = window.__hearthReal;
      return Real ? window.React.createElement(Real, props) : null;
    };
  }

  const load = (src) => new Promise((res, rej) => { const s = document.createElement("script"); s.src = src; s.crossOrigin = "anonymous"; s.onload = res; s.onerror = () => rej(new Error("failed to load " + src)); document.head.appendChild(s); });
  const wait = async (test, ms) => { for (let i = 0; i < ms / 25; i++) { if (test()) return true; await new Promise((r) => setTimeout(r, 25)); } return !!test(); };
  const FILES = [
    "lib/contracts.js", "enums.js", "nav.js", "fixtures.js",
    "lib/ui-runtime.js", "metrics.js", "lib/command-palette.js", "lib/template-menu.js",
    "HearthShell.jsx", "HearthParts.jsx",
    "TodayScreen.jsx", "RoomsScreen.jsx", "DeviceScreens.jsx", "CamerasScreen.jsx", "ClimateScreen.jsx", "SecurityScreen.jsx",
    "EnergyScreen.jsx", "SpendScreen.jsx", "UpkeepScreens.jsx", "PeopleScreens.jsx", "RoutinesScreen.jsx",
    "LogScreen.jsx", "SettingsScreens.jsx", "AuthScreens.jsx",
    "HouseCommits.jsx", "App.jsx",
  ];
  (async () => {
    const sources = FILES.map((f) => fetch(base + f).then((r) => r.text()));
    if (!window.React || !window.ReactDOM) {
      if (!(await wait(() => window.React && window.ReactDOM, 1500))) {
        if (!window.React) await load("https://unpkg.com/react@18.3.1/umd/react.development.js");
        if (!window.ReactDOM) await load("https://unpkg.com/react-dom@18.3.1/umd/react-dom.development.js");
      }
    }
    if (!window.Babel) await load("https://unpkg.com/@babel/standalone@7.29.0/babel.min.js");
    if (!window.lucide) await load("https://unpkg.com/lucide@0.544.0/dist/umd/lucide.min.js");
    await wait(() => Object.keys(window).some((k) => k.indexOf("OriginDesignSystem") === 0), 10000);
    for (let i = 0; i < FILES.length; i++) {
      const src = await sources[i];
      const out = window.Babel.transform(src, { presets: ["react"], filename: FILES[i] }).code;
      try { new Function(out)(); } catch (e) { console.error("boot.js: " + FILES[i], e); throw e; }
    }
    window.dispatchEvent(new Event(READY));
  })().catch((e) => console.error("boot.js:", e));
})();
