// Home screen
function HomeScreen({ navigate, addToCart, isMobile }) {
  const P = window.POP;
  const products = window.POP_PRODUCTS;
  // "Lo que más se mueve" — 2 productos de cada categoría objetivo (5 cats × 2 = 10)
  const top = (() => {
    const TARGET = [
      ['Sillas', 'Silla'],
      ['Teclados', 'Teclado'],
      ['Audífonos', 'Audio', 'Audifonos'],
      ['Joysticks', 'Joystick', 'Controles', 'Gamepad'],
      ['Smartwatch', 'Wearables', 'Wearable'],
    ];
    const seen = new Set();
    const picked = [];
    TARGET.forEach(names => {
      const fromCat = products
        .filter(p => names.some(n => (p.category || '').toLowerCase().includes(n.toLowerCase())))
        .slice(0, 2);
      fromCat.forEach(p => { if (!seen.has(p.id)) { seen.add(p.id); picked.push(p); } });
    });
    // Si no hay suficientes de esas cats, completar con los primeros del catálogo
    if (picked.length < 10) {
      products.forEach(p => { if (!seen.has(p.id) && picked.length < 10) { seen.add(p.id); picked.push(p); } });
    }
    return picked.slice(0, 10);
  })();
  const newArrivals = products.slice(4, 9);
  const [timer, setTimer] = React.useState({ d: 2, h: 14, m: 33, s: 47 });
  const [promoEmail, setPromoEmail] = React.useState('');
  const [promoSent, setPromoSent] = React.useState(false);

  React.useEffect(() => {
    const id = setInterval(() => {
      setTimer(t => {
        let { d, h, m, s } = t;
        s--;
        if (s < 0) { s = 59; m--; }
        if (m < 0) { m = 59; h--; }
        if (h < 0) { h = 23; d--; }
        if (d < 0) { d = 2; h = 14; m = 33; s = 47; }
        return { d, h, m, s };
      });
    }, 1000);
    return () => clearInterval(id);
  }, []);

  const pad = n => String(n).padStart(2, '0');

  return (
    <div className="pop-page-in" style={{ paddingBottom: 0, overflow: 'hidden' }}>

      {/* HERO */}
      <div style={{
        padding: isMobile ? 16 : 32,
        display: 'grid',
        gridTemplateColumns: isMobile ? '1fr' : '1.4fr 1fr',
        gap: isMobile ? 16 : 20,
      }}>
        <div style={{
          background: P.orange, border: `3px solid ${P.ink}`, borderRadius: isMobile ? 16 : 20,
          padding: isMobile ? 22 : 40,
          position: 'relative', overflow: 'hidden', minHeight: isMobile ? 280 : 420,
          boxShadow: `6px 6px 0 ${P.ink}`, color: P.card,
        }}>
          <div className="pop-dots" style={{ position: 'absolute', inset: 0, opacity: 0.4 }}></div>
          <div style={{ position: 'absolute', top: isMobile ? 14 : 30, right: isMobile ? 14 : 30, transform: 'rotate(15deg)' }}>
            <StarBurst size={isMobile ? 80 : 150} fill={P.yellow} text={'HOT\nWEEK'} />
          </div>
          <div style={{ position: 'relative', maxWidth: 600 }}>
            <div className="pop-bounce-in" style={{
              display: 'inline-block', background: P.card, color: P.red,
              border: `2px solid ${P.ink}`, padding: '5px 12px', borderRadius: 999,
              fontFamily: P.display, fontSize: isMobile ? 11 : 13, letterSpacing: 1,
            }}>🔥 HOT WEEK · 14–20 OCT</div>
            <div className="pop-fade-up" style={{
              fontFamily: P.display, fontSize: isMobile ? 44 : 96, lineHeight: 0.9,
              letterSpacing: isMobile ? -2 : -3, marginTop: 18, color: P.card, animationDelay: '.1s',
            }}>
              HASTA<br />
              <span style={{ color: '#ffffff' }} className="pop-stroke">-60%</span><br />
              EN GAMING
            </div>
            <div className="pop-fade-up" style={{ fontSize: isMobile ? 12 : 16, marginTop: 14, maxWidth: 380, lineHeight: 1.4, fontWeight: 500, animationDelay: '.2s' }}>
              Sillas, teclados, audífonos, joysticks. Hasta agotar stock.
            </div>
            <div className="pop-fade-up" style={{ display: 'flex', gap: 12, marginTop: 20, alignItems: 'center', flexWrap: 'wrap', animationDelay: '.3s' }}>
              <PopButton variant="primary" size={isMobile ? 'md' : 'lg'} onClick={() => navigate('listing', { category: 'Ofertas' })}>VER OFERTAS →</PopButton>
              <div style={{ color: P.card, fontSize: isMobile ? 11 : 13 }}>
                <div style={{ fontWeight: 700 }}>Termina en</div>
                <div style={{ fontFamily: P.display, fontSize: isMobile ? 16 : 22, letterSpacing: 1, display: 'flex', gap: 6, alignItems: 'baseline' }}>
                  <span>{timer.d}D</span><span>{pad(timer.h)}H</span><span>{pad(timer.m)}M</span>
                  <span className="pop-pulse" style={{ color: '#ffffff' }}>{pad(timer.s)}S</span>
                </div>
              </div>
            </div>
          </div>
        </div>

        <div style={{ display: 'grid', gridTemplateRows: '1fr 1fr', gap: isMobile ? 12 : 20 }}>
          <div onClick={() => navigate('listing', { category: 'Smartwatch' })} className="pop-lift"
            style={{ background: P.blue, color: P.card, border: `3px solid ${P.ink}`, borderRadius: isMobile ? 14 : 20,
              padding: isMobile ? 18 : 24, boxShadow: `5px 5px 0 ${P.ink}`, position: 'relative', overflow: 'hidden',
              cursor: 'pointer', display: 'flex', flexDirection: 'row', alignItems: 'stretch', minHeight: isMobile ? 140 : 0 }}>
            {/* Text */}
            <div style={{ flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'space-between' }}>
              <div>
                <div style={{ display: 'inline-block', background: P.yellow, color: P.ink, padding: '4px 10px',
                  borderRadius: 999, fontFamily: P.display, fontSize: 11, border: `2px solid ${P.ink}` }}>NUEVOS</div>
                <div style={{ fontFamily: P.display, fontSize: isMobile ? 24 : 32, lineHeight: 1, marginTop: 12, letterSpacing: -1 }}>
                  Smartwatch<br />desde <span style={{ color: P.yellow }}>$100</span>
                </div>
              </div>
              <div style={{ fontSize: 12, fontWeight: 600 }}>18 modelos · todas las marcas →</div>
            </div>
            {/* Image */}
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center',
              flex: isMobile ? '0 0 100px' : '0 0 44%' }}>
              <img src="assets/smartwatch.png" alt="Smartwatch"
                style={{ width: '100%', height: 'auto', maxHeight: isMobile ? 110 : 210,
                  objectFit: 'contain', filter: 'drop-shadow(4px 4px 0 rgba(0,0,0,0.3))' }}
                onError={e => { e.currentTarget.style.display = 'none'; }} />
            </div>
          </div>
          <div onClick={() => navigate('listing', { category: 'Cargadores' })} className="pop-lift"
            style={{ background: P.green, color: P.card, border: `3px solid ${P.ink}`, borderRadius: isMobile ? 14 : 20,
              padding: isMobile ? 18 : 24, boxShadow: `5px 5px 0 ${P.ink}`, position: 'relative', overflow: 'hidden',
              cursor: 'pointer', display: 'flex', flexDirection: 'row', alignItems: 'stretch', minHeight: isMobile ? 140 : 0 }}>
            {/* Text */}
            <div style={{ flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'space-between' }}>
              <div>
                <div style={{ display: 'inline-block', background: P.card, color: P.green, padding: '4px 10px',
                  borderRadius: 999, fontFamily: P.display, fontSize: 11, border: `2px solid ${P.ink}` }}>2x1</div>
                <div style={{ fontFamily: P.display, fontSize: isMobile ? 24 : 32, lineHeight: 1, marginTop: 12, letterSpacing: -1 }}>
                  Cables y<br />cargadores
                </div>
              </div>
              <div style={{ fontSize: 12, fontWeight: 600 }}>Llévate 2, paga 1 · solo hoy →</div>
            </div>
            {/* Image */}
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center',
              flex: isMobile ? '0 0 100px' : '0 0 44%' }}>
              <img src="assets/cableycargador.png" alt="Cables y cargadores"
                style={{ width: '100%', height: 'auto', maxHeight: isMobile ? 110 : 210,
                  objectFit: 'contain', filter: 'drop-shadow(4px 4px 0 rgba(0,0,0,0.3))' }}
                onError={e => { e.currentTarget.style.display = 'none'; }} />
            </div>
          </div>
        </div>
      </div>

      {/* Flash bar */}
      <div style={{ padding: isMobile ? '0 16px 16px' : '0 32px 24px' }}>
        <div className="pop-bounce-in" style={{
          background: P.red, color: P.card, border: `3px solid ${P.ink}`, borderRadius: 16,
          padding: isMobile ? '14px 16px' : '18px 24px',
          display: 'flex', alignItems: 'center', gap: isMobile ? 12 : 24,
          boxShadow: `5px 5px 0 ${P.ink}`, flexWrap: 'wrap',
        }}>
          <div style={{ fontFamily: P.display, fontSize: isMobile ? 20 : 32, letterSpacing: -1, whiteSpace: 'nowrap' }}>⏱ FLASH SALE</div>
          {!isMobile && (
            <div style={{ flex: 1, fontSize: 14, fontWeight: 600, lineHeight: 1.3 }}>
              Audífonos, smartwatch y power banks con hasta -45% · termina cuando se agoten unidades.
            </div>
          )}
          <div style={{ display: 'flex', gap: 6 }}>
            {[pad(timer.h), pad(timer.m), pad(timer.s)].map((n, i) => (
              <div key={i} style={{
                background: P.ink, color: '#ffffff', padding: isMobile ? '6px 8px' : '8px 12px', borderRadius: 8,
                fontFamily: P.display, fontSize: isMobile ? 18 : 22, letterSpacing: 1, minWidth: isMobile ? 38 : 48, textAlign: 'center',
              }}>{n}</div>
            ))}
          </div>
          <PopButton variant="primary" size={isMobile ? 'sm' : 'md'} onClick={() => navigate('listing', { category: 'Ofertas' })}>VER</PopButton>
        </div>
      </div>

      {/* Top sellers */}
      <div style={{ padding: isMobile ? '8px 16px 24px' : '8px 32px 32px' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 18, gap: 12, flexWrap: 'wrap' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 14, flexWrap: 'wrap' }}>
            <div className="pop-press" style={{ background: P.yellow, border: `2px solid ${P.ink}`, padding: '6px 12px', borderRadius: 8,
              fontFamily: P.display, fontSize: 12, letterSpacing: 1, boxShadow: `2px 2px 0 ${P.ink}` }}>🔥 TOP VENTAS</div>
            <div style={{ fontFamily: P.display, fontSize: isMobile ? 22 : 28, letterSpacing: -1 }}>Lo que más se mueve</div>
          </div>
          <div onClick={() => navigate('listing')} style={{ fontSize: 12, fontWeight: 600, borderBottom: `2px solid ${P.ink}`, paddingBottom: 2, cursor: 'pointer' }}>
            Ver todos los 240 →
          </div>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: isMobile ? 'repeat(2,1fr)' : 'repeat(5,1fr)', gap: 12 }}>
          {top.map((p, i) => (
            <div key={p.id} className="pop-fade-up" style={{ animationDelay: `${Math.min(i, 9) * 0.05}s` }}>
              <ProductCard product={p} onClick={() => navigate('pdp', { id: p.id })} onAddToCart={addToCart} />
            </div>
          ))}
        </div>
      </div>

      {/* Promo banners */}
      <div style={{ padding: isMobile ? '8px 16px 24px' : '8px 32px 32px' }}>
        <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : '1fr 1fr', gap: isMobile ? 12 : 20 }}>

          {/* Tarjeta izquierda — Cupón primera compra */}
          <div className="pop-lift" style={{
            background: P.yellow, border: `3px solid ${P.ink}`, borderRadius: 20, padding: isMobile ? 22 : 28,
            boxShadow: `5px 5px 0 ${P.ink}`, display: 'flex', flexDirection: 'column', justifyContent: 'space-between', minHeight: 200,
            position: 'relative', overflow: 'hidden',
          }}>
            <div className="pop-dots" style={{ position: 'absolute', inset: 0, opacity: 0.15 }}></div>
            <div style={{ position: 'relative' }}>
              <div style={{ display: 'inline-block', background: P.ink, color: '#ffffff', padding: '4px 12px',
                borderRadius: 999, fontFamily: P.display, fontSize: 11, letterSpacing: 1 }}>PRIMERA COMPRA</div>
              {promoSent ? (
                <div className="pop-bounce-in">
                  <div style={{ fontFamily: P.display, fontSize: isMobile ? 26 : 32, lineHeight: 1.1, marginTop: 12, letterSpacing: -1 }}>
                    ¡Listo! 🎉<br />Revisá tu email
                  </div>
                  <div style={{ fontSize: 13, marginTop: 10, fontWeight: 600, lineHeight: 1.5 }}>
                    Te enviamos tu código de descuento.<br />¡Válido por 7 días!
                  </div>
                </div>
              ) : (
                <>
                  <div style={{ fontFamily: P.display, fontSize: isMobile ? 28 : 36, lineHeight: 1, marginTop: 12, letterSpacing: -1 }}>
                    Registrate y<br />obtenés <span style={{ color: P.red }}>10% OFF</span>
                  </div>
                  <div style={{ fontSize: 13, marginTop: 10, fontWeight: 600 }}>
                    En tu primera compra · sin mínimo de compra
                  </div>
                  <div style={{ display: 'flex', gap: 6, marginTop: 14, flexWrap: 'wrap' }}>
                    <input
                      type="email"
                      placeholder="tu@email.com"
                      value={promoEmail}
                      onChange={e => setPromoEmail(e.target.value)}
                      onKeyDown={e => e.key === 'Enter' && promoEmail.includes('@') && setPromoSent(true)}
                      style={{
                        flex: 1, minWidth: 0, padding: '10px 14px', border: `2px solid ${P.ink}`,
                        borderRadius: 10, fontFamily: P.font, fontSize: 13, outline: 'none',
                        background: 'rgba(255,255,255,0.7)', boxShadow: `inset 2px 2px 0 rgba(0,0,0,0.08)`,
                      }}
                    />
                    <PopButton variant="dark" size="md"
                      onClick={() => promoEmail.includes('@') && setPromoSent(true)}>
                      OBTENER →
                    </PopButton>
                  </div>
                </>
              )}
            </div>
          </div>

          {/* Tarjeta derecha — WhatsApp */}
          <div className="pop-lift" style={{
            background: P.purple, border: `3px solid ${P.ink}`, borderRadius: 20, padding: isMobile ? 22 : 28,
            boxShadow: `5px 5px 0 ${P.ink}`, display: 'flex', flexDirection: 'column', justifyContent: 'space-between', minHeight: 200,
            position: 'relative', overflow: 'hidden',
          }}>
            <div style={{ position: 'absolute', top: 16, right: 16, fontSize: 80, opacity: 0.12, lineHeight: 1 }}>💬</div>
            <div style={{ position: 'relative' }}>
              <div style={{ display: 'inline-block', background: P.ink, color: P.card, padding: '4px 12px',
                borderRadius: 999, fontFamily: P.display, fontSize: 11, letterSpacing: 1 }}>SOPORTE</div>
              <div style={{ fontFamily: P.display, fontSize: isMobile ? 28 : 36, lineHeight: 1, marginTop: 12, letterSpacing: -1 }}>
                ¿Dudas?<br /><span style={{ color: '#25d366' }}>WhatsApp</span>
              </div>
              <div style={{ fontSize: 13, marginTop: 10, fontWeight: 600, lineHeight: 1.5 }}>
                Asesoramiento personalizado con nuestro equipo.<br />
                <span style={{ opacity: 0.7 }}>Lun–Vie · 9:00 a 18:00 hs</span>
              </div>
            </div>
            {/* ↓ Reemplazá el número con el WhatsApp real de la tienda */}
            <a href="https://wa.me/59891620401?text=Hola%2C%20quisiera%20hacer%20una%20consulta" target="_blank" rel="noopener"
              style={{ textDecoration: 'none', marginTop: 16, alignSelf: 'flex-start' }}>
              <PopButton variant="dark" size="md" icon={<span style={{ fontSize: 16 }}>💬</span>}>
                ESCRIBIR POR WHATSAPP
              </PopButton>
            </a>
          </div>

        </div>
      </div>

      {/* New arrivals */}
      <div style={{ padding: isMobile ? '8px 16px 32px' : '8px 32px 40px' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 18, gap: 12, flexWrap: 'wrap' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 14, flexWrap: 'wrap' }}>
            <div className="pop-press" style={{ background: P.green, color: P.card, border: `2px solid ${P.ink}`, padding: '6px 12px', borderRadius: 8,
              fontFamily: P.display, fontSize: 12, letterSpacing: 1, boxShadow: `2px 2px 0 ${P.ink}` }}>🆕 RECIÉN LLEGADOS</div>
            <div style={{ fontFamily: P.display, fontSize: isMobile ? 22 : 28, letterSpacing: -1 }}>Nuevo en la tienda</div>
          </div>
          <div onClick={() => navigate('listing')} style={{ fontSize: 12, fontWeight: 600, borderBottom: `2px solid ${P.ink}`, paddingBottom: 2, cursor: 'pointer' }}>Ver todo →</div>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr 1fr' : 'repeat(5,1fr)', gap: isMobile ? 12 : 12 }}>
          {newArrivals.map((p, i) => (
            <div key={p.id} className="pop-fade-up" style={{ animationDelay: `${i * 0.05}s` }}>
              <ProductCard product={p} onClick={() => navigate('pdp', { id: p.id })} onAddToCart={addToCart} />
            </div>
          ))}
        </div>
      </div>

    </div>
  );
}

window.HomeScreen = HomeScreen;
