/* VSHD Design — root app, hash router, tweak state */

const { useState: _u, useEffect: _e } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "palette": "white",
  "accent": "stone",
  "serifAccent": true,
  "heroPaceSec": 7,
  "rtlSample": false
}/*EDITMODE-END*/;

const PALETTE_VALUES = {
  white: { paper: "#FFFFFF", bone: "#F5F4F1", line: "#E5E3DE", ink: "#15161A", graphite: "#666766" },
  bone:  { paper: "#F5F4F1", bone: "#EAE7E0", line: "#D8D4CC", ink: "#1A1A1E", graphite: "#666766" },
  warm:  { paper: "#F2EEE6", bone: "#E8E2D5", line: "#D2CBBB", ink: "#262219", graphite: "#7A6E55" }
};

const ACCENT_VALUES = {
  none:  "#9A8C78",
  stone: "#9A8C78",
  clay:  "#A87E5E",
  ink:   "#15161A"
};

/* --- Hash router --- */
function useRoute() {
  const parseHash = () => {
    const h = window.location.hash || "#/";
    return h.replace(/^#\/?/, "");
  };
  const [route, setRoute] = _u(parseHash());
  _e(() => {
    const onHash = () => {
      setRoute(parseHash());
      window.scrollTo({ top: 0, behavior: "instant" });
    };
    window.addEventListener("hashchange", onHash);
    return () => window.removeEventListener("hashchange", onHash);
  }, []);
  const go = (to) => {
    window.location.hash = "#/" + to;
  };
  return [route, go];
}

function App() {
  const [route, go] = useRoute();
  const [enquiryOpen, setEnquiryOpen] = _u(false);
  const [lang, setLang] = _u("en");
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);

  // Apply palette + accent via inline <style> on :root
  _e(() => {
    const p = PALETTE_VALUES[t.palette] || PALETTE_VALUES.white;
    const a = ACCENT_VALUES[t.accent] || ACCENT_VALUES.stone;
    const root = document.documentElement;
    root.style.setProperty("--paper", p.paper);
    root.style.setProperty("--bone", p.bone);
    root.style.setProperty("--line", p.line);
    root.style.setProperty("--ink", p.ink);
    root.style.setProperty("--graphite", p.graphite);
    root.style.setProperty("--accent", a);
  }, [t.palette, t.accent]);

  // Toggle serif-accent off by neutralising em-italic
  _e(() => {
    const id = "vshd-serif-off";
    let st = document.getElementById(id);
    if (!t.serifAccent) {
      if (!st) {
        st = document.createElement("style");
        st.id = id;
        document.head.appendChild(st);
      }
      st.textContent = `
        .h-display em, .h-section em, .hero__title em, .cs-hero__title em,
        .footer__big em, .pillar__title em, .enquiry__h em,
        .cs-pullquote blockquote em, .cs-narrative__h em {
          font-family: var(--font-sans) !important;
          font-style: normal !important;
          font-weight: 200 !important;
        }
      `;
    } else if (st) {
      st.remove();
    }
  }, [t.serifAccent]);

  // RTL flip on the prototype
  _e(() => {
    document.documentElement.setAttribute("dir", (lang === "ar" && t.rtlSample) ? "rtl" : "ltr");
    document.documentElement.setAttribute("lang", lang === "ar" ? "ar" : "en");
  }, [lang, t.rtlSample]);

  // Parse route — supports plain pages, project/:slug, projects?s=Sector
  const parts = route.split("?");
  const pathParts = (parts[0] || "").split("/").filter(Boolean);
  const queryStr = parts[1] || "";
  const query = {};
  queryStr.split("&").filter(Boolean).forEach(kv => {
    const [k, v] = kv.split("=");
    query[k] = decodeURIComponent(v || "");
  });

  // Decide nav darkness (dark on hero-heavy pages, top of page)
  // Track scroll to flip nav from "dark on hero" to "light when scrolled past"
  const [pastHero, setPastHero] = _u(false);
  _e(() => {
    const onScroll = () => setPastHero(window.scrollY > 100);
    window.addEventListener("scroll", onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener("scroll", onScroll);
  }, [route]);

  const isHomeOrCs = pathParts[0] === undefined || pathParts[0] === "" || pathParts[0] === "project";
  const navDark = isHomeOrCs && !pastHero;

  let page;
  if (pathParts.length === 0 || pathParts[0] === "") {
    page = <Home go={go} onOpenEnquiry={() => setEnquiryOpen(true)} tweaks={t} />;
  } else if (pathParts[0] === "projects") {
    page = <Projects go={go} onOpenEnquiry={() => setEnquiryOpen(true)} initialSector={query.s} />;
  } else if (pathParts[0] === "project" && pathParts[1]) {
    page = <CaseStudy slug={pathParts[1]} go={go} onOpenEnquiry={() => setEnquiryOpen(true)} />;
  } else {
    // Stub pages for the rest of the IA
    const labels = {
      studio: ["Studio", "Founder & philosophy"],
      sectors: ["Sectors", "Six typologies"],
      awards: ["Awards", "Issuer, year, project"],
      press: ["Press", "As featured in"],
      contact: ["Contact", "Dubai · Montréal"],
      "join-us": ["Join us", "Careers"]
    };
    const [title, eyebrow] = labels[pathParts[0]] || ["Page", "—"];
    page = <Stub title={title} eyebrow={eyebrow} go={go} onOpenEnquiry={() => setEnquiryOpen(true)} />;
  }

  return (
    <>
      <Nav
        route={pathParts[0] || ""}
        go={go}
        dark={navDark}
        onOpenEnquiry={() => setEnquiryOpen(true)}
        lang={lang}
        setLang={setLang}
      />
      {page}
      <EnquiryPanel open={enquiryOpen} onClose={() => setEnquiryOpen(false)} />

      <TweaksPanel title="Tweaks · VSHD">
        <TweakSection label="Palette" />
        <TweakRadio
          label="Page tone"
          value={t.palette}
          options={["white", "bone", "warm"]}
          onChange={(v) => setTweak("palette", v)}
        />
        <TweakRadio
          label="Accent"
          value={t.accent}
          options={["none", "stone", "clay"]}
          onChange={(v) => setTweak("accent", v)}
        />

        <TweakSection label="Typography" />
        <TweakToggle
          label="Serif italic accents"
          value={t.serifAccent}
          onChange={(v) => setTweak("serifAccent", v)}
        />

        <TweakSection label="Motion" />
        <TweakSlider
          label="Hero pace"
          value={t.heroPaceSec}
          min={3} max={14} step={1} unit="s"
          onChange={(v) => setTweak("heroPaceSec", v)}
        />

        <TweakSection label="Language" />
        <TweakToggle
          label="RTL flip when AR"
          value={t.rtlSample}
          onChange={(v) => setTweak("rtlSample", v)}
        />
      </TweaksPanel>
    </>
  );
}

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