/* TDD — root app + Tweaks integration */

const { useState: useSt, useEffect: useEf, useRef: useRf } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "palette": "brass-moss",
  "displayFont": "Cormorant Garamond",
  "audience": "trade",
  "heroImage": "orange",
  "density": "editorial"
}/*EDITMODE-END*/;

const PALETTES = {
  "brass-moss": {
    name: "Brass + Moss",
    swatches: ["#9A7A3E", "#38483A", "#B25A66"],
    vars: { "--brass": "#9A7A3E", "--brass-deep": "#6F5828", "--moss": "#38483A", "--rose": "#B25A66" },
  },
  "teal-rose": {
    name: "Teal + Rose",
    swatches: ["#2E6E6A", "#234B49", "#B65C6A"],
    vars: { "--brass": "#2E6E6A", "--brass-deep": "#234B49", "--moss": "#3A2F36", "--rose": "#B65C6A" },
  },
  "terracotta-sage": {
    name: "Terracotta + Sage",
    swatches: ["#B86A4A", "#5B6B52", "#C09553"],
    vars: { "--brass": "#B86A4A", "--brass-deep": "#8A4D32", "--moss": "#3F4D38", "--rose": "#C09553" },
  },
  "ink-cream": {
    name: "Ink + Cream",
    swatches: ["#2A2620", "#6E6253", "#B25A66"],
    vars: { "--brass": "#6E6253", "--brass-deep": "#3A332B", "--moss": "#26221C", "--rose": "#B25A66" },
  },
};

const FONT_OPTIONS = [
  { key: "Cormorant Garamond", label: "Cormorant" },
  { key: "Fraunces", label: "Fraunces" },
  { key: "Playfair Display", label: "Playfair" },
];

function TweaksPanel({ tweaks, setTweak, onClose }) {
  return (
    <div className="tweaks-overlay">
      <div className="tweaks-head">
        Tweaks
        <button className="tweaks-close" onClick={onClose} aria-label="close">×</button>
      </div>
      <div className="tweaks-body">
        <div className="grp">
          <div className="ttl">Palette</div>
          <div className="row two">
            {Object.entries(PALETTES).map(([k, p]) => (
              <button key={k} className={"opt " + (tweaks.palette === k ? "on" : "")} onClick={() => setTweak("palette", k)}>
                <span className="sw" style={{ background: p.swatches[0] }}></span>{p.name}
              </button>
            ))}
          </div>
        </div>
        <div className="grp">
          <div className="ttl">Display font</div>
          <div className="row">
            {FONT_OPTIONS.map(f => (
              <button key={f.key} className={"opt " + (tweaks.displayFont === f.key ? "on" : "")} onClick={() => setTweak("displayFont", f.key)} style={{ fontFamily: f.key }}>
                {f.label}
              </button>
            ))}
          </div>
        </div>
        <div className="grp">
          <div className="ttl">Audience-first copy</div>
          <div className="row two">
            <button className={"opt " + (tweaks.audience === "trade" ? "on" : "")} onClick={() => setTweak("audience", "trade")}>Trade</button>
            <button className={"opt " + (tweaks.audience === "private" ? "on" : "")} onClick={() => setTweak("audience", "private")}>Private</button>
          </div>
        </div>
        <div className="grp">
          <div className="ttl">Hero scene</div>
          <div className="row four">
            <button className={"opt " + (tweaks.heroImage === "orange" ? "on" : "")} onClick={() => setTweak("heroImage", "orange")}>Velvet</button>
            <button className={"opt " + (tweaks.heroImage === "greenery" ? "on" : "")} onClick={() => setTweak("heroImage", "greenery")}>Botanical</button>
            <button className={"opt " + (tweaks.heroImage === "yellow" ? "on" : "")} onClick={() => setTweak("heroImage", "yellow")}>Mustard</button>
            <button className={"opt " + (tweaks.heroImage === "dining" ? "on" : "")} onClick={() => setTweak("heroImage", "dining")}>Dining</button>
          </div>
        </div>
        <div className="grp">
          <div className="ttl">Density</div>
          <div className="row two">
            <button className={"opt " + (tweaks.density === "editorial" ? "on" : "")} onClick={() => setTweak("density", "editorial")}>Editorial</button>
            <button className={"opt " + (tweaks.density === "compact" ? "on" : "")} onClick={() => setTweak("density", "compact")}>Compact</button>
          </div>
        </div>
      </div>
    </div>
  );
}

function App() {
  const [route, setRoute] = useSt("home");
  const [brandSlug, setBrandSlug] = useSt(null);
  const [locale, setLocale] = useSt("en");
  const [tweaks, setTweaks] = useSt(TWEAK_DEFAULTS);
  const [tweaksOpen, setTweaksOpen] = useSt(false);

  const dir = locale === "ar" ? "rtl" : "ltr";

  // Sync palette + font + density to CSS vars
  useEf(() => {
    const p = PALETTES[tweaks.palette] || PALETTES["brass-moss"];
    Object.entries(p.vars).forEach(([k, v]) => document.documentElement.style.setProperty(k, v));
    document.documentElement.style.setProperty("--serif", `"${tweaks.displayFont}", "EB Garamond", Georgia, serif`);
    document.documentElement.setAttribute("dir", dir);
    document.body.style.fontFamily = locale === "ar" ? "var(--arabic)" : "var(--sans)";
    // Density
    if (tweaks.density === "compact") {
      document.documentElement.style.setProperty("--section-y", "70px");
    } else {
      document.documentElement.style.setProperty("--section-y", "110px");
    }
  }, [tweaks, locale, dir]);

  // Edit mode protocol (Tweaks)
  useEf(() => {
    function onMsg(e) {
      if (!e.data || typeof e.data !== "object") return;
      if (e.data.type === "__activate_edit_mode") setTweaksOpen(true);
      if (e.data.type === "__deactivate_edit_mode") setTweaksOpen(false);
    }
    window.addEventListener("message", onMsg);
    window.parent.postMessage({ type: "__edit_mode_available" }, "*");
    return () => window.removeEventListener("message", onMsg);
  }, []);

  function setTweak(k, v) {
    setTweaks(t => {
      const next = { ...t, [k]: v };
      window.parent.postMessage({ type: "__edit_mode_set_keys", edits: { [k]: v } }, "*");
      return next;
    });
  }

  function navigate(r) {
    setRoute(r);
    setBrandSlug(null);
    window.scrollTo({ top: 0, behavior: "smooth" });
  }
  function openBrand(slug) {
    setBrandSlug(slug);
    setRoute("brand");
    window.scrollTo({ top: 0, behavior: "smooth" });
  }
  function closeTweaks() {
    setTweaksOpen(false);
    window.parent.postMessage({ type: "__edit_mode_dismissed" }, "*");
  }

  const audience = tweaks.audience;
  const setAudience = (a) => setTweak("audience", a);

  let page;
  if (route === "home") page = <HomePage onNavigate={navigate} openBrand={openBrand} audience={audience} heroImage={tweaks.heroImage} />;
  else if (route === "brands") page = <BrandsPage openBrand={openBrand} />;
  else if (route === "brand") page = <BrandDetail slug={brandSlug} onNavigate={navigate} openBrand={openBrand} />;
  else if (route === "materials") page = <MaterialsPage onNavigate={navigate} openBrand={openBrand} />;
  else if (route === "studio") page = <StudioPage onNavigate={navigate} onBook={() => navigate("contact")} />;
  else if (route === "about") page = <AboutPage onNavigate={navigate} />;
  else if (route === "contact") page = <ContactPage audience={audience} setAudience={setAudience} preferredTab="visit" />;

  return (
    <>
      <ScrollProgress />
      <Nav route={route} onNavigate={navigate} locale={locale} setLocale={setLocale} dir={dir} />
      {page}
      <Footer onNavigate={navigate} />
      {tweaksOpen && <TweaksPanel tweaks={tweaks} setTweak={setTweak} onClose={closeTweaks} />}
    </>
  );
}

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