// ---- SÉRÈNE — app shell, routing, cart state -------------------------

/* =================== HEADER =================== */
function Header({ go, current, count, onCartClick }) {
  const [scrolled, setScrolled] = useState(false);
  const [menuOpen, setMenuOpen] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 12);
    window.addEventListener("scroll", onScroll);
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  const navItems = CATEGORIES.slice(0, 5);

  return (
    <>
      <div style={{ background: "var(--ink)", color: "var(--cream)", textAlign: "center", padding: "9px 20px", fontSize: 11.5, letterSpacing: "0.14em", textTransform: "uppercase" }}>
        Livraison offerte dès 120 € · Emballage cadeau gratuit
      </div>

      <header style={{
        position: "sticky", top: 0, zIndex: 50,
        background: scrolled ? "oklch(0.985 0.008 85 / 0.92)" : "var(--cream)",
        backdropFilter: scrolled ? "blur(10px)" : "none",
        borderBottom: "1px solid " + (scrolled ? "var(--line-soft)" : "transparent"),
        transition: "all 0.3s var(--ease)",
      }}>
        <div className="container" style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "0 36px", height: 74 }}>
          {/* Left: nav (desktop) / menu (mobile) */}
          <nav className="hide-mobile" style={{ display: "flex", gap: 26, flex: 1 }}>
            {navItems.map((c) => (
              <button key={c.id} onClick={() => go("category", { cat: c.id })}
                style={{ background: "none", border: "none", cursor: "pointer", fontSize: 13, letterSpacing: "0.04em", color: "var(--ink-soft)", padding: "4px 0", borderBottom: current.params?.cat === c.id ? "1px solid var(--ink)" : "1px solid transparent" }}>
                {c.name}
              </button>
            ))}
          </nav>
          <button className="show-mobile" onClick={() => setMenuOpen(true)} style={{ background: "none", border: "none", color: "var(--ink)", flex: "0 0 auto" }}><IconMenu /></button>

          {/* Center: logo */}
          <button onClick={() => go("home")} style={{ background: "none", border: "none", cursor: "pointer", flex: "0 0 auto" }}>
            <span style={{ fontFamily: "var(--font-display)", fontSize: 27, letterSpacing: "0.34em", fontWeight: 500, paddingLeft: "0.34em", color: "var(--ink)" }}>SÉRÈNE</span>
          </button>

          {/* Right: icons */}
          <div style={{ display: "flex", gap: 20, flex: 1, justifyContent: "flex-end", alignItems: "center", color: "var(--ink)" }}>
            <button className="hide-mobile" style={ic}><IconSearch /></button>
            <button className="hide-mobile" style={ic}><IconUser /></button>
            <button onClick={onCartClick} style={{ ...ic, position: "relative" }}>
              <IconBag />
              {count > 0 && <span style={{ position: "absolute", top: -6, right: -8, background: "var(--ink)", color: "var(--cream)", fontSize: 10, minWidth: 17, height: 17, borderRadius: 10, display: "flex", alignItems: "center", justifyContent: "center", padding: "0 4px" }}>{count}</span>}
            </button>
          </div>
        </div>
      </header>

      {/* Mobile menu */}
      {menuOpen && (
        <div style={{ position: "fixed", inset: 0, zIndex: 100, background: "var(--cream)", padding: 28 }} className="page-fade">
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 40 }}>
            <span style={{ fontFamily: "var(--font-display)", fontSize: 22, letterSpacing: "0.3em", paddingLeft: "0.3em" }}>SÉRÈNE</span>
            <button onClick={() => setMenuOpen(false)} style={{ background: "none", border: "none", color: "var(--ink)" }}><IconClose size={24} /></button>
          </div>
          <nav style={{ display: "flex", flexDirection: "column", gap: 4 }}>
            <button onClick={() => { go("category", { cat: "all" }); setMenuOpen(false); }} style={mNav}>Toute la boutique</button>
            {CATEGORIES.map((c) => (
              <button key={c.id} onClick={() => { go("category", { cat: c.id }); setMenuOpen(false); }} style={mNav}>{c.name}</button>
            ))}
          </nav>
        </div>
      )}
    </>
  );
}
const ic = { background: "none", border: "none", color: "var(--ink)", cursor: "pointer", display: "flex", padding: 2 };
const mNav = { background: "none", border: "none", textAlign: "left", fontFamily: "var(--font-display)", fontSize: 32, color: "var(--ink)", padding: "12px 0", borderBottom: "1px solid var(--line-soft)", cursor: "pointer" };

/* =================== CART DRAWER =================== */
function CartDrawer({ open, onClose, cart, setQty, removeItem, go }) {
  const sub = cart.reduce((s, i) => s + i.price * i.qty, 0);
  return (
    <>
      <div onClick={onClose} style={{ position: "fixed", inset: 0, zIndex: 200, background: "oklch(0.3 0.01 60 / 0.32)", opacity: open ? 1 : 0, pointerEvents: open ? "auto" : "none", transition: "opacity 0.4s var(--ease)" }} />
      <aside style={{
        position: "fixed", top: 0, right: 0, bottom: 0, width: "min(420px, 100vw)", zIndex: 201,
        background: "var(--cream)", transform: open ? "none" : "translateX(100%)", transition: "transform 0.45s var(--ease)",
        display: "flex", flexDirection: "column", boxShadow: "-20px 0 60px oklch(0.3 0.01 60 / 0.12)",
      }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", padding: "22px 26px", borderBottom: "1px solid var(--line-soft)" }}>
          <h3 style={{ fontSize: 22 }}>Panier ({cart.reduce((s, i) => s + i.qty, 0)})</h3>
          <button onClick={onClose} style={{ background: "none", border: "none", color: "var(--ink)" }}><IconClose size={22} /></button>
        </div>

        {cart.length === 0 ? (
          <div style={{ flex: 1, display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", gap: 16, color: "var(--ink-faint)" }}>
            <IconBag size={36} sw={1} />
            <p style={{ fontSize: 15 }}>Votre panier est vide.</p>
            <button className="btn btn--ghost" onClick={() => { onClose(); go("category", { cat: "all" }); }}>Explorer</button>
          </div>
        ) : (
          <>
            <div style={{ flex: 1, overflowY: "auto", padding: "8px 26px" }}>
              {cart.map((i) => (
                <div key={i.key} style={{ display: "grid", gridTemplateColumns: "66px 1fr auto", gap: 14, padding: "20px 0", borderBottom: "1px solid var(--line-soft)" }}>
                  <Ph label="" tone={i.tone} ratio="4 / 5" style={{ borderRadius: "var(--radius)" }} />
                  <div>
                    <h4 style={{ fontFamily: "var(--font-display)", fontSize: 17, fontWeight: 500 }}>{i.name}</h4>
                    <p style={{ fontSize: 12, color: "var(--ink-faint)", margin: "3px 0 10px" }}>{i.color || i.catName}</p>
                    <Stepper value={i.qty} onChange={(q) => setQty(i.key, q)} small />
                  </div>
                  <div style={{ display: "flex", flexDirection: "column", justifyContent: "space-between", alignItems: "flex-end" }}>
                    <button onClick={() => removeItem(i.key)} style={{ background: "none", border: "none", color: "var(--ink-faint)", cursor: "pointer", padding: 0 }}><IconClose size={15} /></button>
                    <span style={{ fontSize: 14.5, fontVariantNumeric: "tabular-nums" }}>{fmt(i.price * i.qty)}</span>
                  </div>
                </div>
              ))}
            </div>
            <div style={{ padding: 26, borderTop: "1px solid var(--line)" }}>
              <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 6, fontSize: 14, color: "var(--ink-soft)" }}>
                <span>Sous-total</span><span style={{ fontVariantNumeric: "tabular-nums" }}>{fmt(sub)}</span>
              </div>
              <p style={{ fontSize: 12, color: "var(--ink-faint)", marginBottom: 16 }}>Livraison calculée à l'étape suivante.</p>
              <button className="btn btn--block" style={{ marginBottom: 10 }} onClick={() => { onClose(); go("checkout"); }}>Commander</button>
              <button className="btn btn--ghost btn--block" onClick={() => { onClose(); go("cart"); }}>Voir le panier</button>
            </div>
          </>
        )}
      </aside>
    </>
  );
}

/* =================== TOAST =================== */
function Toast({ msg }) {
  return (
    <div style={{
      position: "fixed", bottom: 28, left: "50%", transform: `translateX(-50%) translateY(${msg ? "0" : "20px"})`,
      zIndex: 300, background: "var(--ink)", color: "var(--cream)", padding: "14px 24px", borderRadius: 100,
      fontSize: 13.5, letterSpacing: "0.04em", display: "flex", alignItems: "center", gap: 10,
      opacity: msg ? 1 : 0, pointerEvents: "none", transition: "all 0.4s var(--ease)", boxShadow: "0 12px 40px oklch(0.3 0.01 60 / 0.25)",
    }}>
      <IconCheck size={16} /> {msg}
    </div>
  );
}

/* =================== FOOTER =================== */
function Footer({ go }) {
  return (
    <footer style={{ background: "var(--cream-deep)", borderTop: "1px solid var(--line-soft)", marginTop: "auto" }}>
      <div className="container foot-grid" style={{ padding: "70px 36px 40px", display: "grid", gridTemplateColumns: "1.6fr 1fr 1fr 1fr", gap: 40 }} >
        <div className="foot-brand">
          <div style={{ fontFamily: "var(--font-display)", fontSize: 26, letterSpacing: "0.32em", paddingLeft: "0.32em", marginBottom: 18 }}>SÉRÈNE</div>
          <p style={{ fontSize: 14, color: "var(--ink-soft)", lineHeight: 1.7, maxWidth: 280 }}>
            Objets pour la maison, fabriqués main en Europe. Le beau, le juste, le durable.
          </p>
        </div>
        <FootCol title="Boutique" links={CATEGORIES.map((c) => [c.name, () => go("category", { cat: c.id })])} />
        <FootCol title="Maison" links={[["Notre histoire", () => go("home")], ["Les ateliers", () => go("home")], ["Journal", () => go("home")]]} />
        <FootCol title="Aide" links={[["Livraison & retours", () => go("home")], ["Contact", () => go("home")], ["Entretien", () => go("home")]]} />
      </div>
      <div className="container" style={{ padding: "0 36px 40px", display: "flex", justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", gap: 14, fontSize: 12, color: "var(--ink-faint)", letterSpacing: "0.04em" }}>
        <span>© 2026 SÉRÈNE · Conçu en France</span>
        <span style={{ display: "flex", gap: 22 }}>
          <a href="#" onClick={(e) => e.preventDefault()}>Mentions légales</a>
          <a href="#" onClick={(e) => e.preventDefault()}>CGV</a>
          <a href="#" onClick={(e) => e.preventDefault()}>Confidentialité</a>
        </span>
      </div>
    </footer>
  );
}
const FootCol = ({ title, links }) => (
  <div>
    <h4 style={{ fontFamily: "var(--font-ui)", fontWeight: 500, fontSize: 12, letterSpacing: "0.16em", textTransform: "uppercase", marginBottom: 18 }}>{title}</h4>
    <ul style={{ listStyle: "none", margin: 0, padding: 0, display: "flex", flexDirection: "column", gap: 11 }}>
      {links.map(([label, fn], i) => (
        <li key={i}><button onClick={fn} style={{ background: "none", border: "none", padding: 0, cursor: "pointer", fontSize: 14, color: "var(--ink-soft)", textAlign: "left" }}>{label}</button></li>
      ))}
    </ul>
  </div>
);

/* =================== APP =================== */
function App() {
  const [route, setRoute] = useState({ page: "home", params: {} });
  const [cart, setCart] = useState(() => {
    try { return JSON.parse(localStorage.getItem("serene_cart")) || []; } catch (e) { return []; }
  });
  const [drawer, setDrawer] = useState(false);
  const [toast, setToast] = useState("");
  const [order, setOrder] = useState(null);
  const toastTimer = useRef(null);

  useEffect(() => { localStorage.setItem("serene_cart", JSON.stringify(cart)); }, [cart]);

  const go = (page, params = {}) => { setRoute({ page, params }); window.scrollTo(0, 0); };

  const showToast = (msg) => {
    setToast(msg);
    clearTimeout(toastTimer.current);
    toastTimer.current = setTimeout(() => setToast(""), 2400);
  };

  const addToCart = (p, qty = 1, color = null) => {
    const key = p.id + (color || "");
    setCart((c) => {
      const ex = c.find((i) => i.key === key);
      if (ex) return c.map((i) => (i.key === key ? { ...i, qty: i.qty + qty } : i));
      return [...c, { key, id: p.id, name: p.name, price: p.price, tone: p.tone, catName: p.catName, color, qty }];
    });
    showToast(`${p.name} ajouté au panier`);
  };
  const setQty = (key, qty) => setCart((c) => c.map((i) => (i.key === key ? { ...i, qty } : i)));
  const removeItem = (key) => setCart((c) => c.filter((i) => i.key !== key));

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

  const placeOrder = (data) => {
    const num = "SR-" + Math.floor(10000 + Math.random() * 89999);
    setOrder({ ...data, num });
    setCart([]);
    go("confirmation");
  };

  let view;
  if (route.page === "home") view = <HomePage go={go} addToCart={addToCart} />;
  else if (route.page === "category") view = <CategoryPage params={route.params} go={go} addToCart={addToCart} />;
  else if (route.page === "product") view = <ProductPage params={route.params} go={go} addToCart={addToCart} />;
  else if (route.page === "cart") view = <CartPage cart={cart} setQty={setQty} removeItem={removeItem} go={go} />;
  else if (route.page === "checkout") view = <CheckoutPage cart={cart} go={go} placeOrder={placeOrder} />;
  else if (route.page === "confirmation") view = <ConfirmationPage order={order} go={go} />;

  return (
    <>
      <Header go={go} current={route} count={count} onCartClick={() => setDrawer(true)} />
      <main style={{ flex: 1 }}>{view}</main>
      <Footer go={go} />
      <CartDrawer open={drawer} onClose={() => setDrawer(false)} cart={cart} setQty={setQty} removeItem={removeItem} go={go} />
      <Toast msg={toast} />
    </>
  );
}

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