const { useState, useEffect, useCallback } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "serifFont": "Playfair Display",
  "sansFont": "Hanken Grotesk",
  "palette": ["#bd5e3c", "#6b7048"],
  "heroStyle": "overlay",
  "radius": 18
}/*EDITMODE-END*/;

function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [cart, setCart] = useState([]);
  const [dish, setDish] = useState(null);     // offenes Gericht-Modal
  const [cartOpen, setCartOpen] = useState(false);
  const [reserveOpen, setReserveOpen] = useState(false);

  useReveal();

  // Tweaks → CSS-Variablen
  useEffect(() => {
    const r = document.documentElement.style;
    r.setProperty("--font-serif", `'${t.serifFont}', serif`);
    r.setProperty("--font-sans", `'${t.sansFont}', system-ui, sans-serif`);
    const [a, a2] = t.palette;
    r.setProperty("--accent", a);
    r.setProperty("--accent-d", `color-mix(in srgb, ${a} 84%, black)`);
    r.setProperty("--accent2", a2);
    r.setProperty("--radius", t.radius + "px");
  }, [t]);

  const addToCart = useCallback((line) => {
    setCart((c) => {
      const i = c.findIndex((x) => x.key === line.key);
      if (i >= 0) {
        const next = [...c];
        next[i] = { ...next[i], qty: Math.min(20, next[i].qty + line.qty) };
        return next;
      }
      return [...c, line];
    });
    // kleines haptisches Feedback: Cart kurz öffnen? Nein — dezent, nur Badge.
  }, []);

  const setQty = useCallback((key, qty) => {
    setCart((c) => qty <= 0 ? c.filter((x) => x.key !== key) : c.map((x) => x.key === key ? { ...x, qty: Math.min(20, qty) } : x));
  }, []);
  const removeItem = useCallback((key) => setCart((c) => c.filter((x) => x.key !== key)), []);
  const clearCart = useCallback(() => setCart([]), []);

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

  const openOrder = () => {
    if (count > 0) { setCartOpen(true); }
    else { const el = document.getElementById("menu"); if (el) el.scrollIntoView({ behavior: "smooth" }); }
  };
  const browseMenu = () => { const el = document.getElementById("menu"); if (el) el.scrollIntoView({ behavior: "smooth" }); };

  return (
    <div id="top">
      <Header cartCount={count} onOpenCart={() => setCartOpen(true)} onOrder={openOrder} onReserve={() => setReserveOpen(true)} />
      <main>
        <Hero variant={t.heroStyle} onOrder={openOrder} onReserve={() => setReserveOpen(true)} />
        <Story />
        <Menu onOpen={setDish} />
        <Visit onOrder={openOrder} onReserve={() => setReserveOpen(true)} />
      </main>
      <Footer />

      {/* Mobile sticky Warenkorb-Leiste */}
      {count > 0 && !cartOpen && !dish && (
        <div className="sm:hidden fixed bottom-0 inset-x-0 z-40 p-3 anim-fade" style={{ paddingBottom: "max(0.75rem, env(safe-area-inset-bottom))" }}>
          <button onClick={() => setCartOpen(true)}
            className="w-full h-14 rounded-full bg-terra text-white shadow-2xl shadow-black/25 flex items-center justify-between px-5">
            <span className="flex items-center gap-2.5 font-medium"><span className="min-w-[24px] h-6 px-1.5 rounded-full bg-white/25 grid place-items-center text-[13px]">{count}</span> Warenkorb ansehen</span>
            <span className="font-mono text-[15px]">{CHF(subtotal)}</span>
          </button>
        </div>
      )}

      {dish && <DishModal dish={dish} onClose={() => setDish(null)} onAdd={addToCart} />}
      <CartPanel open={cartOpen} cart={cart} onClose={() => setCartOpen(false)}
        onQty={setQty} onRemove={removeItem} onClear={clearCart} onBrowse={browseMenu} />
      <ReserveModal open={reserveOpen} onClose={() => setReserveOpen(false)} />

      {/* Tweaks */}
      <TweaksPanel title="Tweaks">
        <TweakSection label="Typografie" />
        <TweakSelect label="Headline (Serif)" value={t.serifFont}
          options={["Playfair Display", "Cormorant Garamond", "Bodoni Moda"]}
          onChange={(v) => setTweak("serifFont", v)} />
        <TweakSelect label="Fliesstext (Sans)" value={t.sansFont}
          options={["Hanken Grotesk", "DM Sans", "Figtree"]}
          onChange={(v) => setTweak("sansFont", v)} />

        <TweakSection label="Farbe & Form" />
        <TweakColor label="Akzent-Palette" value={t.palette}
          options={[["#bd5e3c", "#6b7048"], ["#a23c2e", "#2c2722"], ["#56603a", "#caa24a"]]}
          onChange={(v) => setTweak("palette", v)} />
        <TweakSlider label="Eckenradius" value={t.radius} min={0} max={28} step={2} unit="px"
          onChange={(v) => setTweak("radius", v)} />

        <TweakSection label="Hero-Layout" />
        <TweakRadio label="Stil" value={t.heroStyle}
          options={["overlay", "split", "editorial"]}
          onChange={(v) => setTweak("heroStyle", v)} />
      </TweaksPanel>
    </div>
  );
}

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