/* global React, ReactDOM, useLenis, Cursor, Header, CartDrawer, SearchOverlay,
   HomePage, PLPPage, PDPPage, CartPage, CheckoutPage, OrderPage,
   SignInPage, AccountPage, JournalPage, JournalArticlePage, AtelierPage,
   ShowroomsPage, TradePage, CustomPage, HelpPage, SustainabilityPage, ContactPage, NotFoundPage,
   useTweaks, TweaksPanel, TweakSection, TweakRadio, TweakColor, useStore, Store */
const { useState: useState_app, useEffect: useEffect_app, useRef: useRef_app } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accent": "#5C1F1A",
  "motion": "full",
  "neutral": "warm"
}/*EDITMODE-END*/;

const ACCENT_OPTIONS = ["#5C1F1A", "#1F3A2E", "#2A3F5C", "#C25A1F", "#161311"];

const VALID_ROUTES = new Set([
  "home", "plp", "pdp",
  "cart", "checkout", "order",
  "signin", "account",
  "journal", "journal-article",
  "atelier", "showrooms", "trade", "custom",
  "help", "sustainability", "contact",
  "notfound",
]);

const DARK_HERO_ROUTES = new Set(["home", "atelier", "sustainability", "custom"]);

function App() {
  const [route, setRoute] = useState_app(() => {
    const r = location.hash.replace("#", "") || "home";
    return VALID_ROUTES.has(r) ? r : "notfound";
  });
  const [veil, setVeil] = useState_app(false);
  const veilTimerRef = useRef_app(null);

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

  /* Smooth scroll */
  useLenis(true);

  /* Sync route with hash */
  useEffect_app(() => {
    const onHash = () => {
      const r = location.hash.replace("#", "") || "home";
      setRoute(VALID_ROUTES.has(r) ? r : "notfound");
    };
    window.addEventListener("hashchange", onHash);
    return () => window.removeEventListener("hashchange", onHash);
  }, []);

  /* Apply tweak vars */
  useEffect_app(() => {
    const root = document.documentElement;
    root.style.setProperty("--accent", t.accent || "#5C1F1A");
    if (t.neutral === "cool") {
      root.style.setProperty("--bone", "#EFEEEA");
      root.style.setProperty("--bone-warm", "#E6E5E0");
      root.style.setProperty("--bone-deep", "#D8D7D2");
    } else {
      root.style.setProperty("--bone", "#F2EBE0");
      root.style.setProperty("--bone-warm", "#ECE3D3");
      root.style.setProperty("--bone-deep", "#E2D6C0");
    }
    document.body.classList.toggle("motion-off", t.motion === "off");
  }, [t.accent, t.neutral, t.motion]);

  /* Navigate with veil transition */
  const navigate = (newRoute) => {
    if (!VALID_ROUTES.has(newRoute)) newRoute = "notfound";
    if (newRoute === route) return;
    setVeil(true);
    /* Close drawers if open */
    Store.setUI({ cartOpen: false, searchOpen: false });
    clearTimeout(veilTimerRef.current);
    veilTimerRef.current = setTimeout(() => {
      location.hash = newRoute;
      setRoute(newRoute);
      window.scrollTo(0, 0);
      if (window.__lenis) window.__lenis.scrollTo(0, { immediate: true });
      setTimeout(() => setVeil(false), 80);
    }, 220);
  };

  const headerDark = DARK_HERO_ROUTES.has(route);

  return (
    <React.Fragment>
      <Cursor />
      <div className={`veil ${veil ? "is-active" : ""}`} aria-hidden="true"></div>

      <Header route={route} onNavigate={navigate} dark={headerDark} />

      {route === "home" && <HomePage onNavigate={navigate} />}
      {route === "plp" && <PLPPage onNavigate={navigate} />}
      {route === "pdp" && <PDPPage onNavigate={navigate} />}
      {route === "cart" && <CartPage onNavigate={navigate} />}
      {route === "checkout" && <CheckoutPage onNavigate={navigate} />}
      {route === "order" && <OrderPage onNavigate={navigate} />}
      {route === "signin" && <SignInPage onNavigate={navigate} />}
      {route === "account" && <AccountPage onNavigate={navigate} />}
      {route === "journal" && <JournalPage onNavigate={navigate} />}
      {route === "journal-article" && <JournalArticlePage onNavigate={navigate} />}
      {route === "atelier" && <AtelierPage onNavigate={navigate} />}
      {route === "showrooms" && <ShowroomsPage onNavigate={navigate} />}
      {route === "trade" && <TradePage onNavigate={navigate} />}
      {route === "custom" && <CustomPage onNavigate={navigate} />}
      {route === "help" && <HelpPage onNavigate={navigate} />}
      {route === "sustainability" && <SustainabilityPage onNavigate={navigate} />}
      {route === "contact" && <ContactPage onNavigate={navigate} />}
      {route === "notfound" && <NotFoundPage onNavigate={navigate} />}

      <CartDrawer onCheckout={() => navigate("checkout")} />
      <SearchOverlay onNavigate={navigate} />

      <TweaksPanel title="Tweaks">
        <TweakSection label="Brand signature" />
        <TweakColor
          label="Accent color"
          value={t.accent}
          options={ACCENT_OPTIONS}
          onChange={(v) => setTweak("accent", v)}
        />
        <TweakSection label="System" />
        <TweakRadio
          label="Neutral tone"
          value={t.neutral}
          options={[
            { value: "warm", label: "Warm bone" },
            { value: "cool", label: "Cool linen" },
          ]}
          onChange={(v) => setTweak("neutral", v)}
        />
        <TweakRadio
          label="Motion"
          value={t.motion}
          options={[
            { value: "full", label: "Full" },
            { value: "off", label: "Off" },
          ]}
          onChange={(v) => setTweak("motion", v)}
        />
        <TweakSection label="Jump to" />
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 6 }}>
          {[
            ["home", "Home"],
            ["plp", "Catalog"],
            ["pdp", "Sofa PDP"],
            ["cart", "Cart"],
            ["checkout", "Checkout"],
            ["order", "Order ✓"],
            ["signin", "Sign in"],
            ["account", "Account"],
            ["journal", "Journal"],
            ["journal-article", "Article"],
            ["atelier", "Atelier"],
            ["showrooms", "Showrooms"],
            ["trade", "Trade"],
            ["custom", "Custom"],
            ["help", "Help/FAQ"],
            ["sustainability", "Sustain."],
            ["contact", "Contact"],
            ["notfound", "404"],
          ].map(([r, l]) => (
            <button
              key={r}
              onClick={() => navigate(r)}
              style={{
                padding: "6px 10px",
                border: "1px solid currentColor",
                borderRadius: 4,
                fontFamily: "DM Mono, monospace",
                fontSize: 10,
                letterSpacing: "0.12em",
                textTransform: "uppercase",
                background: r === route ? "rgba(41,38,27,0.9)" : "transparent",
                color: r === route ? "#F2EBE0" : "inherit",
                cursor: "pointer",
                textAlign: "left",
              }}
            >{l}</button>
          ))}
        </div>
      </TweaksPanel>
    </React.Fragment>
  );
}

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