/* ============================================================
   LUMFELL — app shell: state, routing, tweaks
   ============================================================ */
const { CATEGORIES, PRODUCTS, TESTIMONIALS } = window.LumData;

/* Defaults live in index.html (the open page) so the Tweaks panel can persist
   your choices across reloads by rewriting that EDITMODE block. */
const TWEAK_DEFAULTS = window.LUM_TWEAK_DEFAULTS || {
  "theme": "light",
  "heroLayout": "split",
  "accent": "#B26A38",
  "serif": "'Bodoni Moda'",
};

/* reveal-on-scroll hook */
function useReveal(dep) {
  useEffect(() => {
    const els = document.querySelectorAll(".reveal:not(.is-in)");
    const io = new IntersectionObserver((ents) => {
      ents.forEach((e) => { if (e.isIntersecting) { e.target.classList.add("is-in"); io.unobserve(e.target); } });
    }, { threshold: 0.12, rootMargin: "0px 0px -8% 0px" });
    els.forEach((el) => io.observe(el));
    return () => io.disconnect();
  }, [dep]);
}

function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [page, setPage] = useState({ name: "home" });
  const [cart, setCart] = useState([]);
  const [cartOpen, setCartOpen] = useState(false);
  const [toasts, setToasts] = useState([]);
  const [solid, setSolid] = useState(false);

  useReveal(page.name + (page.product?.id || "") + (page.cat || ""));

  /* apply tweak vars */
  useEffect(() => {
    document.documentElement.style.setProperty("--cognac", t.accent);
    document.documentElement.style.setProperty("--serif", `${t.serif}, Georgia, serif`);
  }, [t.accent, t.serif]);

  /* theme (light default / dark) */
  useEffect(() => {
    document.body.setAttribute("data-theme", t.theme);
  }, [t.theme]);

  /* header solid on scroll */
  useEffect(() => {
    const onScroll = () => setSolid(window.scrollY > 70);
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  const cartCount = cart.reduce((s, i) => s + i.qty, 0);

  const toast = (msg) => {
    const id = Date.now() + Math.random();
    setToasts((ts) => [...ts, { id, msg }]);
    setTimeout(() => setToasts((ts) => ts.filter((x) => x.id !== id)), 2800);
  };

  const addToCart = (p, qty = 1) => {
    setCart((c) => {
      const ex = c.find((i) => i.id === p.id);
      if (ex) return c.map((i) => i.id === p.id ? { ...i, qty: i.qty + qty } : i);
      return [...c, { id: p.id, name: p.name, price: p.price, color: p.color, tone: p.tone, qty }];
    });
    toast(`${p.name} added to your bag`);
  };
  const setQty = (id, d) => setCart((c) => c.map((i) => i.id === id ? { ...i, qty: Math.max(1, i.qty + d) } : i));
  const removeItem = (id) => setCart((c) => c.filter((i) => i.id !== id));

  const goHome = () => { setPage({ name: "home" }); window.scrollTo(0, 0); };
  const goShop = (cat) => { setPage({ name: "shop", cat: cat || "all" }); window.scrollTo(0, 0); };
  const openProduct = (p) => { setPage({ name: "product", product: p }); };
  const goCheckout = () => { if (cart.length === 0) return; setCartOpen(false); setPage({ name: "checkout" }); window.scrollTo(0, 0); };

  const headerSolid = solid || page.name !== "home" || t.heroLayout === "split";
  const headerOnDark = page.name === "home" && !solid && (t.heroLayout === "full" || t.heroLayout === "centered");

  return (
    <div className="app">
      <Header solid={headerSolid} onDark={headerOnDark} cream={headerOnDark || t.theme === "dark"} cartCount={cartCount}
        onCart={() => setCartOpen(true)} onHome={goHome} onNavShop={() => goShop("all")} />

      {page.name === "home" && (
        <main>
          <Hero layout={t.heroLayout} onShop={() => goShop("all")} />
          <Values />
          <Categories onShop={goShop} />
          <Story onProcess={() => goShop("all")} />
          <BestSellers onOpen={openProduct} onAdd={(p) => addToCart(p, 1)}
            onShop={goShop} />
          <UtilityBand onToast={toast} />
        </main>
      )}

      {page.name === "shop" && (
        <main>
          <ShopPage all={PRODUCTS} cats={CATEGORIES} initialCat={page.cat}
            onOpen={openProduct} onAdd={addToCart} />
        </main>
      )}

      {page.name === "product" && (
        <main>
          <ProductPage product={page.product} all={PRODUCTS}
            onOpen={openProduct} onAdd={addToCart}
            onHome={goHome} onShop={() => goShop("all")} />
        </main>
      )}

      {page.name === "checkout" && (
        <CheckoutPage items={cart} onBack={() => { setPage({ name: "home" }); setCartOpen(true); window.scrollTo(0, 0); }}
          onHome={goHome} />
      )}

      <Footer onHome={goHome} />

      <CartDrawer open={cartOpen} items={cart} onClose={() => setCartOpen(false)}
        onQty={setQty} onRemove={removeItem} onCheckout={goCheckout} />
      <ToastStack toasts={toasts} />

      <TweaksPanel>
        <TweakSection label="Theme" />
        <TweakRadio label="Mode" value={t.theme}
          options={[
            { value: "light", label: "Light" },
            { value: "dark", label: "Dark" },
          ]}
          onChange={(v) => setTweak("theme", v)} />
        <TweakSection label="Hero" />
        <TweakRadio label="Layout" value={t.heroLayout}
          options={["split", "full", "centered"]}
          onChange={(v) => setTweak("heroLayout", v)} />
        <TweakSection label="Brand" />
        <TweakColor label="Accent" value={t.accent}
          options={["#B26A38", "#9A5A2E", "#C2843F", "#7C5A36", "#A53E2E"]}
          onChange={(v) => setTweak("accent", v)} />
        <TweakRadio label="Serif" value={t.serif}
          options={[
            { value: "'Bodoni Moda'", label: "Bodoni" },
            { value: "'Playfair Display'", label: "Playfair" },
            { value: "'Cormorant'", label: "Cormorant" },
          ]}
          onChange={(v) => setTweak("serif", v)} />
      </TweaksPanel>
    </div>
  );
}

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