/* HEY!BEAR — shared components */
const { useState, useEffect, useRef } = React;
const HB = window.HB;
const BRL = (n) => "R$" + n.toLocaleString("pt-BR");

/* ---------- Gummy bear mascot (basic shapes only) ---------- */
function GummyBear({ size = 46, color = "var(--pink)", style }) {
  return (
    <svg viewBox="0 0 100 110" width={size} height={size * 1.1} style={style} aria-hidden="true">
      <defs>
        <radialGradient id="gbg" cx="38%" cy="30%" r="75%">
          <stop offset="0%" stopColor="#fff" stopOpacity=".55" />
          <stop offset="40%" stopColor="#fff" stopOpacity="0" />
        </radialGradient>
      </defs>
      <g fill={color}>
        <ellipse cx="26" cy="22" rx="13" ry="13" />
        <ellipse cx="74" cy="22" rx="13" ry="13" />
        <ellipse cx="50" cy="40" rx="27" ry="25" />
        <ellipse cx="50" cy="74" rx="31" ry="30" />
        <ellipse cx="16" cy="62" rx="11" ry="13" />
        <ellipse cx="84" cy="62" rx="11" ry="13" />
        <ellipse cx="32" cy="100" rx="13" ry="11" />
        <ellipse cx="68" cy="100" rx="13" ry="11" />
      </g>
      <ellipse cx="50" cy="70" rx="17" ry="16" fill="#fff" opacity=".22" />
      <circle cx="40" cy="38" r="3.4" fill="#3a1430" />
      <circle cx="60" cy="38" r="3.4" fill="#3a1430" />
      <path d="M44 47 q6 5 12 0" stroke="#3a1430" strokeWidth="2.4" fill="none" strokeLinecap="round" />
      <rect x="0" y="0" width="100" height="110" fill="url(#gbg)" rx="40" />
    </svg>
  );
}

/* ---------- Logo (official) ---------- */
function Logo({ size = "sm", onClick }) {
  const h = size === "lg" ? 96 : 52;
  return (
    <img src="assets/logo.png" alt="Hey!Bear" onClick={onClick}
      style={{ height: h, width: "auto", display: "block", cursor: onClick ? "pointer" : "default",
        filter: "drop-shadow(0 1px 6px rgba(255,79,162,.35))" }} />
  );
}

/* ---------- Icons (simple) ---------- */
const Icon = {
  cart: (p) => <svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M5 7h15l-1.5 9.5a2 2 0 0 1-2 1.7H8.5a2 2 0 0 1-2-1.7L5 4H2"/><circle cx="9" cy="21" r="1"/><circle cx="17" cy="21" r="1"/></svg>,
  snow: (p) => <svg viewBox="0 0 24 24" width="28" height="28" fill="none" stroke="var(--pink)" strokeWidth="2" strokeLinecap="round" {...p}><path d="M12 2v20M2 12h20M5 5l14 14M19 5L5 19M12 5l-2.5 2M12 5l2.5 2M12 19l-2.5-2M12 19l2.5-2"/></svg>,
  bag: (p) => <svg viewBox="0 0 24 24" width="28" height="28" fill="none" stroke="var(--pink)" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M5 8h14l-1 12H6L5 8z"/><path d="M8.5 8V6a3.5 3.5 0 0 1 7 0v2"/></svg>,
  pack: (p) => <svg viewBox="0 0 24 24" width="28" height="28" fill="none" stroke="var(--pink)" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M3 8l9-5 9 5v8l-9 5-9-5V8z"/><path d="M3 8l9 5 9-5M12 13v8"/></svg>,
  heart: (p) => <svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M12 20s-7-4.5-9.5-9C1 8 2.5 4.5 6 4.5c2 0 3.2 1.2 4 2.3.8-1.1 2-2.3 4-2.3 3.5 0 5 3.5 3.5 6.5C19 15.5 12 20 12 20z"/></svg>,
  play: (p) => <svg viewBox="0 0 24 24" width="22" height="22" fill="currentColor" {...p}><path d="M8 5v14l11-7z"/></svg>,
  search: (p) => <svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" {...p}><circle cx="11" cy="11" r="7"/><path d="M20 20l-3.5-3.5"/></svg>,
  instagram: (p) => <svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...p}><rect x="3" y="3" width="18" height="18" rx="5"/><circle cx="12" cy="12" r="4"/><circle cx="17.5" cy="6.5" r="1.1" fill="currentColor" stroke="none"/></svg>,
};

/* ---------- Striped placeholder ---------- */
function Placeholder({ label, a = "#FFE3F0", b = "#FFD0E6", style }) {
  return (
    <div className="ph" style={{ "--ph-a": a, "--ph-b": b, ...style }}>
      <span className="ph-tag">{label}</span>
    </div>
  );
}

/* ---------- Floating gummies decor ---------- */
function Floaties({ items }) {
  return (
    <>
      {items.map((it, i) => (
        <div key={i} className="floaty" style={{
          left: it.l, right: it.r, top: it.t, bottom: it.bt,
          "--rot": (it.rot || 0) + "deg",
          animation: `drift ${it.dur || 7}s ease-in-out ${it.delay || 0}s infinite`,
        }}>
          {it.bear
            ? <GummyBear size={it.size} color={it.color} />
            : <div style={{ width: it.size, height: it.size, borderRadius: it.shape === "drop" ? "50% 50% 50% 8px" : "42%", background: it.color, boxShadow: "inset -6px -8px 12px rgba(0,0,0,.08), inset 6px 6px 10px rgba(255,255,255,.5)", opacity: it.op || 1 }} />}
        </div>
      ))}
    </>
  );
}

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

/* ---------- Header ---------- */
function Header({ nav, route, count, onCart, onMenu }) {
  const links = [
    ["shop", "Shop"], ["creatina", "Creatina"], ["glow", "Glow"],
    ["sleep", "Sleep"], ["cravings", "Cravings"], ["feedbacks", "Feedbacks"], ["sobre", "Sobre"], ["contato", "Contato"],
  ];
  return (
    <header className="header">
      <div className="topbar">
        <div className="topbar-track">
          {[0, 1].map((k) => (
            <span key={k}>
              Nova fórmula Hey!Bear <i className="dot" /> Frete grátis acima de R$199 <i className="dot" /> Sem açúcar <i className="dot" /> Sem shaker, sem complicação <i className="dot" /> 3g de creatina por goma <i className="dot" /> Embaladas individualmente <i className="dot" />
            </span>
          ))}
        </div>
      </div>
      <div className="wrap">
        <div className="header-in">
          <a onClick={() => nav("home")} style={{ cursor: "pointer" }}><Logo size="sm" /></a>
          <nav className="nav">
            {links.map(([id, label]) => (
              <a key={id} className={route === id ? "active" : ""} onClick={() => nav(id)}>{label}</a>
            ))}
          </nav>
          <div className="header-right">
            <a className="icon-btn" href="https://www.instagram.com/use.heybear/" target="_blank" rel="noopener" aria-label="Instagram @use.heybear"><Icon.instagram /></a>
            <button className="icon-btn" aria-label="Buscar"><Icon.search /></button>
            <button className="icon-btn" onClick={onCart} aria-label="Carrinho">
              <Icon.cart />
              {count > 0 && <span className="cart-count">{count}</span>}
            </button>
            <button className="icon-btn burger" onClick={onMenu} aria-label="Menu">☰</button>
          </div>
        </div>
      </div>
    </header>
  );
}

/* ---------- Footer ---------- */
function Footer({ nav }) {
  return (
    <footer className="footer">
      <div className="wrap">
        <div className="footer-grid">
          <div>
            <div style={{ filter: "brightness(1.1)" }}><Logo size="sm" /></div>
            <p style={{ color: "rgba(255,255,255,.7)", maxWidth: 280, marginTop: 18, fontSize: 15 }}>
              Uma marca de doces premium que por acaso vende suplementos. Suplementação gostosa, prática e sem complicação.
            </p>
          </div>
          <div>
            <h4>Produtos</h4>
            <a onClick={() => nav("creatina")}>Creatina Gummies</a>
            <a onClick={() => nav("glow")}>Glow Gummies</a>
            <a onClick={() => nav("sleep")}>Sleep Gummies</a>
            <a onClick={() => nav("cravings")}>Cravings Gummies</a>
            <a onClick={() => nav("shop")}>Bear Pack</a>
          </div>
          <div>
            <h4>A marca</h4>
            <a onClick={() => nav("sobre")}>Sobre a Hey!Bear</a>
            <a onClick={() => nav("feedbacks")}>Feedbacks</a>
            <a onClick={() => nav("contato")}>Contato</a>
            <a onClick={() => nav("home")}>FAQ</a>
          </div>
          <div>
            <h4>Siga</h4>
            <a href="https://www.instagram.com/use.heybear/" target="_blank" rel="noopener">Instagram</a>
            <a href="https://www.instagram.com/use.heybear/" target="_blank" rel="noopener">TikTok</a>
            <a href="https://www.instagram.com/use.heybear/" target="_blank" rel="noopener">Pinterest</a>
            <a onClick={() => nav("contato")}>Newsletter</a>
          </div>
        </div>
        <div className="footer-bottom">
          <span>© 2026 Hey!Bear · CNPJ 58.154.077/0001-04 · Suplemento alimentar. Não contém medicamento.</span>
          <span>Feito com ♥ no Brasil</span>
        </div>
      </div>
    </footer>
  );
}

/* ---------- Cart drawer ---------- */
function CartDrawer({ open, items, onClose, setQty, remove, total, nav }) {
  const FREE = 199;
  const pct = Math.min(100, (total / FREE) * 100);
  return (
    <>
      <div className={"scrim" + (open ? " show" : "")} onClick={onClose} />
      <aside className={"drawer" + (open ? " show" : "")} aria-hidden={!open}>
        <div className="drawer-head">
          <h3>Sua bolsinha 🐻</h3>
          <button className="icon-btn" onClick={onClose} aria-label="Fechar">✕</button>
        </div>
        {items.length === 0 ? (
          <div className="drawer-empty">
            <div>
              <GummyBear size={80} color="var(--pink-light)" style={{ margin: "0 auto 16px" }} />
              <p style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 20, color: "var(--ink)" }}>Sua bolsinha está vazia</p>
              <p>Que tal começar pela Creatina?</p>
              <button className="btn btn-primary btn-sm" style={{ marginTop: 14 }} onClick={() => { onClose(); nav("creatina"); }}>Ver Creatina</button>
            </div>
          </div>
        ) : (
          <>
            <div className="drawer-body">
              <div style={{ background: "var(--pink-50)", borderRadius: 16, padding: "12px 14px" }}>
                <small style={{ color: "var(--pink-700)", fontWeight: 600, fontSize: 13 }}>
                  {total >= FREE ? "🎉 Você ganhou frete grátis!" : `Faltam ${BRL(FREE - total)} para o frete grátis`}
                </small>
                <div className="free-bar"><i style={{ width: pct + "%" }} /></div>
              </div>
              {items.map((it) => (
                <div className="cart-item" key={it.id}>
                  <div className="ci-media">
                    {it.photo ? <img src={it.photo} alt={it.name} /> : <Placeholder label="" a={it.phColors[0]} b={it.phColors[1]} />}
                  </div>
                  <div className="ci-info">
                    <b>{it.name}</b>
                    <small>{it.flavor}</small>
                    <div className="qty">
                      <button onClick={() => setQty(it.id, it.qty - 1)}>–</button>
                      <span>{it.qty}</span>
                      <button onClick={() => setQty(it.id, it.qty + 1)}>+</button>
                    </div>
                  </div>
                  <div style={{ textAlign: "right" }}>
                    <div className="ci-price">{BRL(it.price * it.qty)}</div>
                    <button className="ci-remove" onClick={() => remove(it.id)}>remover</button>
                  </div>
                </div>
              ))}
            </div>
            <div className="drawer-foot">
              <div className="row"><span style={{ color: "var(--ink-soft)" }}>Subtotal</span><b>{BRL(total)}</b></div>
              <button className="btn btn-primary btn-lg" style={{ width: "100%", justifyContent: "center" }}>Finalizar compra</button>
              <small>Frete e impostos calculados no checkout</small>
            </div>
          </>
        )}
      </aside>
    </>
  );
}

Object.assign(window, { GummyBear, Logo, Icon, Placeholder, Floaties, useReveal, Header, Footer, CartDrawer, BRL });

/* If a product has a real checkout URL, go straight to it; otherwise use the in-app cart */
function buyProduct(p, add, qty) {
  if (p && p.checkout) { window.open(p.checkout, "_blank", "noopener"); }
  else if (add) { add(p.id, qty || 1); }
}
window.buyProduct = buyProduct;
