// App + router + tweaks for Hessa Falasi prototype
const { useState: useStateA, useEffect: useEffectA, useCallback } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accent": "#B08D57",
  "background": "ivory",
  "displayFont": "Cormorant Garamond",
  "density": "comfortable"
}/*EDITMODE-END*/;

function parseRoute(hash) {
  const raw = (hash || "").replace(/^#/, "") || "/";
  const seg = raw.split("/").filter(Boolean);
  if (seg.length === 0) return { path: "/", page: "home" };
  if (seg[0] === "collections") return { path: "/collections", page: "collections" };
  if (seg[0] === "collection" && seg[1]) return { path: "/collection/"+seg[1], page: "collection", slug: seg[1] };
  if (seg[0] === "product" && seg[1]) return { path: "/product/"+seg[1], page: "product", handle: seg[1] };
  if (seg[0] === "the-house") return { path: "/the-house", page: "house" };
  if (seg[0] === "press") return { path: "/press", page: "press" };
  if (seg[0] === "appointments") return { path: "/appointments", page: "appointments" };
  if (seg[0] === "visit") return { path: "/visit", page: "visit" };
  if (seg[0] === "size-guide") return { path: "/size-guide", page: "size" };
  return { path: "/", page: "home" };
}

function App() {
  const [route, setRoute] = useStateA(() => parseRoute(window.location.hash));
  const [locale, setLocale] = useStateA(() => {
    try { return localStorage.getItem("hf-locale") || "en"; } catch (e) { return "en"; }
  });
  const [toast, setToast] = useStateA(null);
  const [tweaks, setTweaks] = useStateA(TWEAK_DEFAULTS);
  const [tweaksOpen, setTweaksOpen] = useStateA(false);

  // Hash router
  useEffectA(() => {
    const onHash = () => {
      setRoute(parseRoute(window.location.hash));
      window.scrollTo({ top: 0, behavior: "instant" });
    };
    window.addEventListener("hashchange", onHash);
    return () => window.removeEventListener("hashchange", onHash);
  }, []);

  // Locale persistence + html lang/dir
  useEffectA(() => {
    document.documentElement.lang = locale;
    document.documentElement.dir = locale === "ar" ? "rtl" : "ltr";
    try { localStorage.setItem("hf-locale", locale); } catch (e) {}
  }, [locale]);

  // Tweaks: apply CSS vars
  useEffectA(() => {
    const root = document.documentElement;
    root.style.setProperty("--gold", tweaks.accent);
    root.style.setProperty("--serif", `"${tweaks.displayFont}", "Times New Roman", serif`);
    if (tweaks.background === "bone") {
      root.style.setProperty("--ivory", "#F4EFE7");
    } else if (tweaks.background === "sand") {
      root.style.setProperty("--ivory", "#EDE3D2");
    } else {
      root.style.setProperty("--ivory", "#FBF8F2");
    }
    // Density: adjust container padding via inline override
    if (tweaks.density === "compact") {
      root.style.setProperty("--pad-x", "clamp(16px, 3vw, 36px)");
    } else if (tweaks.density === "spacious") {
      root.style.setProperty("--pad-x", "clamp(28px, 6vw, 96px)");
    } else {
      root.style.setProperty("--pad-x", "clamp(20px, 4vw, 56px)");
    }
  }, [tweaks]);

  // Tweaks integration with host toolbar
  useEffectA(() => {
    const onMsg = (e) => {
      const d = e.data;
      if (!d || typeof d !== "object") return;
      if (d.type === "__activate_edit_mode") setTweaksOpen(true);
      else if (d.type === "__deactivate_edit_mode") setTweaksOpen(false);
    };
    window.addEventListener("message", onMsg);
    try { window.parent.postMessage({ type: "__edit_mode_available" }, "*"); } catch (e) {}
    return () => window.removeEventListener("message", onMsg);
  }, []);

  const navigate = useCallback((href) => { window.location.hash = href.replace(/^#/, ""); }, []);
  const showToast = useCallback((msg) => setToast(msg), []);

  const setTweak = (key, value) => {
    setTweaks(prev => {
      const next = { ...prev, [key]: value };
      try { window.parent.postMessage({ type: "__edit_mode_set_keys", edits: { [key]: value } }, "*"); } catch (e) {}
      return next;
    });
  };

  const closeTweaks = () => {
    setTweaksOpen(false);
    try { window.parent.postMessage({ type: "__edit_mode_dismissed" }, "*"); } catch (e) {}
  };

  const dark = false; // nav stays light; hero is dark anyway

  let page;
  switch (route.page) {
    case "home":        page = <HomePage locale={locale} navigate={navigate} showToast={showToast} />; break;
    case "collections": page = <CollectionsHubPage locale={locale} navigate={navigate} />; break;
    case "collection":  page = <CollectionDetailPage slug={route.slug} locale={locale} navigate={navigate} />; break;
    case "product":     page = <ProductPage handle={route.handle} locale={locale} navigate={navigate} showToast={showToast} />; break;
    case "house":       page = <HousePage locale={locale} navigate={navigate} />; break;
    case "press":       page = <PressPage locale={locale} />; break;
    case "appointments":page = <AppointmentsPage locale={locale} showToast={showToast} />; break;
    case "visit":       page = <VisitPage locale={locale} />; break;
    case "size":        page = <SizeGuidePage locale={locale} />; break;
    default:            page = <HomePage locale={locale} navigate={navigate} showToast={showToast} />;
  }

  return (
    <>
      <Navbar route={route} locale={locale} setLocale={setLocale} navigate={navigate} dark={dark} />
      {page}
      <Footer locale={locale} />
      <WhatsAppFab locale={locale} />
      <Toast message={toast} onDone={() => setToast(null)} />
      {tweaksOpen ? <TweaksPanel tweaks={tweaks} setTweak={setTweak} onClose={closeTweaks} /> : null}
    </>
  );
}

// ----- Tweaks panel -----
function TweaksPanel({ tweaks, setTweak, onClose }) {
  return (
    <div style={{
      position:"fixed", right:18, bottom:78, zIndex:75,
      width:300, background:"var(--ivory)", border:"1px solid var(--line-strong)",
      boxShadow:"0 18px 50px rgba(14,13,11,.16)", padding:18,
    }}>
      <div style={{display:"flex",justifyContent:"space-between",alignItems:"center",borderBottom:"1px solid var(--line)",paddingBottom:10,marginBottom:14}}>
        <span className="eyebrow" style={{color:"var(--gold)"}}>Tweaks</span>
        <button onClick={onClose} className="nav-link" style={{fontSize:11}}>Close</button>
      </div>

      <TweakSection label="Accent thread">
        <SwatchRow value={tweaks.accent} onChange={(v)=>setTweak("accent",v)} options={[
          "#B08D57", // gold
          "#9C7E4F", // bronze
          "#7E1D2B", // henna
          "#21433A", // deep emerald
          "#3C5A6E"  // ink blue
        ]}/>
      </TweakSection>

      <TweakSection label="Paper">
        <SegRow value={tweaks.background} onChange={(v)=>setTweak("background",v)} options={[
          {v:"ivory", l:"Ivory"},
          {v:"bone", l:"Bone"},
          {v:"sand", l:"Sand"}
        ]}/>
      </TweakSection>

      <TweakSection label="Display type">
        <SegRow value={tweaks.displayFont} onChange={(v)=>setTweak("displayFont",v)} options={[
          {v:"Cormorant Garamond", l:"Cormorant"},
          {v:"Tajawal", l:"Tajawal"}
        ]}/>
      </TweakSection>

      <TweakSection label="Density">
        <SegRow value={tweaks.density} onChange={(v)=>setTweak("density",v)} options={[
          {v:"compact",l:"Compact"},
          {v:"comfortable",l:"Default"},
          {v:"spacious",l:"Spacious"}
        ]}/>
      </TweakSection>
    </div>
  );
}

function TweakSection({ label, children }) {
  return (
    <div style={{marginBottom:14}}>
      <div className="eyebrow" style={{marginBottom:8,color:"var(--muted)"}}>{label}</div>
      {children}
    </div>
  );
}

function SwatchRow({ value, onChange, options }) {
  return (
    <div style={{display:"flex",gap:8}}>
      {options.map(c => (
        <button key={c} onClick={()=>onChange(c)} style={{
          width:32, height:32, borderRadius:"50%", background:c,
          border: value===c ? "2px solid var(--ink)" : "1px solid var(--line-strong)",
          padding:0, cursor:"pointer", outlineOffset:2
        }} aria-label={c}/>
      ))}
    </div>
  );
}

function SegRow({ value, onChange, options }) {
  return (
    <div style={{display:"grid",gridTemplateColumns:`repeat(${options.length},1fr)`,border:"1px solid var(--line-strong)"}}>
      {options.map((o,i) => (
        <button key={o.v}
          onClick={()=>onChange(o.v)}
          style={{
            padding:"9px 6px",
            background: value===o.v ? "var(--ink)" : "transparent",
            color: value===o.v ? "var(--ivory)" : "var(--ink)",
            border:0, borderInlineEnd: i<options.length-1 ? "1px solid var(--line-strong)" : "0",
            fontSize:10, letterSpacing:".14em", textTransform:"uppercase", fontWeight:500
          }}>{o.l}</button>
      ))}
    </div>
  );
}

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