// ============================================================
// Aartisan — app entry point: router, tweaks
// ============================================================

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "density": "airy",
  "theme": "paper",
  "headerStyle": "sticky",
  "heroVariant": "v1",
  "heroTitleId": "made-simple"
}/*EDITMODE-END*/;

// Route ↔ URL slug mapping
const SLUG_TO_ROUTE = {
  "/":              "home",
  "/build":         "build",
  "/cases":         "cases",
  "/about":         "about",
  "/faq":           "faq",
  "/privacy":       "privacy",
};
function routeToSlug(route) {
  if (route.startsWith("case:")) return "/cases/" + route.split(":")[1];
  const map = { home: "/", build: "/build", cases: "/cases", about: "/about", faq: "/faq", privacy: "/privacy" };
  return map[route] || "/";
}
function slugToRoute(pathname) {
  if (pathname.startsWith("/cases/")) return "case:" + pathname.replace("/cases/", "");
  return SLUG_TO_ROUTE[pathname] || "home";
}

function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);

  const [route, setRoute] = React.useState(() => slugToRoute(window.location.pathname));
  const [builderInitial, setBuilderInitial] = React.useState(null);

  // Apply theme + density via root classes/styles
  React.useEffect(() => {
    const html = document.documentElement;
    html.classList.remove("theme-plum", "theme-blush");
    if (t.theme === "plum") html.classList.add("theme-plum");
    if (t.theme === "blush") html.classList.add("theme-blush");
    html.style.setProperty("--density", t.density === "packed" ? "0.65" : "1");
  }, [t.theme, t.density]);

  // Sync URL → route on browser back/forward
  React.useEffect(() => {
    const onPop = () => setRoute(slugToRoute(window.location.pathname));
    window.addEventListener("popstate", onPop);
    return () => window.removeEventListener("popstate", onPop);
  }, []);

  // Scroll to top on route change
  React.useEffect(() => {
    window.scrollTo({ top: 0, behavior: "instant" in document.documentElement ? "instant" : "auto" });
  }, [route]);

  const navigate = (target, extra) => {
    if (target === "build" && extra) setBuilderInitial(extra);
    else if (target === "build") setBuilderInitial(null);
    const slug = routeToSlug(target);
    window.history.pushState(null, "", slug);
    setRoute(target);
  };

  const renderScreen = () => {
    if (route.startsWith("case:")) {
      const id = route.split(":")[1];
      return <CaseDetailScreen id={id} onNav={navigate} />;
    }
    switch (route) {
      case "home":     return <HomeScreen onNav={navigate} heroVariant={t.heroVariant} heroTitleId={t.heroTitleId} />;
      case "build":    return <BuilderScreen initialConfig={builderInitial} onNav={navigate} />;
      case "cases":    return <CasesScreen onNav={navigate} />;
      case "about":    return <AboutScreen onNav={navigate} />;
      case "faq":      return <FAQScreen onNav={navigate} />;
      case "privacy":  return <PrivacyScreen />;
      default:         return <HomeScreen onNav={navigate} heroVariant={t.heroVariant} heroTitleId={t.heroTitleId} />;
    }
  };

  const currentNavId = (() => {
    if (route.startsWith("case:")) return "cases";
    return route;
  })();

  return (
    <div className="aartisan-root">
      <SvgDefs />
      <Header
        current={currentNavId}
        onNav={navigate}
        headerStyle={t.headerStyle}
      />
      <main>{renderScreen()}</main>
      <Footer onNav={navigate} />

      <TweaksPanel title="Tweaks">
        <TweakSection label="Color theme">
          <TweakRadio
            label="Theme"
            value={t.theme}
            options={[
              { value: "paper", label: "Paper" },
              { value: "blush", label: "Blush" },
              { value: "plum",  label: "Plum" },
            ]}
            onChange={(v) => setTweak("theme", v)}
          />
        </TweakSection>
        <TweakSection label="Density">
          <TweakRadio
            label="Spacing"
            value={t.density}
            options={[
              { value: "airy",   label: "Airy" },
              { value: "packed", label: "Packed" },
            ]}
            onChange={(v) => setTweak("density", v)}
          />
        </TweakSection>
        <TweakSection label="Header style">
          <TweakRadio
            label="Header"
            value={t.headerStyle}
            options={[
              { value: "sticky", label: "Sticky" },
              { value: "float",  label: "Float" },
            ]}
            onChange={(v) => setTweak("headerStyle", v)}
          />
        </TweakSection>
        <TweakSection label="Hero variant (home page)">
          <TweakRadio
            label="Hero"
            value={t.heroVariant}
            options={[
              { value: "v1", label: "Forwarding card" },
              { value: "v2", label: "Marquee" },
            ]}
            onChange={(v) => setTweak("heroVariant", v)}
          />
        </TweakSection>
        <TweakSection label="Hero headline (forwarding card)">
          <TweakSelect
            label="Headline"
            value={t.heroTitleId}
            options={HERO_TITLES.map(h => ({
              value: h.id,
              label: h.lines.join(" "),
            }))}
            onChange={(v) => setTweak("heroTitleId", v)}
          />
          <div style={{ fontSize: 11, color: "var(--fg-3)", marginTop: 8, lineHeight: 1.4 }}>
            Italic accent picks which line gets the GT Proelium Sharp treatment.
          </div>
        </TweakSection>
        <TweakSection label="Quick jump">
          <TweakButton label="Home"        onClick={() => navigate("home")} />
          <TweakButton label="Build"       onClick={() => navigate("build")} secondary />
          <TweakButton label="Case detail" onClick={() => setRoute("case:portawell")} secondary />
        </TweakSection>
      </TweaksPanel>
    </div>
  );
}

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