/* ============================================================
   App shell: hash router, theme + tweaks, nav/footer, mount.
   Receives one storefront config loaded from JSON.
   ============================================================ */

const { useState: uS, useEffect: uE, useCallback: uC } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "heroLayout": "split",
  "heroImageSize": 250,
  "heroImageX": 0,
  "heroImageY": 0,
  "heroImageMobileSize": 300,
  "heroImageMobileX": 0,
  "heroImageMobileY": 0,
  "heroImageRotate": true,
  "heroImageRotateSpeed": 300,
  "heroImageRotateOriginX": 50,
  "heroImageRotateOriginY": 0,
  "cardStyle": "clean",
  "theme": "__brand"
}/*EDITMODE-END*/;

const ROUTES = ["home", "menu", "order", "contact"];

// URL params let a gallery/embed pin a specific variation:
//   ?hero=split|centered|fullbleed  ?cards=clean|editorial|list
//   ?theme=__brand|warm|cream|ink|forest  ?route=home|menu|order|contact
//   ?scroll=<px>  ?gallery=1 (ephemeral cart, no persistence)
const QP = new URLSearchParams(location.search);
const GALLERY = QP.get("gallery") === "1";

// The Tweaks panel is a local design tool — show it only on a dev host
// (localhost / file://), never on the deployed site. Force on with ?tweaks=1.
const IS_DEV = location.protocol === "file:" ||
  /^(localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1\])$/.test(location.hostname);
const SHOW_TWEAKS = QP.get("tweaks") === "1" || (IS_DEV && QP.get("tweaks") !== "0");
function paramTweaks() {
  const o = {};
  if (QP.get("hero")) o.heroLayout = QP.get("hero");
  if (QP.get("cards")) o.cardStyle = QP.get("cards");
  if (QP.get("theme")) o.theme = QP.get("theme");
  return o;
}

function routeFromHash() {
  const h = (location.hash || "").replace(/^#\/?/, "").split("?")[0];
  if (ROUTES.includes(h)) return h;
  const r = QP.get("route");
  return ROUTES.includes(r) ? r : "home";
}

function App({ brand }) {
  const [t, setTweak] = useTweaks({ ...TWEAK_DEFAULTS, ...paramTweaks() });
  const [route, setRoute] = uS(routeFromHash());
  const cart = useCart(brand.id, GALLERY);

  // gallery embeds open on a chosen page and optional scroll offset
  uE(() => {
    const s = +QP.get("scroll") || 0;
    if (s) requestAnimationFrame(() => window.scrollTo(0, s));
  }, []);

  // resolve theme: "__brand" means use the brand's default
  const theme = t.theme === "__brand" || !t.theme ? brand.theme : t.theme;
  uE(() => { document.documentElement.setAttribute("data-theme", theme); }, [theme]);

  // hash routing
  uE(() => {
    const onHash = () => { setRoute(routeFromHash()); };
    window.addEventListener("hashchange", onHash);
    return () => window.removeEventListener("hashchange", onHash);
  }, []);

  const go = uC((r) => {
    if (location.hash.replace(/^#\/?/, "") !== r) location.hash = `/${r}`;
    setRoute(r);
    window.scrollTo({ top: 0, behavior: "instant" in window ? "instant" : "auto" });
  }, []);

  const count = cartCount(cart.items);
  const exportTweaks = uC(() => {
    const blob = new Blob([JSON.stringify(t, null, 2)], { type: "application/json" });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = `${brand.id || "storefront"}-tweaks.json`;
    document.body.appendChild(a);
    a.click();
    a.remove();
    URL.revokeObjectURL(url);
  }, [brand.id, t]);

  let Page;
  if (route === "menu") Page = <MenuPage brand={brand} cart={cart} go={go} t={t} />;
  else if (route === "order") Page = <OrderPage brand={brand} cart={cart} go={go} />;
  else if (route === "contact") Page = <ContactPage brand={brand} go={go} />;
  else Page = <HomePage brand={brand} cart={cart} go={go} t={t} />;

  return (
    <div className="site" data-route={route}>
      <Nav brand={brand} route={route} go={go} count={count} />
      <div key={route} className="route-fade">{Page}</div>
      <Footer brand={brand} go={go} />

      {SHOW_TWEAKS && <TweaksPanel title="Tweaks">
        <TweakSection label="Layout" />
        <TweakRadio label="Hero" value={t.heroLayout}
          options={[{ value: "split", label: "Split" }, { value: "centered", label: "Center" }, { value: "fullbleed", label: "Full" }]}
          onChange={(v) => setTweak("heroLayout", v)} />
        <TweakSelect label="Menu cards" value={t.cardStyle}
          options={[{ value: "clean", label: "Clean (image top)" }, { value: "editorial", label: "Editorial (large)" }, { value: "list", label: "List (compact)" }]}
          onChange={(v) => setTweak("cardStyle", v)} />

        <TweakSection label="Hero image" />
        <TweakToggle label="Slow rotate" value={t.heroImageRotate}
          onChange={(v) => setTweak("heroImageRotate", v)} />
        <TweakSlider label="Rotate speed" value={t.heroImageRotateSpeed} min={20} max={360} unit="s"
          onChange={(v) => setTweak("heroImageRotateSpeed", v)} />
        <TweakSlider label="Spin center X" value={t.heroImageRotateOriginX} min={0} max={100} unit="%"
          onChange={(v) => setTweak("heroImageRotateOriginX", v)} />
        <TweakSlider label="Spin center Y" value={t.heroImageRotateOriginY} min={0} max={100} unit="%"
          onChange={(v) => setTweak("heroImageRotateOriginY", v)} />
        <TweakSlider label="Size" value={t.heroImageSize} min={70} max={320} unit="%"
          onChange={(v) => setTweak("heroImageSize", v)} />
        <TweakSlider label="Left / right" value={t.heroImageX} min={-320} max={320} unit="px"
          onChange={(v) => setTweak("heroImageX", v)} />
        <TweakSlider label="Up / down" value={t.heroImageY} min={-220} max={220} unit="px"
          onChange={(v) => setTweak("heroImageY", v)} />

        <TweakSection label="Mobile image" />
        <TweakSlider label="Size" value={t.heroImageMobileSize} min={70} max={320} unit="%"
          onChange={(v) => setTweak("heroImageMobileSize", v)} />
        <TweakSlider label="Left / right" value={t.heroImageMobileX} min={-320} max={320} unit="px"
          onChange={(v) => setTweak("heroImageMobileX", v)} />
        <TweakSlider label="Up / down" value={t.heroImageMobileY} min={-220} max={220} unit="px"
          onChange={(v) => setTweak("heroImageMobileY", v)} />

        <TweakSection label="Color theme" />
        <TweakSelect label="Palette" value={t.theme}
          options={[
            { value: "__brand", label: "Brand default" },
            { value: "warm", label: "Warm · tomato" },
            { value: "cream", label: "Cream · berry" },
            { value: "ink", label: "Ink · minimal" },
            { value: "forest", label: "Forest · herb" },
          ]}
          onChange={(v) => setTweak("theme", v)} />
        <TweakSection label="Export" />
        <TweakButton label="Download settings" onClick={exportTweaks} />
        <p style={{ fontSize: "10.5px", lineHeight: 1.5, color: "rgba(41,38,27,.5)", margin: "2px 0 0" }}>
          Same template, both brands — only the menu data &amp; default palette change.
        </p>
      </TweaksPanel>}
    </div>
  );
}

function renderConfigError(error) {
  document.getElementById("root").innerHTML = `
    <main class="config-error">
      <h1>Storefront config could not be loaded</h1>
      <p>${String(error.message || error)}</p>
    </main>
  `;
}

(window.BRAND_CONFIG_PROMISE || Promise.resolve(window.BRAND_CONFIG))
  .then((brand) => {
    document.title = brand.full || brand.name;
    document.documentElement.setAttribute("data-theme", brand.theme || "warm");
    ReactDOM.createRoot(document.getElementById("root")).render(<App brand={brand} />);
  })
  .catch(renderConfigError);
