// === Mania De Jeans CG — Shared Components ===
const { useState, useEffect, useMemo, useRef, useCallback } = React;

// === Icons (heroicons-style outline, minimal set) ===
const Icon = {
  Search: (p) => <svg width={p.s||18} height={p.s||18} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="11" cy="11" r="7"/><path d="M21 21l-4.3-4.3"/></svg>,
  User: (p) => <svg width={p.s||20} height={p.s||20} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="8" r="4"/><path d="M4 21c0-4.4 3.6-8 8-8s8 3.6 8 8"/></svg>,
  Heart: (p) => <svg width={p.s||20} height={p.s||20} viewBox="0 0 24 24" fill={p.filled?"currentColor":"none"} stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M20.84 4.61a5.5 5.5 0 00-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 00-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 000-7.78z"/></svg>,
  Cart: (p) => <svg width={p.s||20} height={p.s||20} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M3 3h2l2.4 12.2a2 2 0 002 1.6h9.6a2 2 0 002-1.6L23 6H6"/><circle cx="9" cy="20" r="1.5"/><circle cx="18" cy="20" r="1.5"/></svg>,
  Menu: (p) => <svg width={p.s||22} height={p.s||22} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M3 6h18M3 12h18M3 18h18"/></svg>,
  Close: (p) => <svg width={p.s||18} height={p.s||18} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M18 6L6 18M6 6l12 12"/></svg>,
  Plus: (p) => <svg width={p.s||16} height={p.s||16} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round"><path d="M12 5v14M5 12h14"/></svg>,
  Minus: (p) => <svg width={p.s||16} height={p.s||16} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round"><path d="M5 12h14"/></svg>,
  ChevronRight: (p) => <svg width={p.s||14} height={p.s||14} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><path d="M9 6l6 6-6 6"/></svg>,
  ChevronDown: (p) => <svg width={p.s||14} height={p.s||14} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><path d="M6 9l6 6 6-6"/></svg>,
  Star: (p) => <svg width={p.s||14} height={p.s||14} viewBox="0 0 24 24" fill={p.empty?"none":"currentColor"} stroke="currentColor" strokeWidth="1.5"><path d="M12 2l3.09 6.26L22 9.27l-5 4.87L18.18 21 12 17.77 5.82 21 7 14.14l-5-4.87 6.91-1.01L12 2z"/></svg>,
  Truck: (p) => <svg width={p.s||18} height={p.s||18} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><rect x="1" y="6" width="14" height="11" rx="1"/><path d="M15 9h4l3 3v5h-7"/><circle cx="6" cy="19" r="2"/><circle cx="18" cy="19" r="2"/></svg>,
  Shield: (p) => <svg width={p.s||18} height={p.s||18} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M12 2l8 4v6c0 5-3.5 9-8 10-4.5-1-8-5-8-10V6l8-4z"/><path d="M9 12l2 2 4-4"/></svg>,
  WhatsApp: (p) => <svg width={p.s||20} height={p.s||20} viewBox="0 0 24 24" fill="currentColor"><path d="M17.5 14.4c-.3-.1-1.7-.8-2-.9-.3-.1-.5-.1-.6.1-.2.3-.7.9-.8 1.1-.2.2-.3.2-.6.1-.3-.1-1.2-.4-2.3-1.4-.9-.8-1.4-1.7-1.6-2-.2-.3 0-.5.1-.6.1-.1.3-.3.4-.5.1-.2.2-.3.3-.5.1-.2 0-.4 0-.5 0-.1-.6-1.5-.8-2-.2-.5-.4-.5-.6-.5h-.5c-.2 0-.5.1-.7.3-.2.3-.9.9-.9 2.3 0 1.3 1 2.6 1.1 2.8.1.2 1.9 2.9 4.6 4 1.6.7 2.2.7 3 .6.5-.1 1.7-.7 1.9-1.4.2-.7.2-1.2.2-1.4-.1-.1-.3-.2-.6-.3zM12 2C6.5 2 2 6.5 2 12c0 1.7.5 3.4 1.3 4.8L2 22l5.3-1.3c1.4.8 2.9 1.2 4.6 1.2 5.5 0 10-4.5 10-10S17.5 2 12 2zm0 18c-1.5 0-2.9-.4-4.2-1.1l-.3-.2-3 .8.8-3-.2-.3C4.4 14.9 4 13.5 4 12c0-4.4 3.6-8 8-8s8 3.6 8 8-3.6 8-8 8z"/></svg>,
  Trash: (p) => <svg width={p.s||16} height={p.s||16} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M3 6h18M8 6V4a2 2 0 012-2h4a2 2 0 012 2v2M19 6l-1 14a2 2 0 01-2 2H8a2 2 0 01-2-2L5 6"/></svg>,
  Check: (p) => <svg width={p.s||16} height={p.s||16} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12l5 5L20 7"/></svg>,
  CheckCircle: (p) => <svg width={p.s||20} height={p.s||20} viewBox="0 0 24 24" fill="currentColor"><path d="M12 0a12 12 0 100 24 12 12 0 000-24zm5.7 9.2l-7.4 7.4-3.8-3.8 1.4-1.4 2.4 2.4 6-6 1.4 1.4z"/></svg>,
  Lock: (p) => <svg width={p.s||16} height={p.s||16} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><rect x="5" y="11" width="14" height="10" rx="2"/><path d="M8 11V7a4 4 0 018 0v4"/></svg>,
  Pix: (p) => <svg width={p.s||16} height={p.s||16} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M12 3l9 9-9 9-9-9 9-9z"/><path d="M8 8l4 4-4 4M16 8l-4 4 4 4"/></svg>,
  Sliders: (p) => <svg width={p.s||16} height={p.s||16} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M4 6h13M4 12h7M4 18h13"/><circle cx="19" cy="6" r="2"/><circle cx="13" cy="12" r="2"/><circle cx="19" cy="18" r="2"/></svg>,
  Pin: (p) => <svg width={p.s||14} height={p.s||14} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M12 22s8-7 8-13a8 8 0 10-16 0c0 6 8 13 8 13z"/><circle cx="12" cy="9" r="3"/></svg>,
  Box: (p) => <svg width={p.s||18} height={p.s||18} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M21 8L12 3 3 8v8l9 5 9-5V8z"/><path d="M3 8l9 5 9-5M12 13v9"/></svg>,
  Tag: (p) => <svg width={p.s||16} height={p.s||16} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M21 12.5L12.5 21l-9-9V3h9l8.5 8.5z"/><circle cx="7.5" cy="7.5" r="1.5"/></svg>,
  Chart: (p) => <svg width={p.s||18} height={p.s||18} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M3 3v18h18"/><path d="M7 14l3-3 3 3 5-5"/></svg>,
  Settings: (p) => <svg width={p.s||18} height={p.s||18} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.7 1.7 0 00.3 1.8l.1.1a2 2 0 11-2.8 2.8l-.1-.1a1.7 1.7 0 00-1.8-.3 1.7 1.7 0 00-1 1.5V21a2 2 0 11-4 0v-.1a1.7 1.7 0 00-1-1.5 1.7 1.7 0 00-1.8.3l-.1.1a2 2 0 11-2.8-2.8l.1-.1a1.7 1.7 0 00.3-1.8 1.7 1.7 0 00-1.5-1H3a2 2 0 110-4h.1a1.7 1.7 0 001.5-1 1.7 1.7 0 00-.3-1.8L4.2 7a2 2 0 112.8-2.8l.1.1a1.7 1.7 0 001.8.3H9a1.7 1.7 0 001-1.5V3a2 2 0 114 0v.1a1.7 1.7 0 001 1.5 1.7 1.7 0 001.8-.3l.1-.1a2 2 0 112.8 2.8l-.1.1a1.7 1.7 0 00-.3 1.8V9a1.7 1.7 0 001.5 1H21a2 2 0 110 4h-.1a1.7 1.7 0 00-1.5 1z"/></svg>,
  Edit: (p) => <svg width={p.s||14} height={p.s||14} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M11 4H4a2 2 0 00-2 2v14a2 2 0 002 2h14a2 2 0 002-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 013 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>,
  Eye: (p) => <svg width={p.s||14} height={p.s||14} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>,
  Bolt: (p) => <svg width={p.s||16} height={p.s||16} viewBox="0 0 24 24" fill="currentColor"><path d="M13 2L3 14h7v8l10-12h-7V2z"/></svg>,
  Alert: (p) => <svg width={p.s||14} height={p.s||14} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="10"/><path d="M12 8v4M12 16h.01"/></svg>,
  Image: (p) => <svg width={p.s||18} height={p.s||18} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="9" cy="9" r="2"/><path d="M21 15l-5-5L5 21"/></svg>,
  Home: (p) => <svg width={p.s||16} height={p.s||16} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M3 12l9-9 9 9"/><path d="M5 10v10h14V10"/></svg>,
};

// === Denim placeholder ===
// Renders a soft denim-textured rectangle with a label.
// Variants are hashed from `seed` to add visual variety across products.
function DenimPlaceholder({ label, seed = "x", tone, accent }) {
  // Hash seed → consistent pseudo-random values
  const hash = useMemo(() => {
    let h = 0;
    for (let i = 0; i < seed.length; i++) h = (h * 31 + seed.charCodeAt(i)) >>> 0;
    return h;
  }, [seed]);
  const variantIdx = hash % 4;
  const baseTone = tone || ["#3d5a7a", "#4a6586", "#2e4769", "#5a7593"][hash % 4];

  return (
    <div className="denim-ph">
      <svg viewBox="0 0 300 400" preserveAspectRatio="xMidYMid slice" aria-hidden="true">
        <defs>
          <linearGradient id={`g${seed}`} x1="0" y1="0" x2="1" y2="1">
            <stop offset="0%" stopColor={baseTone} stopOpacity="1"/>
            <stop offset="100%" stopColor={baseTone} stopOpacity="0.85"/>
          </linearGradient>
          <pattern id={`p${seed}`} width="3" height="3" patternUnits="userSpaceOnUse" patternTransform="rotate(45)">
            <line x1="0" y1="0" x2="0" y2="3" stroke="rgba(255,255,255,0.06)" strokeWidth="1"/>
          </pattern>
          <pattern id={`pv${seed}`} width="2" height="2" patternUnits="userSpaceOnUse">
            <rect width="2" height="2" fill="rgba(0,0,0,0.04)"/>
            <line x1="0" y1="0" x2="2" y2="0" stroke="rgba(255,255,255,0.03)" strokeWidth="0.5"/>
          </pattern>
        </defs>
        <rect width="300" height="400" fill={`url(#g${seed})`}/>
        <rect width="300" height="400" fill={`url(#p${seed})`}/>
        <rect width="300" height="400" fill={`url(#pv${seed})`}/>
        {/* Soft vignette */}
        <radialGradient id={`vg${seed}`} cx="50%" cy="50%" r="70%">
          <stop offset="60%" stopColor="black" stopOpacity="0"/>
          <stop offset="100%" stopColor="black" stopOpacity="0.25"/>
        </radialGradient>
        <rect width="300" height="400" fill={`url(#vg${seed})`}/>
        {/* Decorative seams / shapes based on variant */}
        {variantIdx === 0 && (
          <g opacity="0.18">
            <path d="M 150 0 L 150 400" stroke="#f4d27a" strokeWidth="1" strokeDasharray="6 4"/>
            <path d="M 80 80 L 80 320" stroke="rgba(255,255,255,0.4)" strokeWidth="0.5"/>
            <path d="M 220 80 L 220 320" stroke="rgba(255,255,255,0.4)" strokeWidth="0.5"/>
          </g>
        )}
        {variantIdx === 1 && (
          <g opacity="0.16">
            <rect x="50" y="80" width="60" height="80" fill="none" stroke="#f4d27a" strokeWidth="0.5" strokeDasharray="4 3"/>
            <rect x="190" y="80" width="60" height="80" fill="none" stroke="#f4d27a" strokeWidth="0.5" strokeDasharray="4 3"/>
          </g>
        )}
        {variantIdx === 2 && (
          <g opacity="0.2">
            <path d="M 30 0 L 30 400" stroke="rgba(255,255,255,0.3)" strokeWidth="0.5"/>
            <path d="M 270 0 L 270 400" stroke="rgba(255,255,255,0.3)" strokeWidth="0.5"/>
            <path d="M 150 200 Q 130 220 150 240 Q 170 260 150 280" stroke="#f4d27a" strokeWidth="0.6" fill="none" opacity="0.6"/>
          </g>
        )}
        {variantIdx === 3 && (
          <g opacity="0.18">
            <ellipse cx="150" cy="200" rx="120" ry="60" fill="rgba(255,255,255,0.12)"/>
            <path d="M 150 40 L 150 360" stroke="#f4d27a" strokeWidth="0.4" strokeDasharray="3 6"/>
          </g>
        )}
      </svg>
      {label && <span className="label">{label}</span>}
    </div>
  );
}

// === Helpers ===
const fmt = (v) => "R$ " + v.toFixed(2).replace(".", ",");
const fmtN = (v) => v.toFixed(2).replace(".", ",");

// === Logo ===
const BRAND_LOGO = (() => {
  const p = (window.location.pathname || "").replace(/\\/g, "/");
  return p.includes("/admin") ? "../assets/images/logo.jpg" : "assets/images/logo.jpg";
})();

function Logo({ onClick, showName }) {
  return (
    <div className="brand" onClick={onClick}>
      <img className="brand-logo" src={BRAND_LOGO} alt={showName ? "" : "Mania De Jeans CG"} width="120" height="120"/>
      {showName && (
        <div className="brand-words">
          <div className="top">Mania De Jeans CG</div>
        </div>
      )}
    </div>
  );
}

// === Header ===
function Header({ route, go, cartCount, fav, openSearch }) {
  return (
    <>
      <div className="announce">
        <span className="item"><Icon.Truck s={14}/> Enviamos para todo o Brasil</span>
        <span className="dot"/>
        <span className="item"><Icon.WhatsApp s={14}/> Atendimento personalizado pelo WhatsApp</span>
        <span className="dot"/>
        <span className="item">Parcele em até 3x sem juros</span>
      </div>
      <header className="header">
        <div className="header-inner">
          <Logo onClick={() => go("home")} showName/>
          <div className="search">
            <Icon.Search s={16}/>
            <input placeholder="Buscar por modelo, lavagem, tamanho…" onFocus={() => openSearch && openSearch()} readOnly/>
          </div>
          <div className="header-actions">
            <button className="icon-btn" aria-label="Favoritos" onClick={() => go("inst", { tab: "contato" })}><Icon.Heart/></button>
            <button className="icon-btn" aria-label="Contato" onClick={() => go("inst", { tab: "contato" })}><Icon.User/></button>
            <button className="icon-btn" aria-label="Carrinho" onClick={() => go("cart")}>
              <Icon.Cart/>
              {cartCount > 0 && <span className="badge">{cartCount}</span>}
            </button>
          </div>
        </div>
        <nav className="nav">
          <div className="nav-inner">
            <a className={"nav-item" + (route.screen === "home" ? " active" : "")} onClick={() => go("home")}>Início</a>
            <a className={"nav-item" + (route.screen === "catalog" ? " active" : "")} onClick={() => go("catalog")}>Coleção</a>
            <a className={"nav-item" + (route.screen === "inst" ? " active" : "")} onClick={() => go("inst", { tab: "sobre" })}>Sobre</a>
          </div>
        </nav>
      </header>
    </>
  );
}

// === Footer ===
const FOOTER_CAT_FALLBACK = [
  "Wide leg", "Pantalona", "Flare", "Boot cut", "Barrel", "Mom", "Skinny", "Cigarrete",
];

function Footer({ go, flushTop }) {
  const [catVersion, setCatVersion] = useState(0);
  useEffect(() => {
    if (window.MJ_CATEGORY_NAMES?.length) return;
    const p = window.MJ_loadCatalogLookups?.();
    if (p) p.then(() => setCatVersion((v) => v + 1)).catch(() => {});
  }, []);

  const footerCategories = useMemo(() => {
    void catVersion;
    const names = window.MJ_CATEGORY_NAMES?.length
      ? window.MJ_CATEGORY_NAMES
      : (window.MJ_CATEGORIES || []).map((c) => c.id);
    const list = names.length ? names : FOOTER_CAT_FALLBACK;
    return list.map((name) => ({ id: name, label: name }));
  }, [catVersion]);

  return (
    <footer className={"footer" + (flushTop ? " footer--flush" : "")}>
      <div className="footer-main">
        <div className="footer-brand">
          <Logo onClick={() => go("home")}/>
          <p>Jeans com estilo e qualidade<br/>Enviamos para todo o Brasil</p>
          <div style={{display: 'flex', gap: 10, alignItems: 'center', color: 'rgba(255,255,255,.7)', fontSize: 13}}>
            <Icon.Pin s={14}/> Loja em Campo Grande - MS &nbsp;·&nbsp; <Icon.WhatsApp s={14}/>{" "}
            <a href={window.MJ_WHATSAPP.url} target="_blank" rel="noopener noreferrer" style={{color:'inherit'}}>{window.MJ_WHATSAPP.display}</a>
          </div>
        </div>
        <div>
          <h4>Loja</h4>
          <div className="links">
            <a onClick={() => go("catalog")}>Toda a coleção</a>
            {footerCategories.map((c) => (
              <a key={c.id} onClick={() => go("catalog", { category: c.id })}>{c.label}</a>
            ))}
          </div>
        </div>
        <div>
          <h4>Atendimento</h4>
          <div className="links">
            <a onClick={() => go("inst", { tab: "entrega" })}>Política de entrega</a>
            <a onClick={() => go("inst", { tab: "trocas" })}>Trocas e devoluções</a>
            <a onClick={() => go("inst", { tab: "faq" })}>Perguntas frequentes</a>
            <a onClick={() => go("inst", { tab: "contato" })}>Contato e WhatsApp</a>
          </div>
        </div>
        <div>
          <h4>Institucional</h4>
          <div className="links">
            <a onClick={() => go("inst", { tab: "sobre" })}>Sobre a loja</a>
            <a onClick={() => go("inst", { tab: "privacidade" })}>Política de privacidade</a>
          </div>
        </div>
      </div>
      <div className="footer-bottom">
        <div className="footer-bottom-inner">
          <div>© 2026 Mania De Jeans CG · CNPJ 46.574.821/0001-32 · Todos os direitos reservados</div>
          <div className="payments">
            <span className="pay-chip">PIX</span>
            <span className="pay-chip">VISA</span>
            <span className="pay-chip">MASTER</span>
            <span className="pay-chip">ELO</span>
            <span className="pay-chip">BOLETO</span>
          </div>
        </div>
      </div>
    </footer>
  );
}

// === Foto do produto (URL do Storage ou placeholder) ===
function isImageUrl(src) {
  return typeof src === "string" && /^https?:\/\//i.test(src);
}

function ProductPhoto({ src, seed, tone, alt, className, style }) {
  if (isImageUrl(src)) {
    return (
      <img
        src={src}
        alt={alt || ""}
        className={className}
        style={{ width: "100%", height: "100%", objectFit: "cover", display: "block", ...style }}
        loading="lazy"
      />
    );
  }
  return <DenimPlaceholder label={src || ""} seed={seed} tone={tone}/>;
}

// === Product Card ===
function ProductCard({ p, style, onClick, fav, toggleFav }) {
  const isFav = fav && fav.includes(p.id);
  const photoSrc = p.fotoListing || p.foto1 || p.imageUrl || p.images?.[0];
  return (
    <div className={"card style-" + (style || "minimal")} onClick={() => onClick(p)}>
      <div className="ph-wrap">
        <ProductPhoto src={photoSrc} seed={p.id} tone={p.colorHex} alt={p.name}/>
        <div className="ribbons">
          {p.isNew && <span className="rib new">Novo</span>}
          {p.isPromo && <span className="rib promo">-{Math.round(((p.priceOld - p.price) / p.priceOld) * 100)}%</span>}
        </div>
        <button
          className={"heart" + (isFav ? " on" : "")}
          onClick={(e) => { e.stopPropagation(); toggleFav && toggleFav(p.id); }}
          aria-label="Favoritar"
        >
          <Icon.Heart s={16} filled={isFav}/>
        </button>
        <div className="quick">Ver detalhes</div>
      </div>
      <div className="name">{p.name}</div>
      <div className="price-row">
        {p.priceOld && <span className="price-old">{fmt(p.priceOld)}</span>}
        <span className={"price" + (p.priceOld ? " price-discount" : "")}>{fmt(p.price)}</span>
      </div>
      <div className="installments">{p.installments}</div>
    </div>
  );
}

// === Calculadora de frete (Correios) ===
function ShippingQuotePanel({ cep, onCepChange, items, subtotal, shipping, setShipping, toast, variant }) {
  const [loading, setLoading] = useState(false);
  const [err, setErr] = useState("");
  const inBox = variant !== "inline";

  const options = shipping?.options || [];
  const selected = shipping?.selected || null;
  const digits = window.MJ_cepDigits?.(cep) || "";

  const pickDefault = useCallback((list) => {
    if (!list?.length) return null;
    const pac = list.find((o) => window.MJ_isEconomyShipping?.(o));
    return pac || list[0];
  }, []);

  const onCalculate = async () => {
    setErr("");
    if (digits.length !== 8) {
      setErr("Informe um CEP com 8 dígitos.");
      return;
    }
    setLoading(true);
    try {
      const data = await window.MJ_fetchShippingQuote({ toCep: digits, items });
      const list = data.options || [];
      const chosen = selected && list.find((o) => o.id === selected.id) ? selected : pickDefault(list);
      setShipping({
        toCep: window.MJ_normalizeCep(digits),
        options: list,
        selected: chosen,
        quotedAt: new Date().toISOString(),
        estimated: !!data.estimated,
      });
      if (!list.length) setErr("Nenhuma opção de frete para este CEP.");
    } catch (e) {
      setErr(e.message || "Erro ao calcular frete.");
      toast?.(e.message || "Erro ao calcular frete.");
    } finally {
      setLoading(false);
    }
  };

  const onSelect = (opt) => {
    setShipping((prev) => ({
      ...(prev || {}),
      toCep: window.MJ_normalizeCep(digits) || prev?.toCep,
      options: prev?.options || options,
      selected: opt,
      quotedAt: prev?.quotedAt || new Date().toISOString(),
    }));
  };

  const content = (
    <>
      <div className="cep-row">
        <input
          placeholder="Digite seu CEP (00000-000)"
          value={cep}
          onChange={(e) => onCepChange(e.target.value)}
          maxLength={9}
        />
        <button type="button" className="btn btn-outline btn-sm" onClick={onCalculate} disabled={loading}>
          {loading ? "Calculando…" : "Calcular"}
        </button>
      </div>
      {err && <div style={{ fontSize: 12, color: "var(--promo)", marginTop: 6 }}>{err}</div>}
      {options.length > 0 && (
        <div style={{ marginTop: 10 }}>
          {options.map((opt) => {
            const isOn = selected?.id === opt.id;
            const price = Number(opt.price) || 0;
            return (
              <label
                key={opt.id}
                className={"opt" + (isOn ? " on" : "")}
                style={{ display: "flex", alignItems: "center", gap: 8, cursor: "pointer", marginBottom: 6 }}
              >
                <input
                  type="radio"
                  name="mj-shipping-opt"
                  checked={isOn}
                  onChange={() => onSelect(opt)}
                  style={{ accentColor: "var(--denim-700)" }}
                />
                <span className="l" style={{ flex: 1 }}>
                  <Icon.Truck s={12} style={{ verticalAlign: "middle" }} /> {opt.company} · {opt.name}
                  <span style={{ color: "var(--ink-500)", fontWeight: 500 }}> · {window.MJ_formatDeliveryLabel(opt)}</span>
                </span>
                <span className="r">{fmt(price)}</span>
              </label>
            );
          })}
        </div>
      )}
      {!options.length && !err && (
        <div style={{ fontSize: 12.5, color: "var(--ink-500)", marginTop: 4 }}>
          Informe o CEP e clique em Calcular para ver prazos e valores.
        </div>
      )}
      {shipping?.estimated && options.length > 0 && (
        <div style={{ fontSize: 11.5, color: "var(--ink-500)", marginTop: 6, lineHeight: 1.45 }}>
          Valores estimados (Correios indisponível no momento). A loja pode confirmar no pedido.
        </div>
      )}
    </>
  );

  if (!inBox) return <div className="shipping-inline">{content}</div>;

  return (
    <div className="delivery-box">
      <div className="title">
        <Icon.Truck s={14} style={{ verticalAlign: "middle" }} /> &nbsp; Calcular entrega para todo o Brasil
      </div>
      {content}
    </div>
  );
}

// === Toast ===
function Toast({ message, onClose }) {
  useEffect(() => {
    if (!message) return;
    const t = setTimeout(onClose, 2800);
    return () => clearTimeout(t);
  }, [message, onClose]);
  if (!message) return null;
  return (
    <div className="toast">
      <span className="ic"><Icon.CheckCircle s={18}/></span>
      {message}
    </div>
  );
}

// === Modal ===
function Modal({ open, onClose, children, title }) {
  if (!open) return null;
  return (
    <div className="modal-bg" onClick={onClose}>
      <div className="modal" onClick={(e) => e.stopPropagation()}>
        <button className="modal-close" onClick={onClose} aria-label="Fechar"><Icon.Close/></button>
        {title && <h3 style={{fontFamily:'var(--font-display)', fontSize:22, margin:'0 0 16px', letterSpacing:'-0.02em', color:'var(--denim-900)'}}>{title}</h3>}
        {children}
      </div>
    </div>
  );
}

// === Star Rating ===
function StarRating({ rating, size = 14 }) {
  const filled = Math.round(rating);
  return (
    <span className="stars">
      {[1,2,3,4,5].map(i => <Icon.Star key={i} s={size} empty={i > filled}/>)}
    </span>
  );
}

// === Share to window ===
Object.assign(window, {
  Icon, DenimPlaceholder, Logo, Header, Footer, ProductCard, ProductPhoto, isImageUrl, ShippingQuotePanel, Toast, Modal, StarRating, fmt, fmtN
});
