// Sassalbini · app root

function App() {
  const initialTheme = (window.TWEAKS && window.TWEAKS.theme) || "editorial";
  // migrate old "midnight" → editorial
  const safeInitial = initialTheme === "midnight" ? "editorial" : initialTheme;
  const [theme, setTheme] = useState(safeInitial);
  const [editMode, setEditMode] = useState(false);

  const [cat, setCat] = useState("all");
  const [q, setQ] = useState("");
  const [sort, setSort] = useState("featured");

  const [wishes, setWishes] = useState(() => { try { return JSON.parse(localStorage.getItem("sb_wishes") || "[]"); } catch { return []; } });
  const [cart, setCart] = useState(() => { try { return JSON.parse(localStorage.getItem("sb_cart") || "[]"); } catch { return []; } });
  const [openProduct, setOpenProduct] = useState(null);
  const [cartOpen, setCartOpen] = useState(false);
  const [toast, setToast] = useState(null);

  useEffect(() => { document.documentElement.setAttribute("data-theme", theme); }, [theme]);
  useEffect(() => { localStorage.setItem("sb_wishes", JSON.stringify(wishes)); }, [wishes]);
  useEffect(() => { localStorage.setItem("sb_cart", JSON.stringify(cart)); }, [cart]);

  useEffect(() => {
    function onMsg(e) {
      const d = e.data || {};
      if (d.type === "__activate_edit_mode") setEditMode(true);
      if (d.type === "__deactivate_edit_mode") setEditMode(false);
    }
    window.addEventListener("message", onMsg);
    window.parent.postMessage({ type: "__edit_mode_available" }, "*");
    return () => window.removeEventListener("message", onMsg);
  }, []);

  function updateTheme(next) {
    setTheme(next);
    window.parent.postMessage({ type: "__edit_mode_set_keys", edits: { theme: next } }, "*");
  }

  const toggleWish = id => setWishes(ws => ws.includes(id) ? ws.filter(x => x !== id) : [...ws, id]);
  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, qty }];
    });
    setToast({ k: Date.now(), text: `${p.name} aggiunto` });
  };
  useEffect(() => {
    if (!toast) return;
    const t = setTimeout(() => setToast(null), 2200);
    return () => clearTimeout(t);
  }, [toast]);

  const setQty = (id, qty) => {
    if (qty <= 0) return setCart(c => c.filter(i => i.id !== id));
    setCart(c => c.map(i => i.id === id ? { ...i, qty } : i));
  };
  const removeFromCart = id => setCart(c => c.filter(i => i.id !== id));

  const cartCount = cart.reduce((s, i) => s + i.qty, 0);
  const inCartIds = new Set(cart.map(i => i.id));

  const visible = useMemo(() => {
    const f = filterProducts(PRODUCTS, { cat, q });
    return sortProducts(f, sort);
  }, [cat, q, sort]);

  return (
    <div className="page">
      <div className="blob blob-1" />
      <div className="blob blob-2" />
      <div className="blob blob-3" />

      <div className="shell">
        <Hero cartCount={cartCount} onOpenCart={() => setCartOpen(true)} />

        <Storia />

        <div className="section-head" id="prodotti">
          <div>
            <div className="eyebrow">Bottega · {new Date().toLocaleDateString("it-IT", { day: "numeric", month: "long" })}</div>
            <h2 className="section-title">Formaggi <em>al banco</em></h2>
          </div>
          <div className="section-count">{visible.length} {visible.length === 1 ? "prodotto" : "prodotti"}</div>
        </div>

        <Filterbar cat={cat} setCat={setCat} q={q} setQ={setQ} sort={sort} setSort={setSort} />

        <div className="grid">
          {visible.map(p => (
            <ProductCard key={p.id} p={p} onOpen={setOpenProduct} wished={wishes.includes(p.id)} toggleWish={toggleWish} inCart={inCartIds.has(p.id)} onAdd={addToCart} />
          ))}
        </div>

        {visible.length === 0 && (
          <div style={{textAlign: "center", padding: "80px 20px", color: "var(--muted)"}}>
            <div className="font-display" style={{fontSize: 32, fontStyle: "italic", color: "var(--fg)", marginBottom: 10}}>Nessun prodotto</div>
            <div>Prova a rimuovere qualche filtro.</div>
          </div>
        )}

        <Mappa />
        <Testimonianze />
        <Contatti />
        <Footer />
      </div>

      {!cartOpen && <FloatingCart count={cartCount} onOpen={() => setCartOpen(true)} />}
      {openProduct && <ProductModal p={openProduct} onClose={() => setOpenProduct(null)} onAdd={addToCart} />}
      {cartOpen && <CartPanel items={cart} onClose={() => setCartOpen(false)} onQty={setQty} onRemove={removeFromCart} />}
      {editMode && <Tweaks theme={theme} setTheme={updateTheme} />}
      {toast && <Toast msg={toast} />}
    </div>
  );
}

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