/* global React, ReactDOM, PRODUCTS, STORE, brl,
   Header, Footer, Home, CategoryView, ProductView, CartDrawer, AgeGate,
   useTweaks, TweaksPanel, TweakSection, TweakRadio, TweakColor, TweakSelect, TweakSlider */
const { useState, useEffect } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "theme": "dark",
  "accent": "#FFD60A",
  "displayFont": "Anton",
  "radius": 20
}/*EDITMODE-END*/;

const FONT_STACK = {
  "Anton": '"Anton", "Archivo", sans-serif',
  "Archivo": '"Archivo", sans-serif',
  "Bebas Neue": '"Bebas Neue", "Archivo", sans-serif',
  "Oswald": '"Oswald", "Archivo", sans-serif',
};

function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [view, setView] = useState("home");      // home | category | product
  const [catId, setCatId] = useState("todos");
  const [current, setCurrent] = useState(null);
  const [hist, setHist] = useState([]);          // pilha de navegação (botão Voltar)
  const [cart, setCart] = useState([]);
  const [fav, setFav] = useState([]);
  const [search, setSearch] = useState("");
  const [drawer, setDrawer] = useState(false);
  const [age, setAge] = useState(false);
  const [toast, setToast] = useState(null);

  // The preview host forcibly themes <body>/#root, so we scope every token
  // to a wrapper div we fully control.
  const styleVars = {
    "--accent": t.accent,
    "--accent-2": t.accent,
    "--font-display": FONT_STACK[t.displayFont] || FONT_STACK.Anton,
    "--r": t.radius + "px",
    "--r-lg": (t.radius + 8) + "px",
  };
  const wrapClass = "app-root" + (t.theme === "light" ? " theme-light" : "");
  // Host force-themes near-root elements via class rules; inline literals on a
  // child of .app-content survive. So carry bg+text as inline colors here.
  const THEME = {
    dark:  { bg: "#0B0B0C", text: "#F6F6F2" },
    light: { bg: "#F1F0EA", text: "#131311" },
  };

  useEffect(() => { window.scrollTo({ top: 0, behavior: "instant" in window ? "instant" : "auto" }); }, [view, current, catId]);

  const pushHist = () => setHist((h) => [...h, { view, catId, current, search }]);
  const goHome = () => { setHist([]); setSearch(""); setView("home"); };
  const goCat = (id) => { pushHist(); setSearch(""); setCatId(id); setView("category"); };
  const openProduct = (p) => { pushHist(); setCurrent(p); setView("product"); };
  const onSearch = (q) => { setSearch(q); if (q.trim()) setView("category"); else if (view === "category") setView("home"); };
  // Voltar inteligente: restaura a tela anterior; se não há histórico, vai pra Home.
  const goBack = () => setHist((h) => {
    if (!h.length) { setView("home"); return h; }
    const s = h[h.length - 1];
    setView(s.view); setCatId(s.catId); setCurrent(s.current); setSearch(s.search);
    return h.slice(0, -1);
  });

  const showToast = (msg) => {
    setToast(msg);
    clearTimeout(window.__nikToast);
    window.__nikToast = setTimeout(() => setToast(null), 1800);
  };
  // Adiciona ao carrinho SEM abrir a gaveta: o cliente continua navegando.
  const addToCart = (p, flavor = p.flavors[0], qty = 1) => {
    const key = p.id + "::" + flavor;
    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, brand: p.brand, model: p.model, price: p.price, flavors: p.flavors, flavor, qty }];
    });
    showToast("Adicionado ao carrinho ✓");
  };
  const changeQty = (key, d) => setCart((c) =>
    c.map((i) => i.key === key ? { ...i, qty: Math.max(1, i.qty + d) } : i).filter((i) => i.qty > 0));
  const removeItem = (key) => setCart((c) => c.filter((i) => i.key !== key));
  const toggleFav = (id) => setFav((f) => f.includes(id) ? f.filter((x) => x !== id) : [...f, id]);

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

  if (!age) return (
    <div className={wrapClass} style={styleVars}>
      <div className="app-content">
        <div className="page-inner">
          <div className="page-bg" style={{ background: THEME[t.theme].bg }} />
          <div className="content-wrap" style={{ color: THEME[t.theme].text }}>
            <AgeGate onConfirm={() => setAge(true)} />
          </div>
        </div>
      </div>
    </div>
  );

  return (
    <div className={wrapClass} style={styleVars}>
      <div className="app-content">
        <div className="page-inner">
          <div className="page-bg" style={{ background: THEME[t.theme].bg }} />
          <div className="content-wrap" style={{ color: THEME[t.theme].text }}>
      <div className="age-bar">🔞 Venda exclusiva para maiores de 18 anos · Produtos contêm nicotina</div>
      <Header cartCount={cartCount} onCart={() => setDrawer(true)} onSearch={onSearch} search={search}
              onHome={goHome} onNavCat={goCat} onBack={goBack} canBack={hist.length > 0} />

      {view === "home" && <Home onOpen={openProduct} onAdd={addToCart} onNavCat={goCat} fav={fav} onFav={toggleFav} />}
      {view === "category" && <CategoryView catId={catId} onOpen={openProduct} onAdd={addToCart} onNavCat={goCat} fav={fav} onFav={toggleFav} search={search} />}
      {view === "product" && current && <ProductView p={current} onAdd={addToCart} onNavCat={goCat} onOpen={openProduct} fav={fav} onFav={toggleFav} />}

      <Footer onNavCat={goCat} onHome={goHome} />

      {drawer && <CartDrawer items={cart} onClose={() => setDrawer(false)} onQty={changeQty} onRemove={removeItem} />}

      {/* Barra fixa de finalizar — aparece quando há itens e a gaveta está fechada */}
      {cartCount > 0 && !drawer && (
        <button className="cart-fab" onClick={() => setDrawer(true)}>
          <span className="cart-fab-l"><span className="cart-fab-badge">{cartCount}</span> {cartCount === 1 ? "item" : "itens"} no carrinho</span>
          <span className="cart-fab-r">{brl(cartTotal)} <Icon k="arrow" size={16} /></span>
        </button>
      )}

      {/* Toast de confirmação */}
      {toast && <div className="toast"><Icon k="check" size={16} /> {toast}</div>}

      <TweaksPanel title="Tweaks">
        <TweakSection label="Tema" />
        <TweakRadio label="Fundo" value={t.theme} options={["dark", "light"]} onChange={(v) => setTweak("theme", v)} />
        <TweakColor label="Cor de destaque" value={t.accent}
          options={["#FFD60A", "#C6F23A", "#8B5CF6", "#FF7A2F"]} onChange={(v) => setTweak("accent", v)} />
        <TweakSection label="Tipografia" />
        <TweakSelect label="Fonte dos títulos" value={t.displayFont}
          options={["Anton", "Archivo", "Bebas Neue", "Oswald"]} onChange={(v) => setTweak("displayFont", v)} />
        <TweakSection label="Forma" />
        <TweakSlider label="Arredondamento" value={t.radius} min={4} max={32} step={2} unit="px"
          onChange={(v) => setTweak("radius", v)} />
      </TweaksPanel>
          </div>
        </div>
      </div>
    </div>
  );
}

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