// LC4lab — Shared components
const { useState, useEffect, useRef, useMemo } = React;

// Brand gradient mapping for cards
function brandGradient(brand) {
  return `linear-gradient(135deg, ${brand.accent}28, ${brand.accent2}18 60%, transparent)`;
}
function coverGradient(brand) {
  return `linear-gradient(135deg, ${brand.accent}38 0%, ${brand.bg || '#0a1628'} 60%, ${brand.accent2}30 100%)`;
}

function formatPrice(n) {
  return "R$ " + n.toFixed(2).replace(".", ",");
}

// Icons - inline SVG
const Icons = {
  search: (s=18) => <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="11" cy="11" r="7"/><path d="m20 20-3.5-3.5"/></svg>,
  cart: (s=18) => <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M2 3h2l2.5 12.5a2 2 0 0 0 2 1.5h9a2 2 0 0 0 2-1.5L22 7H6"/><circle cx="9" cy="21" r="1.5"/><circle cx="18" cy="21" r="1.5"/></svg>,
  user: (s=18) => <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="8" r="4"/><path d="M4 21a8 8 0 0 1 16 0"/></svg>,
  sun: (s=18) => <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="4"/><path d="M12 2v2m0 16v2M4.93 4.93l1.41 1.41m11.32 11.32 1.41 1.41M2 12h2m16 0h2M4.93 19.07l1.41-1.41m11.32-11.32 1.41-1.41"/></svg>,
  moon: (s=18) => <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/></svg>,
  arrow: (s=16) => <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12h14M13 5l7 7-7 7"/></svg>,
  close: (s=18) => <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M18 6 6 18M6 6l12 12"/></svg>,
  plus: (s=14) => <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round"><path d="M12 5v14M5 12h14"/></svg>,
  ebook: (s=20) => <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><path d="M4 4h12a3 3 0 0 1 3 3v13H7a3 3 0 0 1-3-3V4z"/><path d="M4 17a3 3 0 0 1 3-3h12"/><path d="M8 8h7M8 11h5"/></svg>,
  sheet: (s=20) => <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><rect x="3" y="3" width="18" height="18" rx="2"/><path d="M3 9h18M3 15h18M9 3v18M15 3v18"/></svg>,
  play: (s=20) => <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><circle cx="12" cy="12" r="9"/><path d="m10 8 6 4-6 4V8z" fill="currentColor"/></svg>,
  combo: (s=20) => <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><rect x="3" y="3" width="8" height="8" rx="1"/><rect x="13" y="3" width="8" height="8" rx="1"/><rect x="3" y="13" width="8" height="8" rx="1"/><rect x="13" y="13" width="8" height="8" rx="1"/></svg>,
  star: (s=14) => <svg width={s} height={s} viewBox="0 0 24 24" fill="currentColor"><path d="m12 2 3 7 7 .6-5.3 4.7L18.2 22 12 18l-6.2 4 1.5-7.7L2 9.6 9 9z"/></svg>,
  check: (s=14) => <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round"><path d="m5 12 5 5L20 7"/></svg>,
  spark: (s=18) => <svg width={s} height={s} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"><path d="M12 3v4M12 17v4M3 12h4M17 12h4M5.6 5.6l2.8 2.8M15.6 15.6l2.8 2.8M5.6 18.4l2.8-2.8M15.6 8.4l2.8-2.8"/></svg>,
};

function typeIcon(type) {
  if (type === "E-book") return Icons.ebook(16);
  if (type === "Planilha") return Icons.sheet(16);
  if (type === "Aulas") return Icons.play(16);
  if (type === "Combo") return Icons.combo(16);
  return Icons.spark(16);
}

// Brand card
function BrandCard({ brand, onClick }) {
  const total = brand.products.length;
  return (
    <div className="brand-card reveal" onClick={onClick}
      style={{ "--card-grad": brandGradient(brand) }}>
      <div className="brand-card-head">
        <img className="brand-card-logo" src={brand.logo} alt={brand.name}/>
        <span className="brand-card-tag">{brand.tag}</span>
      </div>
      <h3>{brand.name}</h3>
      <p className="brand-card-pitch">{brand.pitch}</p>
      <div className="brand-card-foot">
        <span><b>{total}</b> produtos · <b>{brand.students}</b> alunos</span>
        <div className="brand-card-arrow">{Icons.arrow(14)}</div>
      </div>
    </div>
  );
}

// Product card
function ProductCard({ brand, product, onOpen, onAdd }) {
  const initials = product.title.split(" ").slice(0,2).map(w => w[0]).join("").toUpperCase();
  return (
    <div className="product-card reveal" onClick={onOpen}
      style={{ "--cover-grad": coverGradient(brand) }}>
      <div className="product-cover">
        <span className="product-tag">{typeIcon(product.type)} {product.type}</span>
        {product.bestseller && <span className="product-bestseller">+ Vendido</span>}
        {product.image ? (
          <img src={product.image} alt={product.title}
               style={{ position: "absolute", inset: 0, width: "100%", height: "100%", objectFit: "cover", objectPosition: "center top", borderRadius: "inherit", background: "#0a1530" }} />
        ) : (
          <>
            <div className="product-cover-stripes"/>
            <div className="product-cover-glyph">{initials}</div>
          </>
        )}
      </div>
      <div className="product-body">
        <h4>{product.title}</h4>
        <p>{product.desc}</p>
        {product.pages && <span className="product-meta">{product.pages} páginas</span>}
        {product.duration && <span className="product-meta">{product.duration} de aulas</span>}
        <div className="product-foot">
          <div className="price">
            <span className="price-now">{formatPrice(product.price)}</span>
            {product.original && <span className="price-old">{formatPrice(product.original)}</span>}
          </div>
          <button className="btn btn-ghost btn-sm" onClick={e => { e.stopPropagation(); if (product.checkoutUrl) { window.open(product.checkoutUrl, "_blank", "noopener"); } else { onAdd(brand, product); } }}>
            Comprar agora
          </button>
        </div>
      </div>
    </div>
  );
}

// Product modal
function ProductModal({ brand, product, onClose, onAdd, go }) {
  useEffect(() => {
    const onKey = (e) => e.key === "Escape" && onClose();
    document.addEventListener("keydown", onKey);
    document.body.style.overflow = "hidden";
    return () => { document.removeEventListener("keydown", onKey); document.body.style.overflow = ""; };
  }, []);
  if (!product) return null;
  const initials = product.title.split(" ").slice(0,2).map(w => w[0]).join("").toUpperCase();
  return (
    <div className="modal-back" onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()}>
        <button className="modal-close" onClick={onClose}>{Icons.close(16)}</button>
        <div className="modal-grid">
          <div className="modal-cover" style={{ "--cover-grad": coverGradient(brand) }}>
            {product.image ? (
              <img src={product.image} alt={product.title}
                   style={{ position: "absolute", inset: 0, width: "100%", height: "100%", objectFit: "contain", objectPosition: "center", borderRadius: "inherit", background: "#0a1530" }} />
            ) : (
              <>
                <div className="product-cover-stripes"/>
                <div className="product-cover-glyph" style={{ fontSize: 96 }}>{initials}</div>
              </>
            )}
            <span className="product-tag" style={{top: 18, left: 18, zIndex: 2}}>{typeIcon(product.type)} {product.type}</span>
          </div>
          <div className="modal-body">
            <div className="breadcrumbs">{brand.name} / {product.type}</div>
            <h2>{product.title}</h2>
            <p style={{ color: "var(--text-dim)", lineHeight: 1.6 }}>{product.desc}</p>
            <ul style={{ listStyle: "none", display: "flex", flexDirection: "column", gap: 10, margin: "12px 0" }}>
              {product.pages && <li style={{ display: "flex", gap: 10, alignItems: "center", color: "var(--text-dim)", fontSize: 14 }}><span style={{color: "var(--cyan)"}}>{Icons.check()}</span> {product.pages} páginas em PDF</li>}
              {product.duration && <li style={{ display: "flex", gap: 10, alignItems: "center", color: "var(--text-dim)", fontSize: 14 }}><span style={{color: "var(--cyan)"}}>{Icons.check()}</span> {product.duration} de vídeo-aulas</li>}
              <li style={{ display: "flex", gap: 10, alignItems: "center", color: "var(--text-dim)", fontSize: 14 }}><span style={{color: "var(--cyan)"}}>{Icons.check()}</span> eBook</li>
              <li style={{ display: "flex", gap: 10, alignItems: "center", color: "var(--text-dim)", fontSize: 14 }}><span style={{color: "var(--cyan)"}}>{Icons.check()}</span> Planilha de controle</li>
              <li style={{ display: "flex", gap: 10, alignItems: "center", color: "var(--text-dim)", fontSize: 14 }}><span style={{color: "var(--cyan)"}}>{Icons.check()}</span> APP</li>
            </ul>
            <div style={{ display: "flex", alignItems: "baseline", gap: 12, marginTop: 8 }}>
              <span style={{ fontFamily: "Space Grotesk", fontSize: 36, fontWeight: 600 }}>{formatPrice(product.price)}</span>
              {product.original && <s style={{ color: "var(--text-mute)" }}>{formatPrice(product.original)}</s>}
            </div>
            <div style={{ display: "flex", gap: 10, marginTop: 16 }}>
              <button className="btn btn-primary btn-lg" style={{ flex: 1 }} onClick={() => { if (product.checkoutUrl) { window.open(product.checkoutUrl, "_blank", "noopener"); onClose(); } else { onAdd(brand, product); onClose(); } }}>
                Comprar agora
              </button>
              
            </div>
            {product.salesPage && (
              <button className="btn btn-outline" style={{marginTop: 8, width: "100%"}} onClick={() => { onClose(); go && go({page:'produto', id: product.id}); }}>
                Ver página de vendas completa →
              </button>
            )}
            {brand.id === "controle-simplificado" && (
              <button className="btn btn-outline" style={{marginTop: 8, width: "100%"}} onClick={() => { onClose(); go && go({page:'produto', id: 'diagnostico'}); }}>
                Diagnóstico Financeiro →
              </button>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

// Cart drawer
function CartDrawer({ open, items, onClose, onRemove, onCheckout }) {
  if (!open) return null;
  const total = items.reduce((a, i) => a + i.product.price, 0);
  const original = items.reduce((a, i) => a + (i.product.original || i.product.price), 0);
  const saved = original - total;
  return (
    <>
      <div className="drawer-back" onClick={onClose}/>
      <aside className="drawer">
        <div className="drawer-head">
          <h3>Seu carrinho ({items.length})</h3>
          <button className="icon-btn" onClick={onClose}>{Icons.close(16)}</button>
        </div>
        <div className="drawer-body">
          {items.length === 0 ? (
            <div className="empty">Seu carrinho está vazio.<br/>Que tal explorar nossos produtos?</div>
          ) : items.map((it, idx) => {
            const initials = it.product.title.split(" ").slice(0,2).map(w => w[0]).join("").toUpperCase();
            return (
              <div className="cart-item" key={idx}>
                <div className="cart-item-cover">{initials}</div>
                <div className="cart-item-body">
                  <h4>{it.product.title}</h4>
                  <span>{it.brand.name} · {it.product.type}</span>
                  <button className="cart-remove" onClick={() => onRemove(idx)}>Remover</button>
                </div>
                <div className="cart-item-price">{formatPrice(it.product.price)}</div>
              </div>
            );
          })}
        </div>
        {items.length > 0 && (
          <div className="drawer-foot">
            {saved > 0 && <div className="cart-total-row" style={{ color: "var(--emerald)" }}><span>Economia</span><span>−{formatPrice(saved)}</span></div>}
            <div className="cart-total-row big"><span>Total</span><span>{formatPrice(total)}</span></div>
            <button className="btn btn-primary btn-lg" onClick={onCheckout}>
              Finalizar compra {Icons.arrow(14)}
            </button>
            <span style={{ fontSize: 12, color: "var(--text-mute)", textAlign: "center" }}>
              Pagamento seguro · Hotmart / Kiwify
            </span>
          </div>
        )}
      </aside>
    </>
  );
}

// Toasts
function Toasts({ toasts }) {
  return (
    <div className="toasts">
      {toasts.map(t => <div className="toast" key={t.id}><b>{Icons.check()}</b> {t.msg}</div>)}
    </div>
  );
}

// Reveal hook
function useReveal() {
  useEffect(() => {
    const els = document.querySelectorAll(".reveal");
    const io = new IntersectionObserver((entries) => {
      entries.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();
  });
}

Object.assign(window, {
  BrandCard, ProductCard, ProductModal, CartDrawer, Toasts,
  Icons, formatPrice, brandGradient, coverGradient, typeIcon, useReveal,
});
