// app.jsx — Marsa Cove · Off-Plan Microsite (Template Demo for D&B Properties)
// Composes the chrome (Nav/Hero/Footer/FAB/Modal) with the chapter sections.
// Manages locale, tweaks, scroll-driven nav, and intersection-observer entry animations.

const { useState, useEffect, useRef, useMemo } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "palette": ["#171144", "#F6F3EE", "#B8935C"],
  "paletteId": "ink",
  "hero": "cinematic",
  "density": "regular",
  "showWA": true,
  "showDemoStrip": false,
  "locale": "en"
}/*EDITMODE-END*/;

function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [locale, setLocale] = useState(t.locale || "en");
  const [localeOpen, setLocaleOpen] = useState(false);
  const [registerOpen, setRegisterOpen] = useState(false);
  const [navDark, setNavDark] = useState(true);
  const [progress, setProgress] = useState(0);
  const L = window.LOCALES[locale];

  // Expose locale globally for sub-components / form logging
  window.__LOCALE = locale;

  // Document dir + lang
  useEffect(() => {
    document.documentElement.dir = L.dir;
    document.documentElement.lang = locale;
    document.body.style.fontFamily = locale === "ar" ? "var(--ar)" : "var(--sans)";
  }, [locale, L.dir]);

  // Density attr
  useEffect(() => {
    document.documentElement.setAttribute("data-density", t.density);
  }, [t.density]);

  // Persist locale into tweak state so reload restores
  useEffect(() => {
    if (t.locale !== locale) setTweak("locale", locale);
  }, [locale]);

  // Apply palette tokens
  useEffect(() => {
    const palette = window.TWEAK_PALETTES.find((p) => p.id === t.paletteId) || window.TWEAK_PALETTES[0];
    const r = document.documentElement.style;
    Object.entries(palette.tokens).forEach(([k, v]) => {
      r.setProperty("--" + (k === "ink2" ? "ink-2" : k === "gold2" ? "gold-2" : k), v);
    });
  }, [t.paletteId]);

  // Scroll: nav dark <-> light, progress bar, AND fade-up reveal (scroll-based because
  // IntersectionObserver doesn't fire reliably in the preview sandbox iframe).
  useEffect(() => {
    function revealInView() {
      const vh = window.innerHeight;
      document.querySelectorAll(".fade-up:not(.is-in)").forEach((el) => {
        const r = el.getBoundingClientRect();
        if (r.top < vh - 40 && r.bottom > 0) el.classList.add("is-in");
      });
    }
    function onScroll() {
      const y = window.scrollY;
      const vh = window.innerHeight;
      setNavDark(y < vh * 0.7);
      const max = document.documentElement.scrollHeight - vh;
      setProgress(max > 0 ? Math.min(1, y / max) : 0);
      revealInView();
    }
    onScroll();
    setTimeout(revealInView, 50);
    setTimeout(revealInView, 400);
    window.addEventListener("scroll", onScroll, { passive: true });
    window.addEventListener("resize", revealInView);
    return () => {
      window.removeEventListener("scroll", onScroll);
      window.removeEventListener("resize", revealInView);
    };
  }, []);

  // (removed separate IntersectionObserver effect — sandbox doesn't fire IO callbacks reliably)

  // open register from anywhere
  useEffect(() => {
    function on() { setRegisterOpen(true); }
    window.addEventListener("open-register", on);
    return () => window.removeEventListener("open-register", on);
  }, []);

  return (
    <div>
      <div className="scroll-prog" style={{ transform: `scaleX(${progress})` }}></div>

      {t.showDemoStrip && (
        <div className="demo-strip" style={{ display: "block" }}>
          <span className="gold">●</span>&nbsp;&nbsp;Template Demo · sample off-plan project · listings flow from the live feed in production
        </div>
      )}

      <window.Nav
        locale={locale}
        setLocale={setLocale}
        dark={navDark}
        onOpenRegister={() => setRegisterOpen(true)}
        onOpenLocale={() => setLocaleOpen(true)}
        localeOpen={localeOpen}
      />

      <window.LocaleMenu open={localeOpen} locale={locale} setLocale={setLocale} onClose={() => setLocaleOpen(false)} />

      <window.Hero
        L={L}
        variant={t.hero}
        onOpenRegister={() => setRegisterOpen(true)}
      />

      <window.Overview L={L} />
      <window.Bridge L={L} />
      <window.Design L={L} />
      <window.Residences L={L} />
      <window.Amenities L={L} />
      <window.Location L={L} />
      <window.Gallery L={L} />
      <window.Trust L={L} />
      <window.AgentCard L={L} />
      <window.CTASection L={L} />
      <window.Footer L={L} />

      <window.WhatsAppFAB L={L} show={t.showWA} />
      <window.RegisterModal open={registerOpen} onClose={() => setRegisterOpen(false)} L={L} />

      <TweaksPanel title="Tweaks">
        <TweakSection label="Language" />
        <TweakSelect
          label="Locale"
          value={locale}
          options={[
            { value: "en", label: "EN · English" },
            { value: "ar", label: "AR · العربية (RTL)" },
            { value: "de", label: "DE · Deutsch" },
            { value: "ru", label: "RU · Русский" },
            { value: "zh", label: "ZH · 中文" },
          ]}
          onChange={(v) => setLocale(v)}
        />

        <TweakSection label="Palette" />
        <TweakColor
          label="Brand"
          value={(window.TWEAK_PALETTES.find((p) => p.id === t.paletteId) || window.TWEAK_PALETTES[0]).swatches}
          options={window.TWEAK_PALETTES.map((p) => p.swatches)}
          onChange={(v) => {
            const found = window.TWEAK_PALETTES.find((p) => p.swatches.join() === v.join());
            if (found) {
              setTweak({ palette: v, paletteId: found.id });
            }
          }}
        />
        <div style={{ fontSize: 10.5, color: "rgba(41,38,27,0.55)", lineHeight: 1.5, marginTop: -4 }}>
          Default is brand-verified ink-indigo (<code>#171144</code>) from the logo SVG.
          Marine was the brief's placeholder; sand & stone are sector-friendly alternatives.
        </div>

        <TweakSection label="Layout" />
        <TweakRadio
          label="Hero"
          value={t.hero}
          options={["cinematic", "split", "muted"]}
          onChange={(v) => setTweak("hero", v)}
        />
        <TweakRadio
          label="Density"
          value={t.density}
          options={["compact", "regular", "cinematic"]}
          onChange={(v) => setTweak("density", v)}
        />

        <TweakSection label="Surfaces" />
        <TweakToggle
          label="WhatsApp FAB"
          value={t.showWA}
          onChange={(v) => setTweak("showWA", v)}
        />
        <TweakToggle
          label="Template demo strip"
          value={t.showDemoStrip}
          onChange={(v) => setTweak("showDemoStrip", v)}
        />
      </TweaksPanel>
    </div>
  );
}

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<App />);
