// =========================================================
// Main App — router + tweaks panel + shell
// =========================================================

const DEFAULTS = /*EDITMODE-BEGIN*/{
  "theme": "light",
  "fontPair": "editorial",
  "accent": "#D08540",
  "heroLayout": "split",
  "cardStyle": "bordered"
}/*EDITMODE-END*/;

const FONT_PAIRS = {
  editorial: { display: '"DM Serif Display", Georgia, serif', body: '"Manrope", system-ui, sans-serif' },
  modern:    { display: '"Cormorant Garamond", Georgia, serif', body: '"DM Sans", system-ui, sans-serif' },
  classic:   { display: '"Spectral", Georgia, serif', body: '"Libre Franklin", system-ui, sans-serif' },
};

const ACCENT_SWATCHES = ["#D08540", "#3F6F9C", "#467D52", "#B65463"];

function App() {
  const [route, setRoute] = React.useState({ name: "home" });
  const [cartOpen, setCartOpen] = React.useState(false);
  const [loginOpen, setLoginOpen] = React.useState(false);
  const [toast, setToast] = React.useState(null);
  const [lastOrder, setLastOrder] = React.useState(null);

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

  React.useEffect(() => { seedDemoOrdersIfEmpty(); }, []);

  // Apply theme + fonts + accent
  React.useEffect(() => {
    document.documentElement.setAttribute("data-theme", t.theme || "light");
    const pair = FONT_PAIRS[t.fontPair] || FONT_PAIRS.editorial;
    document.documentElement.style.setProperty("--font-display", pair.display);
    document.documentElement.style.setProperty("--font-body", pair.body);
    document.documentElement.style.setProperty("--accent", t.accent || "#D08540");
  }, [t.theme, t.fontPair, t.accent]);

  const navigate = (next) => {
    setRoute(next);
    window.scrollTo({ top: 0, behavior: "instant" });
  };

  const handleAdd = (product, qty = 1) => {
    addToCart(product.id, qty);
    setToast(`Added ${product.name}`);
  };

  const onLoginNeeded = () => setLoginOpen(true);

  const onPlaced = (order) => {
    setLastOrder(order);
    navigate({ name: "confirmation" });
  };

  return (
    <div className={"app card-style-" + (t.cardStyle || "bordered") + " hero-layout-" + (t.heroLayout || "split")}>
      <SiteHeader
        route={route}
        navigate={navigate}
        openCart={() => setCartOpen(true)}
        openLogin={() => setLoginOpen(true)}
      />

      {route.name === "home"      && <HomePage navigate={navigate} onAdd={handleAdd} heroLayout={t.heroLayout} />}
      {route.name === "category"  && <CategoryPage catId={route.id} navigate={navigate} onAdd={handleAdd} />}
      {route.name === "product"   && <ProductPage id={route.id} navigate={navigate} onAdd={handleAdd} />}
      {route.name === "checkout"  && <CheckoutPage navigate={navigate} onLoginNeeded={onLoginNeeded} onPlaced={onPlaced} />}
      {route.name === "confirmation" && <ConfirmationPage order={lastOrder} navigate={navigate} />}
      {route.name === "account"   && <AccountPage navigate={navigate} onLoginNeeded={onLoginNeeded} />}
      {route.name === "admin"     && <AdminPage navigate={navigate} />}
      {route.name === "about"     && <AboutPage navigate={navigate} />}

      <SiteFooter navigate={navigate} />

      <CartDrawer open={cartOpen} onClose={() => setCartOpen(false)} navigate={navigate} />
      <LoginModal open={loginOpen} onClose={() => setLoginOpen(false)} onSuccess={() => { setLoginOpen(false); setToast("Signed in"); }} />

      <Toast message={toast} onDone={() => setToast(null)} />

      <TweaksPanel title="Tweaks">
        <TweakSection label="Theme">
          <TweakRadio
            label="Mode"
            value={t.theme}
            onChange={v => setTweak("theme", v)}
            options={[{ value: "light", label: "Light" }, { value: "dark", label: "Dark" }]}
          />
          <TweakColor
            label="Accent"
            value={t.accent}
            onChange={v => setTweak("accent", v)}
            options={ACCENT_SWATCHES}
          />
        </TweakSection>

        <TweakSection label="Typography">
          <TweakSelect
            label="Font pair"
            value={t.fontPair}
            onChange={v => setTweak("fontPair", v)}
            options={[
              { value: "editorial", label: "DM Serif + Manrope" },
              { value: "modern",    label: "Cormorant + DM Sans" },
              { value: "classic",   label: "Spectral + Libre Franklin" },
            ]}
          />
        </TweakSection>

        <TweakSection label="Hero layout">
          <TweakRadio
            label="Style"
            value={t.heroLayout}
            onChange={v => setTweak("heroLayout", v)}
            options={[
              { value: "split",   label: "Split" },
              { value: "marquee", label: "Marquee" },
            ]}
          />
        </TweakSection>

        <TweakSection label="Product card">
          <TweakSelect
            label="Card style"
            value={t.cardStyle}
            onChange={v => setTweak("cardStyle", v)}
            options={[
              { value: "bordered", label: "Bordered (default)" },
              { value: "minimal",  label: "Minimal · no border" },
              { value: "postcard", label: "Postcard · padded" },
            ]}
          />
        </TweakSection>

        <TweakSection label="Demo data">
          <TweakButton
            label="Reset all data"
            secondary
            onClick={() => {
              if (confirm("Clear all orders, cart and user data? This resets the prototype.")) {
                localStorage.removeItem(STORE_KEY);
                location.reload();
              }
            }}
          />
        </TweakSection>
      </TweaksPanel>
    </div>
  );
}

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