// components.jsx — Componentes compartidos para MiPC y su Mundo
// (Header, Footer, ProductCard, ProductImage, Banners, Breadcrumbs, Rating, etc.)

const { useState, useEffect, useRef, useMemo, useCallback } = React;

// ── Iconos SVG (line, stroke-current) ────────────────────────────────
const Icon = {
  search:  () => <svg 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:    () => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M3 4h2l2.5 12.5a2 2 0 0 0 2 1.5h8.5a2 2 0 0 0 2-1.5L21.5 8H6"/><circle cx="10" cy="20.5" r="1.5"/><circle cx="18" cy="20.5" r="1.5"/></svg>,
  user:    () => <svg 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>,
  heart:   () => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M12 21s-7-4.5-9.5-9C.5 8 3 4 6.5 4c2 0 3.5 1.5 5.5 4 2-2.5 3.5-4 5.5-4C21 4 23.5 8 21.5 12 19 16.5 12 21 12 21z"/></svg>,
  menu:    () => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M4 6h16M4 12h16M4 18h16"/></svg>,
  truck:   () => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M3 16V6h11v10"/><path d="M14 9h4l3 4v3h-7"/><circle cx="7" cy="18" r="2"/><circle cx="17" cy="18" r="2"/></svg>,
  shield:  () => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M12 3 4 6v6c0 5 3.5 8.5 8 9 4.5-.5 8-4 8-9V6l-8-3z"/></svg>,
  card:    () => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="2" y="6" width="20" height="12" rx="2"/><path d="M2 10h20"/></svg>,
  headset: () => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M3 14v-2a9 9 0 0 1 18 0v2"/><rect x="2" y="14" width="5" height="6" rx="1.5"/><rect x="17" y="14" width="5" height="6" rx="1.5"/><path d="M21 20a3 3 0 0 1-3 3h-2"/></svg>,
  chevron: ({d='right'}) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{transform:`rotate(${{right:0,down:90,left:180,up:270}[d]}deg)`}}><path d="m9 6 6 6-6 6"/></svg>,
  star:    ({filled}) => <svg viewBox="0 0 24 24" fill={filled?'currentColor':'none'} stroke="currentColor" strokeWidth="1.6" strokeLinejoin="round"><path d="M12 3l2.6 5.6 6 .6-4.5 4.2 1.3 6-5.4-3.2-5.4 3.2 1.3-6L3.4 9.2l6-.6L12 3z"/></svg>,
  close:   () => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M6 6l12 12M18 6 6 18"/></svg>,
  check:   () => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"><path d="m4 12 5 5 11-12"/></svg>,
  trash:   () => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M4 7h16M9 7V4h6v3M6 7l1 13a2 2 0 0 0 2 2h6a2 2 0 0 0 2-2l1-13"/></svg>,
  filter:  () => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M3 5h18M6 12h12M10 19h4"/></svg>,
};

// ── ProductImage (placeholder SVG por categoría + color) ─────────────
function ProductImage({ p, size = 'card' }) {
  const big = size === 'big';
  const sz = big ? 460 : 220;
  const bg = p.color || '#64748b';
  const cat = p.categoria;
  // Glifo grande translúcido del icono de la categoría
  const cats = window.MiPCInventario.categorias.find(c => c.id === cat);
  return (
    <div className="prod-img" style={{ background: `linear-gradient(135deg, ${bg}15, ${bg}30)` }}>
      <svg viewBox="0 0 200 200" width="100%" height="100%" preserveAspectRatio="xMidYMid meet">
        <defs>
          <pattern id={`p-${p.id}`} width="14" height="14" patternUnits="userSpaceOnUse" patternTransform="rotate(35)">
            <line x1="0" y1="0" x2="0" y2="14" stroke={bg} strokeOpacity=".08" strokeWidth="2"/>
          </pattern>
        </defs>
        <rect width="200" height="200" fill={`url(#p-${p.id})`}/>
        <text x="100" y="120" textAnchor="middle" fontSize="86" opacity=".95">{cats?.icono || '📦'}</text>
        <text x="100" y="170" textAnchor="middle" fontSize="9" fill={bg} fontFamily="ui-monospace,monospace" opacity=".7" letterSpacing="1">
          {(p.marca || '').toUpperCase()}
        </text>
      </svg>
    </div>
  );
}

// ── Rating estrellas ─────────────────────────────────────────────────
function Rating({ value = 0, reviews, size = 14 }) {
  const full = Math.round(value);
  return (
    <span className="rating" style={{ fontSize: size }}>
      <span className="rating-stars">
        {[1,2,3,4,5].map(i => (
          <span key={i} className="star" style={{width:size,height:size}}><Icon.star filled={i<=full}/></span>
        ))}
      </span>
      {reviews != null && <span className="rating-count">({reviews})</span>}
    </span>
  );
}

// ── Badge ────────────────────────────────────────────────────────────
function Badge({ children, tone = 'default' }) {
  return <span className={`badge badge-${tone}`}>{children}</span>;
}

// ── ProductCard ──────────────────────────────────────────────────────
function ProductCard({ p, onClick, onAdd }) {
  const fmt = window.MiPCInventario.formatoCOP;
  const desc = p.precioAntes && p.precioAntes > p.precio
    ? Math.round((1 - p.precio / p.precioAntes) * 100) : 0;
  return (
    <article className="card" onClick={onClick}>
      <div className="card-img-wrap">
        {desc > 0 && <span className="card-discount">-{desc}%</span>}
        <button className="card-fav" onClick={(e)=>{e.stopPropagation();}} aria-label="Favorito"><Icon.heart/></button>
        <ProductImage p={p}/>
      </div>
      <div className="card-body">
        <div className="card-brand">{p.marca}</div>
        <h3 className="card-title">{p.nombre}</h3>
        <div className="card-prices">
          {p.precioAntes && p.precioAntes > p.precio && (
            <span className="price-old">{fmt(p.precioAntes)}</span>
          )}
          <span className="price-now">{fmt(p.precio)}</span>
        </div>
        <div className="card-meta">
          <Rating value={p.rating} reviews={p.reviews}/>
        </div>
        {p.envioGratis && <div className="card-shipping"><Icon.truck/> Envío gratis</div>}
        <button className="card-cta" onClick={(e)=>{e.stopPropagation(); onAdd && onAdd(p);}}>
          Agregar al carrito
        </button>
      </div>
    </article>
  );
}

// ── Header ───────────────────────────────────────────────────────────
function Header({ route, cartCount, onNavigate, onSearch, query, setQuery, showBanners }) {
  const cats = window.MiPCInventario.categorias;
  const [openMenu, setOpenMenu] = useState(false);
  const submit = (e) => { e.preventDefault(); onSearch(query); };
  return (
    <header className="site-header">
      {showBanners && (
        <div className="topbar">
          <span>🚚 Envío gratis en compras superiores a $150.000 COP</span>
          <span className="topbar-dot">·</span>
          <span>📞 (601) 745 8800</span>
          <span className="topbar-dot">·</span>
          <span>💳 Hasta 36 cuotas con tu tarjeta de crédito</span>
        </div>
      )}
      <div className="header-main">
        <button className="header-burger" onClick={()=>setOpenMenu(o=>!o)} aria-label="Menú"><Icon.menu/></button>
        <a className="brand" onClick={(e)=>{e.preventDefault(); onNavigate('/');}} href="#/">
          <img src="assets/logo-mipc.png" alt="Mi PC y su Mundo"/>
        </a>
        <form className="search" onSubmit={submit}>
          <input
            type="search"
            placeholder="¿Qué estás buscando hoy? Ej: portátil, audífonos, PS5…"
            value={query}
            onChange={(e)=>setQuery(e.target.value)}
            aria-label="Buscar productos"
          />
          <button type="submit" aria-label="Buscar"><Icon.search/></button>
        </form>
        <div className="header-actions">
          <button className="header-action" onClick={()=>onNavigate('/login')}>
            <Icon.user/><span><small>Hola, ingresa</small><strong>Mi cuenta</strong></span>
          </button>
          <button className="header-action cart" onClick={()=>onNavigate('/carrito')}>
            <span className="cart-icon">
              <Icon.cart/>
              {cartCount > 0 && <span className="cart-pill">{cartCount}</span>}
            </span>
            <span><small>Mi</small><strong>Carrito</strong></span>
          </button>
        </div>
      </div>
      <nav className={`header-nav ${openMenu?'open':''}`}>
        {cats.map(c => (
          <a key={c.id} onClick={(e)=>{e.preventDefault(); setOpenMenu(false); onNavigate('/categoria/'+c.id);}}
             href={'#/categoria/'+c.id}
             className={route === '/categoria/'+c.id ? 'active' : ''}>
            <span className="nav-ic">{c.icono}</span> {c.nombre}
          </a>
        ))}
        <a className="nav-cta" onClick={(e)=>{e.preventDefault(); setOpenMenu(false); onNavigate('/categoria/ofertas');}} href="#/categoria/ofertas">🔥 Ofertas del día</a>
      </nav>
    </header>
  );
}

// ── Footer ───────────────────────────────────────────────────────────
function Footer() {
  return (
    <footer className="site-footer">
      <div className="footer-grid">
        <div>
          <h4>Atención al cliente</h4>
          <ul>
            <li>Centro de ayuda</li>
            <li>Estado de mi pedido</li>
            <li>Cambios y devoluciones</li>
            <li>Garantías</li>
            <li>Contáctanos</li>
          </ul>
        </div>
        <div>
          <h4>Mi PC y su Mundo</h4>
          <ul>
            <li>Quiénes somos</li>
            <li>Trabaja con nosotros</li>
            <li>Tiendas físicas</li>
            <li>Términos y condiciones</li>
            <li>Política de privacidad</li>
          </ul>
        </div>
        <div>
          <h4>Compra fácil</h4>
          <ul>
            <li>Medios de pago</li>
            <li>Envíos a todo Colombia</li>
            <li>Crédito directo</li>
            <li>Vende con nosotros</li>
          </ul>
        </div>
        <div>
          <h4>Síguenos</h4>
          <div className="socials">
            <span>📘 Facebook</span>
            <span>📷 Instagram</span>
            <span>▶️ YouTube</span>
            <span>🎵 TikTok</span>
          </div>
          <h4 style={{marginTop:16}}>Suscríbete</h4>
          <div className="newsletter">
            <input placeholder="tu@correo.com"/>
            <button>Suscribir</button>
          </div>
        </div>
      </div>
      <div className="footer-payments">
        <span className="pay">VISA</span>
        <span className="pay">MASTERCARD</span>
        <span className="pay">PSE</span>
        <span className="pay">Nequi</span>
        <span className="pay">Daviplata</span>
        <span className="pay">Efecty</span>
        <span className="pay">Addi</span>
      </div>
      <div className="footer-bottom">
        <span>© 2026 Grupo Mi PC y su Mundo SAS · NIT 900.xxx.xxx-x · Bogotá, Colombia</span>
        <span>mipcysumundo.com</span>
      </div>
    </footer>
  );
}

// ── Breadcrumbs ──────────────────────────────────────────────────────
function Breadcrumbs({ items, onNavigate }) {
  return (
    <nav className="breadcrumbs">
      {items.map((it, i) => (
        <React.Fragment key={i}>
          {i > 0 && <span className="bc-sep">/</span>}
          {it.to ? (
            <a href={'#'+it.to} onClick={(e)=>{e.preventDefault(); onNavigate(it.to);}}>{it.label}</a>
          ) : (
            <span>{it.label}</span>
          )}
        </React.Fragment>
      ))}
    </nav>
  );
}

// ── Hero / Carrusel principal ────────────────────────────────────────
function Hero({ onNavigate, variant = 'A' }) {
  const slidesA = [
    { kicker:'TECNO DAYS', titulo:'Hasta 40% OFF', sub:'En los mejores portátiles para estudio y trabajo', cta:'Ver portátiles', to:'/categoria/computadores', bg:'#dc2626', accent:'#fbbf24' },
    { kicker:'GAMING', titulo:'Arma tu setup', sub:'PS5, sillas, monitores 165Hz y más', cta:'Explorar gaming', to:'/categoria/gaming', bg:'#1e3a8a', accent:'#22c55e' },
    { kicker:'NUEVO', titulo:'iPhone 15 ya llegó', sub:'Llévalo con 12 cuotas sin interés', cta:'Lo quiero', to:'/categoria/celulares', bg:'#0f172a', accent:'#f59e0b' },
  ];
  const [idx, setIdx] = useState(0);
  useEffect(() => {
    const t = setInterval(() => setIdx(i => (i + 1) % slidesA.length), 6000);
    return () => clearInterval(t);
  }, []);
  const s = slidesA[idx];
  return (
    <section className={`hero hero-${variant}`} style={{'--hero-bg': s.bg, '--hero-accent': s.accent}}>
      <div className="hero-inner">
        <div className="hero-text">
          <span className="hero-kicker">{s.kicker}</span>
          <h1>{s.titulo}</h1>
          <p>{s.sub}</p>
          <button className="btn btn-primary" onClick={()=>onNavigate(s.to)}>{s.cta}</button>
        </div>
        <div className="hero-art" aria-hidden="true">
          <div className="hero-blob"/>
          <div className="hero-glyph">{['💻','🎮','📱'][idx]}</div>
        </div>
      </div>
      <div className="hero-dots">
        {slidesA.map((_,i) => (
          <button key={i} className={i===idx?'on':''} onClick={()=>setIdx(i)} aria-label={`Slide ${i+1}`}/>
        ))}
      </div>
    </section>
  );
}

// ── Strip de beneficios ──────────────────────────────────────────────
function BenefitsStrip() {
  const items = [
    { icon: <Icon.truck/>, t:'Envío gratis', s:'A partir de $150.000' },
    { icon: <Icon.shield/>, t:'Compra protegida', s:'30 días para cambios' },
    { icon: <Icon.card/>, t:'Hasta 36 cuotas', s:'Con tarjeta de crédito' },
    { icon: <Icon.headset/>, t:'Atención 24/7', s:'Chat, WhatsApp y línea' },
  ];
  return (
    <section className="benefits">
      {items.map((it,i)=>(
        <div key={i} className="benefit">
          <span className="benefit-ic">{it.icon}</span>
          <div><strong>{it.t}</strong><small>{it.s}</small></div>
        </div>
      ))}
    </section>
  );
}

// ── Grid de categorías circulares ────────────────────────────────────
function CategoryCircles({ onNavigate }) {
  const cats = window.MiPCInventario.categorias;
  return (
    <section className="cat-circles">
      <div className="section-head"><h2>Compra por categoría</h2></div>
      <div className="circles">
        {cats.map(c => (
          <button key={c.id} className="circle" onClick={()=>onNavigate('/categoria/'+c.id)}>
            <span className="circle-ic">{c.icono}</span>
            <span>{c.nombre}</span>
          </button>
        ))}
      </div>
    </section>
  );
}

Object.assign(window, {
  Icon, ProductImage, Rating, Badge, ProductCard,
  Header, Footer, Breadcrumbs, Hero, BenefitsStrip, CategoryCircles,
});
