// zeus-pages.jsx — Home, Shop, Detail, HowItWorks, SellerPortal

const cats = ['Todos','Muebles','Hogar','Coleccionismo','Ropa y textil','Arte','Electrodomésticos','Otros'];
const PAGE_SIZE = 12;

/* ── HOME ── */
function Home({ t, setPage, setSelectedProduct }) {
  const products = useProducts();
  const recent = getRecentlyViewed().map(id => products.find(p => p.id === id)).filter(Boolean).slice(0, 4);
  const featured = products.filter(p => p.status !== 'vendido').slice(0, 4);

  return (
    <div>
      {/* ─────────── HERO: qué hacemos / para quién / quién está detrás ─────────── */}
      <section className="zv-section" style={{ background: t.bg, padding: '56px 32px 56px', textAlign: 'center' }}>
        <div style={{ maxWidth: 900, margin: '0 auto' }}>
          <h1 className="zv-big-title" style={{ fontSize: 'clamp(36px,6.5vw,72px)', fontWeight: 900, color: t.text, lineHeight: 1.05, letterSpacing: '-1.5px', marginBottom: 18 }}>
            Vendemos por ti<br/><span style={{ color: t.primary }}>lo que ya no usas</span>
          </h1>

          <p style={{ fontSize: 'clamp(18px,2.5vw,22px)', color: t.textMid, lineHeight: 1.55, maxWidth: 640, margin: '0 auto 14px' }}>
            Tú haces <strong style={{ color: t.text }}>una foto con el móvil</strong>. Nosotros lo valoramos, lo publicamos, gestionamos el envío al comprador y te ingresamos el dinero cuando se vende.
          </p>

          <BigWhatsAppButton t={t} />

          <div style={{ marginTop: 16, display:'flex', justifyContent:'center', gap:20, flexWrap:'wrap', fontSize:15, color:t.textLight }}>
            <span>📞 <a href={'tel:+34' + WA_NUMBER.slice(2)} style={{ color:t.text, fontWeight:700, textDecoration:'none' }}>699 601 627</a></span>
            <span>✉️ hola@zeusventas.es</span>
          </div>
        </div>
      </section>

      {/* ─────────── CÓMO FUNCIONA — 3 pasos súper claros ─────────── */}
      <section className="zv-section" style={{ padding: '64px 32px', background: t.bgAlt }}>
        <div style={{ maxWidth: 1000, margin: '0 auto', textAlign: 'center' }}>
          <h2 style={{ fontSize: 'clamp(30px,5vw,40px)', fontWeight: 900, color: t.text, marginBottom: 10 }}>Así de fácil</h2>
          <p style={{ fontSize: 18, color: t.textMid, marginBottom: 40 }}>Solo 3 pasos. Tú haces el primero, yo hago los otros dos.</p>

          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit,minmax(240px,1fr))', gap: 20 }}>
            {[
              { n:'1', icon:'📸', title:'Haz una foto', body:'Con el móvil, no importa la calidad. Si no sabes, te ayuda un familiar o te guiamos por teléfono.', tu:true },
              { n:'2', icon:'🏷️', title:'Lo vendo por ti', body:'Yo le pongo precio, escribo el anuncio, lo publico, atiendo a los compradores y organizo el envío.', tu:false },
              { n:'3', icon:'💶', title:'Tú cobras', body:'El dinero llega a tu cuenta 48h después de que el comprador reciba el objeto. Si no se vende, no pagas nada.', tu:false },
            ].map(s => (
              <div key={s.n} style={{ background:t.card, borderRadius:20, padding:'28px 22px', border:`2px solid ${s.tu ? t.primary : t.border}`, textAlign:'center', position:'relative' }}>
                {s.tu && (
                  <div style={{ position:'absolute', top:-12, left:'50%', transform:'translateX(-50%)', background:t.primary, color:'#fff', padding:'4px 14px', borderRadius:100, fontSize:11, fontWeight:800, letterSpacing:1 }}>
                    LO HACES TÚ
                  </div>
                )}
                <div style={{ width:52, height:52, borderRadius:'50%', background:t.primary, color:'#fff', display:'flex', alignItems:'center', justifyContent:'center', fontWeight:900, fontSize:22, margin:'0 auto 14px' }}>{s.n}</div>
                <div style={{ fontSize:42, marginBottom:10 }}>{s.icon}</div>
                <h3 style={{ fontSize:20, fontWeight:800, color:t.text, marginBottom:8 }}>{s.title}</h3>
                <p style={{ fontSize:15, color:t.textMid, lineHeight:1.55 }}>{s.body}</p>
              </div>
            ))}
          </div>

          <div style={{ marginTop: 40 }}><BigWhatsAppButton t={t} label="ENVIAR MI PRIMERA FOTO" /></div>
        </div>
      </section>

      {/* ─────────── QUÉ ACEPTAMOS — ejemplos visibles ─────────── */}
      <section className="zv-section" style={{ padding: '56px 28px', background: t.bg }}>
        <div style={{ maxWidth: 1000, margin: '0 auto' }}>
          <div style={{ textAlign:'center', marginBottom:36 }}>
            <h2 style={{ fontSize: 'clamp(28px,5vw,36px)', fontWeight: 900, color: t.text, marginBottom: 10 }}>¿Qué puedes vender?</h2>
            <p style={{ fontSize: 17, color: t.textMid, maxWidth:600, margin:'0 auto', lineHeight:1.55 }}>
              Si está en buen estado y alguien lo quiere, lo vendemos. Estos son los más habituales:
            </p>
          </div>

          <div style={{ display:'grid', gridTemplateColumns:'repeat(auto-fill,minmax(140px,1fr))', gap:14 }}>
            {[
              { icon:'🪑', label:'Muebles', ej:'Sillas, mesas, armarios' },
              { icon:'🔧', label:'Herramientas', ej:'Eléctricas, manuales, jardinería' },
              { icon:'📺', label:'Electrodomésticos', ej:'Pequeños y grandes' },
              { icon:'🍽️', label:'Vajillas y cubertería', ej:'Porcelana, plata, antiguas' },
              { icon:'📚', label:'Libros y discos', ej:'Colecciones, vinilos' },
              { icon:'🚲', label:'Bicicletas', ej:'Adultos y niños' },
              { icon:'🎨', label:'Arte y decoración', ej:'Cuadros, lámparas, espejos' },
              { icon:'⌚', label:'Relojes y joyas', ej:'De marca o coleccionismo' },
              { icon:'👕', label:'Ropa de marca', ej:'Vintage, abrigos, bolsos' },
              { icon:'🧸', label:'Juguetes', ej:'Antiguos, de colección' },
              { icon:'🎻', label:'Instrumentos', ej:'Música, audio antiguo' },
              { icon:'📦', label:'Y más cosas', ej:'Pregúntanos sin compromiso' },
            ].map(c => (
              <div key={c.label} style={{ background:t.card, border:`1px solid ${t.border}`, borderRadius:14, padding:'18px 12px', textAlign:'center' }}>
                <div style={{ fontSize:34, marginBottom:6 }}>{c.icon}</div>
                <div style={{ fontSize:14, fontWeight:800, color:t.text, marginBottom:3 }}>{c.label}</div>
                <div style={{ fontSize:11, color:t.textLight, lineHeight:1.4 }}>{c.ej}</div>
              </div>
            ))}
          </div>

          <p style={{ textAlign:'center', fontSize:14, color:t.textLight, marginTop:24, fontStyle:'italic' }}>
            ¿No sabes si lo tuyo encaja? <a href={waUrl('Hola, tengo un objeto y no sé si me lo aceptaríais. Os mando foto.')} target="_blank" rel="noopener noreferrer" style={{ color:t.primary, fontWeight:700 }}>Pregúntanos por WhatsApp</a> — sin compromiso.
          </p>
        </div>
      </section>

      {/* Stats bar */}
      <div style={{ background: t.primary, padding: '32px 20px', display: 'flex', justifyContent: 'center', gap: 'clamp(24px,6vw,80px)', flexWrap: 'wrap' }}>
        {[
          ['+' + products.length, 'Objetos publicados'],
          ['Gratis', 'Sin coste inicial'],
          ['24h', 'Te contactamos hoy'],
          [products.filter(p=>p.status==='vendido').length || '0', 'Ya vendidos'],
        ].map(([n, l]) => (
          <div key={l} style={{ textAlign: 'center' }}>
            <div style={{ fontSize: 'clamp(28px,5vw,38px)', fontWeight: 900, color: '#fff' }}>{n}</div>
            <div style={{ fontSize: 15, color: 'rgba(255,255,255,0.7)', marginTop: 2 }}>{l}</div>
          </div>
        ))}
      </div>

      {/* Featured products */}
      <section className="zv-section" style={{ padding: '64px 32px', background: t.bgAlt }}>
        <div style={{ maxWidth: 1280, margin: '0 auto' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', marginBottom: 32, flexWrap: 'wrap', gap: 12 }}>
            <div>
              <h2 style={{ fontSize: 'clamp(28px,5vw,36px)', fontWeight: 900, color: t.text, marginBottom: 4 }}>
                {products.length > 0 ? 'Objetos en venta ahora' : 'Sé el primero en vender'}
              </h2>
              <p style={{ fontSize: 17, color: t.textMid }}>{products.length} artículos gestionados</p>
            </div>
            {products.length > 4 && (
              <button onClick={() => setPage('shop')} style={{ background: t.primary, color: '#fff', border: 'none', cursor: 'pointer', padding: '12px 28px', borderRadius: 100, fontSize: 16, fontWeight: 700, fontFamily: 'Outfit,sans-serif' }}>Ver todos →</button>
            )}
          </div>
          {featured.length > 0 ? (
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill,minmax(260px,1fr))', gap: 20 }}>
              {featured.map(p => (
                <ProductCard key={p.id} p={p} t={t} onClick={() => { addRecentlyViewed(p.id); setSelectedProduct(p); setPage('detail'); }} />
              ))}
            </div>
          ) : (
            <EmptyState t={t} icon="🏷️" title="Todavía no hay anuncios" subtitle="Publica el primer objeto y empieza a vender." actionLabel="Publicar primer anuncio" onAction={() => setPage('publish')} />
          )}
        </div>
      </section>

      {/* Recently viewed */}
      {recent.length > 0 && (
        <section style={{ padding: '48px 32px', background: t.bg }}>
          <div style={{ maxWidth: 1280, margin: '0 auto' }}>
            <h2 style={{ fontSize: 24, fontWeight: 800, color: t.text, marginBottom: 24 }}>Vistos recientemente</h2>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill,minmax(220px,1fr))', gap: 16 }}>
              {recent.map(p => (
                <ProductCard key={p.id} p={p} t={t} onClick={() => { addRecentlyViewed(p.id); setSelectedProduct(p); setPage('detail'); }} />
              ))}
            </div>
          </div>
        </section>
      )}

      {/* Share section */}
      <section className="zv-section" style={{ padding:'48px 16px', boxSizing:'border-box', overflowX:'hidden', background: t.bg }}>
        <div style={{ maxWidth: 640, margin: '0 auto', textAlign: 'center' }}>
          <div style={{ fontSize: 32, marginBottom: 10 }}>📤</div>
          <h2 style={{ fontSize:'clamp(22px,4vw,28px)', fontWeight: 900, color: t.text, marginBottom: 10 }}>
            ¿Conoces a alguien que quiera vender cosas que le sobran?
          </h2>
          <p style={{ fontSize: 16, color: t.textMid, marginBottom: 22, lineHeight: 1.5 }}>
            Envíale Zeus Ventas por WhatsApp. Le harás un favor.
          </p>
          <button
            onClick={async () => {
              const res = await shareZeusVentas('site');
              if (res === 'copied') alert('Enlace copiado. Pégalo en WhatsApp.');
            }}
            style={{
              background: t.primary, color: '#fff', border: 'none',
              cursor: 'pointer', padding: '14px 28px', borderRadius: 100,
              fontSize: 16, fontWeight: 700, fontFamily: 'Outfit,sans-serif',
              display: 'inline-flex', alignItems: 'center', gap: 10
            }}
          >
            <span style={{ fontSize: 18 }}>📤</span> Enviar a un amigo
          </button>
        </div>
      </section>

      {/* ─────────── COMISIÓN Y PLAZOS — claro y sin letra pequeña ─────────── */}
      <section className="zv-section" style={{ padding: '64px 32px', background: t.primary }}>
        <div style={{ maxWidth: 720, margin: '0 auto', textAlign: 'center' }}>
          <h2 style={{ fontSize: 'clamp(30px,5vw,40px)', fontWeight: 900, color: '#fff', marginBottom: 12 }}>Sin letra pequeña</h2>
          <p style={{ fontSize: 'clamp(17px,2.5vw,20px)', color: 'rgba(255,255,255,0.9)', lineHeight: 1.6, marginBottom: 28 }}>
            Si no se vende, no pagas nada. Si se vende, sabes desde el primer día cuánto cobras y cuándo.
          </p>

          {/* Ejemplo numérico */}
          <div style={{ background: 'rgba(255,255,255,0.15)', borderRadius: 20, padding: '24px 20px', marginBottom: 18 }}>
            <div style={{ fontSize: 14, color: 'rgba(255,255,255,0.8)', marginBottom: 12, letterSpacing:1 }}>EJEMPLO: OBJETO DE 100€</div>
            <div className="zv-commission-numbers" style={{ display: 'flex', justifyContent: 'center', gap: 40, flexWrap: 'wrap' }}>
              <div>
                <div style={{ fontSize: 42, fontWeight: 900, color: '#fff' }}>80€</div>
                <div style={{ color: 'rgba(255,255,255,0.8)', fontSize: 14 }}>Para ti</div>
              </div>
              <div style={{ alignSelf:'center', fontSize:28, color:'rgba(255,255,255,0.5)' }}>+</div>
              <div>
                <div style={{ fontSize: 42, fontWeight: 900, color: '#fff' }}>20€</div>
                <div style={{ color: 'rgba(255,255,255,0.8)', fontSize: 14 }}>Comisión Zeus</div>
              </div>
            </div>
          </div>

          {/* Tabla de comisiones por tramo */}
          <div style={{ background: 'rgba(255,255,255,0.1)', borderRadius: 16, padding: '18px 20px', marginBottom: 24, fontSize:14, color:'rgba(255,255,255,0.95)' }}>
            <div style={{ fontWeight:700, marginBottom:10, fontSize:13, letterSpacing:1 }}>COMISIÓN SEGÚN PRECIO DE VENTA</div>
            <div style={{ display:'grid', gridTemplateColumns:'repeat(auto-fit, minmax(120px, 1fr))', gap:8, fontSize:13 }}>
              <div>Hasta 50€<br/><strong style={{ fontSize:18 }}>30%</strong></div>
              <div>50–200€<br/><strong style={{ fontSize:18 }}>25%</strong></div>
              <div>200–500€<br/><strong style={{ fontSize:18 }}>20%</strong></div>
              <div>Más de 500€<br/><strong style={{ fontSize:18 }}>15%</strong></div>
            </div>
          </div>

          {/* CUÁNDO COBRO YO — la pregunta que más temen los mayores */}
          <div style={{ background: '#fff', color: t.text, borderRadius: 16, padding: '22px 24px', marginBottom: 28, textAlign:'left' }}>
            <div style={{ fontSize:13, fontWeight:800, color:t.primary, letterSpacing:1, marginBottom:10, textTransform:'uppercase' }}>
              💶 ¿Cuándo cobro yo?
            </div>
            <ul style={{ listStyle:'none', padding:0, margin:0, fontSize:15, lineHeight:1.7 }}>
              <li style={{ marginBottom:6 }}>✅ <strong>Por transferencia bancaria</strong> a tu cuenta (también en mano si lo prefieres).</li>
              <li style={{ marginBottom:6 }}>✅ <strong>48h después</strong> de que el comprador reciba el objeto y confirme que está bien.</li>
              <li>✅ <strong>Sin sorpresas:</strong> tú firmas un acuerdo simple antes del envío con el precio mínimo y la comisión.</li>
            </ul>
          </div>

          <BigWhatsAppButton t={t} label="EMPEZAR — ES GRATIS" />
        </div>
      </section>
    </div>
  );
}

/* ── SHOP ── */
function Shop({ t, setPage, setSelectedProduct }) {
  const products = useProducts();
  const favs = useFavorites();
  const [filter, setFilter] = React.useState('Todos');
  const [search, setSearch] = React.useState('');
  const [sort, setSort] = React.useState('newest');
  const [priceMin, setPriceMin] = React.useState('');
  const [priceMax, setPriceMax] = React.useState('');
  const [showSold, setShowSold] = React.useState(false);
  const [showFavs, setShowFavs] = React.useState(false);
  const [page, setPageNum] = React.useState(1);

  // Reset page on filter change
  React.useEffect(() => setPageNum(1), [filter, search, sort, priceMin, priceMax, showSold, showFavs]);

  const filtered = products.filter(p => {
    if (!showSold && p.status === 'vendido') return false;
    if (showFavs && !favs.includes(p.id)) return false;
    if (filter !== 'Todos' && p.cat !== filter) return false;
    if (search && !(p.title||'').toLowerCase().includes(search.toLowerCase())) return false;
    if (priceMin && p.price < Number(priceMin)) return false;
    if (priceMax && p.price > Number(priceMax)) return false;
    return true;
  }).sort((a, b) => {
    if (sort === 'price_asc') return a.price - b.price;
    if (sort === 'price_desc') return b.price - a.price;
    return b.publishedAt - a.publishedAt; // newest
  });

  const totalPages = Math.ceil(filtered.length / PAGE_SIZE);
  const paginated = filtered.slice((page - 1) * PAGE_SIZE, page * PAGE_SIZE);

  const inputS = { padding: '10px 16px', borderRadius: 100, border: `2px solid ${t.border}`, background: t.card, color: t.text, fontFamily: 'Outfit,sans-serif', fontSize: 15, outline: 'none' };

  return (
    <div className="zv-section" style={{ background: t.bg, minHeight: '100vh', padding: '48px 32px' }}>
      <div style={{ maxWidth: 1280, margin: '0 auto' }}>
        <h1 className="zv-big-title" style={{ fontSize: 'clamp(36px,6vw,46px)', fontWeight: 900, color: t.text, marginBottom: 6 }}>Productos</h1>
        <p style={{ fontSize: 17, color: t.textMid, marginBottom: 28 }}>Encuentra objetos con historia cerca de ti</p>

        {/* Search row */}
        <div style={{ marginBottom: 10 }}>
          <input value={search} onChange={e => setSearch(e.target.value)} placeholder="Buscar artículos…" style={{ ...inputS, width:'100%', boxSizing:'border-box', borderRadius: 100 }} />
        </div>
        {/* Filters row — sort + min + max alineados */}
        <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr 1fr', gap: 10, marginBottom: 16 }}>
          <select value={sort} onChange={e => setSort(e.target.value)} style={{ ...inputS, cursor: 'pointer', appearance: 'none', paddingRight: 32, minWidth:0 }}>
            <option value="newest">Más recientes</option>
            <option value="price_asc">Precio: menor primero</option>
            <option value="price_desc">Precio: mayor primero</option>
          </select>
          <input type="number" inputMode="decimal" value={priceMin} onChange={e => setPriceMin(e.target.value)} placeholder="Min €" style={{ ...inputS, minWidth:0, textAlign:'center' }} />
          <input type="number" inputMode="decimal" value={priceMax} onChange={e => setPriceMax(e.target.value)} placeholder="Máx €" style={{ ...inputS, minWidth:0, textAlign:'center' }} />
        </div>

        {/* Category pills + toggles */}
        <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginBottom: 32, alignItems: 'center' }}>
          {cats.map(c => (
            <button key={c} onClick={() => setFilter(c)} style={{ padding: '10px 20px', borderRadius: 100, fontSize: 15, fontWeight: 600, cursor: 'pointer', fontFamily: 'Outfit,sans-serif', border: `2px solid ${filter === c ? t.primary : t.border}`, background: filter === c ? t.primary : t.card, color: filter === c ? '#fff' : t.textMid }}>{c}</button>
          ))}
          <div style={{ marginLeft: 'auto', display: 'flex', gap: 8 }}>
            <button onClick={() => setShowFavs(v => !v)} style={{ padding: '10px 18px', borderRadius: 100, fontSize: 15, fontWeight: 600, cursor: 'pointer', fontFamily: 'Outfit,sans-serif', border: `2px solid ${showFavs ? t.accent : t.border}`, background: showFavs ? t.accentLight : t.card, color: showFavs ? t.accent : t.textMid }}>❤️ Favoritos ({favs.length})</button>
            <button onClick={() => setShowSold(v => !v)} style={{ padding: '10px 18px', borderRadius: 100, fontSize: 15, fontWeight: 600, cursor: 'pointer', fontFamily: 'Outfit,sans-serif', border: `2px solid ${showSold ? t.primary : t.border}`, background: showSold ? t.primary : t.card, color: showSold ? '#fff' : t.textMid }}>Ver vendidos</button>
          </div>
        </div>

        {products.length === 0 ? (
          <EmptyState t={t} icon="🛍️" title="Aún no hay productos" subtitle="Sé el primero en publicar un anuncio." actionLabel="Publicar un anuncio" onAction={() => setPage('publish')} />
        ) : (
          <>
            <p style={{ fontSize: 14, color: t.textLight, marginBottom: 16 }}>{filtered.length} resultado{filtered.length !== 1 ? 's' : ''}</p>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill,minmax(260px,1fr))', gap: 20 }}>
              {paginated.map(p => (
                <ProductCard key={p.id} p={p} t={t} onClick={() => { addRecentlyViewed(p.id); setSelectedProduct(p); setPage('detail'); }} />
              ))}
            </div>
            {filtered.length === 0 && (
              <div style={{ textAlign: 'center', padding: '60px 0', color: t.textLight, fontSize: 18 }}>Sin resultados para los filtros seleccionados.</div>
            )}
            {/* Pagination */}
            {totalPages > 1 && (
              <div style={{ display: 'flex', justifyContent: 'center', gap: 8, marginTop: 40, flexWrap: 'wrap' }}>
                <button onClick={() => setPageNum(p => Math.max(1, p - 1))} disabled={page === 1} style={{ padding: '10px 20px', borderRadius: 100, border: `2px solid ${t.border}`, background: t.card, cursor: page === 1 ? 'default' : 'pointer', fontFamily: 'Outfit,sans-serif', fontWeight: 600, opacity: page === 1 ? 0.4 : 1 }}>←</button>
                {Array.from({ length: totalPages }, (_, i) => i + 1).map(n => (
                  <button key={n} onClick={() => setPageNum(n)} style={{ padding: '10px 20px', borderRadius: 100, border: `2px solid ${n === page ? t.primary : t.border}`, background: n === page ? t.primary : t.card, color: n === page ? '#fff' : t.text, cursor: 'pointer', fontFamily: 'Outfit,sans-serif', fontWeight: 700 }}>{n}</button>
                ))}
                <button onClick={() => setPageNum(p => Math.min(totalPages, p + 1))} disabled={page === totalPages} style={{ padding: '10px 20px', borderRadius: 100, border: `2px solid ${t.border}`, background: t.card, cursor: page === totalPages ? 'default' : 'pointer', fontFamily: 'Outfit,sans-serif', fontWeight: 600, opacity: page === totalPages ? 0.4 : 1 }}>→</button>
              </div>
            )}
          </>
        )}
      </div>
    </div>
  );
}

/* ── DETAIL ── */
/* Helper: ¿este comprador (según localStorage) tiene oferta pendiente en esta op? */
function hasMyOfferPending(op) {
  if (!op) return false;
  const myPhone = (localStorage.getItem('zeus_buyer_phone') || '').replace(/\s/g,'');
  if (!myPhone) return false;
  const norm = s => (s || '').replace(/\s/g,'');
  return (op.offers || []).some(o => o.status === 'pendiente' && norm(o.buyerPhone) === myPhone)
      || (op.counterOffers || []).some(c => c.status === 'pendiente' && norm(c.buyerPhone) === myPhone);
}

/* ── BUYER ACTIONS BLOCK ── Lo que ve el comprador respecto a sus ofertas y contraofertas */
function BuyerActionsBlock({ t, product, op, shippingInfo }) {
  if (!op) return null;
  const myPhone = (localStorage.getItem('zeus_buyer_phone') || '').replace(/\s/g,'');
  if (!myPhone) return null;
  const norm = s => (s || '').replace(/\s/g,'');

  // Mis ofertas pendientes (esperando respuesta del vendedor)
  const myPendingOffers = (op.offers || []).filter(o => o.status === 'pendiente' && norm(o.buyerPhone) === myPhone);
  // Mis ofertas contraofertadas (el vendedor me pide más dinero)
  const counterOffersForMe = (op.counterOffers || []).filter(c => c.status === 'pendiente' && norm(c.buyerPhone) === myPhone);
  // Mis ofertas aceptadas
  const myAcceptedOffer = (op.offers || []).find(o => o.status === 'aceptada' && norm(o.buyerPhone) === myPhone);
  const myAcceptedCounter = (op.counterOffers || []).find(c => c.status === 'aceptada' && norm(c.buyerPhone) === myPhone);
  // Mis ofertas rechazadas (más reciente)
  const myRejectedOffer = (op.offers || []).filter(o => o.status === 'rechazada' && norm(o.buyerPhone) === myPhone).sort((a,b)=>b.rejectedAt-a.rejectedAt)[0];

  if (!myPendingOffers.length && !counterOffersForMe.length && !myAcceptedOffer && !myAcceptedCounter && !myRejectedOffer) return null;

  const handleRetire = (offer) => {
    if (!confirm(`¿Retirar tu oferta de ${offer.amount}€?`)) return;
    retireOffer(op.id, offer.id);
  };

  const handleAcceptCounter = (counter) => {
    if (!confirm(`¿Aceptar la contraoferta de ${counter.amount}€ del vendedor?`)) return;
    acceptCounterOffer(op.id, counter.id, product.size, shippingInfo?.priceNum || null);
  };
  const handleRejectCounter = (counter) => {
    if (!confirm(`¿Rechazar la contraoferta de ${counter.amount}€?`)) return;
    rejectCounterOffer(op.id, counter.id);
  };

  return (
    <div style={{ marginBottom:14 }}>
      {/* Oferta aceptada por el vendedor */}
      {(myAcceptedOffer || myAcceptedCounter) && (() => {
        const accepted = myAcceptedCounter || myAcceptedOffer;
        return (
          <div style={{ background:'#dcfce7', border:'2px solid #15803d', borderRadius:14, padding:'16px 18px', marginBottom:10 }}>
            <div style={{ fontSize:13, fontWeight:800, color:'#15803d', letterSpacing:1, marginBottom:8, textTransform:'uppercase' }}>
              ✅ Tu oferta fue aceptada
            </div>
            <div style={{ fontSize:16, color:t.text, lineHeight:1.5, marginBottom:10 }}>
              El vendedor aceptó tu oferta de <strong style={{ color:'#15803d' }}>{accepted.amount}€</strong>.
            </div>
            <div style={{ background:'#fff', borderRadius:10, padding:'12px 14px', fontSize:14, color:t.textMid, lineHeight:1.6 }}>
              <strong style={{ color:t.text }}>Próximo paso:</strong> Te contactaremos en las próximas horas al <strong>{localStorage.getItem('zeus_buyer_phone') || 'tu teléfono'}</strong> para enviarte el enlace de pago seguro.
              {shippingInfo && shippingInfo.priceNum && (
                <div style={{ marginTop:6 }}>Total: {accepted.amount}€ + {shippingInfo.price} envío = <strong style={{ color:t.text }}>{(Number(accepted.amount) + shippingInfo.priceNum).toFixed(2).replace('.', ',')}€</strong></div>
              )}
            </div>
          </div>
        );
      })()}

      {/* Contraoferta del vendedor pendiente de mi respuesta */}
      {counterOffersForMe.map(c => (
        <div key={c.id} style={{ background:'#ede9fe', border:'2px solid #7c3aed', borderRadius:14, padding:'16px 18px', marginBottom:10 }}>
          <div style={{ fontSize:13, fontWeight:800, color:'#5b21b6', letterSpacing:1, marginBottom:8, textTransform:'uppercase' }}>
            🟣 El vendedor te ha contraofertado
          </div>
          <div style={{ fontSize:14, color:t.textMid, marginBottom:6 }}>Pediste:</div>
          <div style={{ fontSize:18, color:t.textLight, marginBottom:8, textDecoration:'line-through' }}>
            {(op.offers || []).find(o => o.id === c.originalOfferId)?.amount || '?'}€
          </div>
          <div style={{ fontSize:14, color:t.textMid, marginBottom:6 }}>Su contraoferta:</div>
          <div style={{ fontSize:28, fontWeight:900, color:'#5b21b6', marginBottom:10 }}>{c.amount}€</div>
          {c.message && (
            <div style={{ background:'#fff', borderRadius:8, padding:'10px 12px', marginBottom:12, fontSize:14, color:t.textMid, fontStyle:'italic' }}>
              💬 "{c.message}"
            </div>
          )}
          <div style={{ display:'flex', gap:8, flexWrap:'wrap' }}>
            <button
              onClick={()=>handleAcceptCounter(c)}
              style={{ flex:'1 1 auto', minWidth:120, background:'#15803d', color:'#fff', border:'none', cursor:'pointer', padding:'12px 14px', borderRadius:100, fontSize:14, fontWeight:700, fontFamily:'Outfit,sans-serif' }}
            >
              ✅ Aceptar {c.amount}€
            </button>
            <button
              onClick={()=>handleRejectCounter(c)}
              style={{ flex:'1 1 auto', minWidth:120, background:'#fff', color:'#b91c1c', border:'1px solid #fecaca', cursor:'pointer', padding:'12px 14px', borderRadius:100, fontSize:14, fontWeight:700, fontFamily:'Outfit,sans-serif' }}
            >
              ❌ Rechazar
            </button>
          </div>
        </div>
      ))}

      {/* Mis ofertas pendientes (esperando vendedor) */}
      {myPendingOffers.map(o => (
        <div key={o.id} style={{ background:'#fef3c7', border:'1px solid #fcd34d', borderRadius:12, padding:'14px 16px', marginBottom:10 }}>
          <div style={{ fontSize:13, fontWeight:800, color:'#92400e', letterSpacing:1, marginBottom:6, textTransform:'uppercase' }}>
            ⏳ Tu oferta está pendiente
          </div>
          <div style={{ fontSize:14, color:t.text, lineHeight:1.5, marginBottom:10 }}>
            Has ofrecido <strong>{o.amount}€</strong> · enviada {timeSince(o.time)}.<br/>
            <span style={{ fontSize:13, color:t.textMid }}>Te avisamos por WhatsApp cuando el vendedor responda.</span>
          </div>
          <button
            onClick={()=>handleRetire(o)}
            style={{ background:'none', color:'#b91c1c', border:'1px solid #fecaca', cursor:'pointer', padding:'8px 14px', borderRadius:100, fontSize:12, fontWeight:700, fontFamily:'Outfit,sans-serif' }}
          >
            Retirar oferta
          </button>
        </div>
      ))}

      {/* Mi última oferta rechazada */}
      {!myPendingOffers.length && !counterOffersForMe.length && !myAcceptedOffer && !myAcceptedCounter && myRejectedOffer && (
        <div style={{ background:'#fee2e2', border:'1px solid #fca5a5', borderRadius:12, padding:'12px 14px', marginBottom:10, fontSize:13, color:'#991b1b' }}>
          ❌ Tu oferta de {myRejectedOffer.amount}€ fue rechazada{myRejectedOffer.rejectReason ? ': "' + myRejectedOffer.rejectReason + '"' : '.'} Puedes hacer una nueva oferta abajo.
        </div>
      )}
    </div>
  );
}

/* ── BUY NOW MODAL ── Compra directa por el precio pedido (auto-acepta) */
function BuyNowModal({ t, product, shippingInfo, onClose, onConfirmed }) {
  const [step, setStep] = React.useState(1);  // 1=datos, 2=confirmado
  const [name, setName] = React.useState(() => localStorage.getItem('zeus_buyer_name') || '');
  const [phone, setPhone] = React.useState(() => localStorage.getItem('zeus_buyer_phone') || '');
  const [email, setEmail] = React.useState(() => localStorage.getItem('zeus_buyer_email') || '');
  const [submitting, setSubmitting] = React.useState(false);

  const cleanName = (name || '').trim();
  const cleanPhone = (phone || '').replace(/\D/g, '');
  const validForm = cleanName.length >= 2 && cleanPhone.length >= 9;

  const handleConfirm = () => {
    if (!validForm) return;
    setSubmitting(true);

    const SHIPPING_PRICES = { pequeno: 7.90, mediano: 13.90, grande: 24.90, voluminoso: null };
    const shippingPrice = product.size ? SHIPPING_PRICES[product.size] : null;

    // 1. Crear la oferta al precio pedido
    const result = makeOffer(product.id, {
      buyerName: cleanName,
      buyerPhone: phone.trim(),
      buyerEmail: email.trim(),
      amount: Number(product.price),
      message: '🛒 Compra directa al precio pedido',
    });

    if (result.ok) {
      // 2. Auto-aceptar la oferta (compra directa)
      acceptOffer(result.op.id, result.offer.id, product.size, shippingPrice);
      // 3. Guardar comprador
      try {
        localStorage.setItem('zeus_buyer_phone', phone.trim());
        localStorage.setItem('zeus_buyer_name', cleanName);
        if (email.trim()) localStorage.setItem('zeus_buyer_email', email.trim());
      } catch {}
      setStep(2);
      setTimeout(() => { onConfirmed(); }, 3000);
    } else {
      alert(result.error || 'No se pudo procesar la compra. Inténtalo más tarde.');
      setSubmitting(false);
    }
  };

  const total = shippingInfo && shippingInfo.priceNum
    ? (Number(product.price) + shippingInfo.priceNum).toFixed(2).replace('.', ',')
    : null;

  return (
    <div onClick={onClose} style={{ position:'fixed', inset:0, background:'rgba(0,0,0,0.6)', zIndex:1000, display:'flex', alignItems:'center', justifyContent:'center', padding:16 }}>
      <div onClick={e=>e.stopPropagation()} style={{ background:t.bg, borderRadius:20, width:'100%', maxWidth:480, maxHeight:'90vh', overflow:'auto' }}>

        {step === 1 && (
          <>
            {/* Header */}
            <div style={{ background:t.primary, padding:'20px 24px', borderRadius:'20px 20px 0 0', display:'flex', justifyContent:'space-between', alignItems:'center' }}>
              <div>
                <div style={{ fontSize:20, fontWeight:900, color:'#fff' }}>💳 Comprar ahora</div>
                <div style={{ fontSize:13, color:'rgba(255,255,255,0.75)', marginTop:2 }}>{product.title}</div>
              </div>
              <button onClick={onClose} style={{ background:'rgba(255,255,255,0.2)', color:'#fff', border:'none', cursor:'pointer', width:32, height:32, borderRadius:'50%', fontSize:18, fontWeight:700, fontFamily:'Outfit,sans-serif' }}>✕</button>
            </div>

            <div style={{ padding:'22px 24px' }}>
              {/* Resumen del precio */}
              <div style={{ background:t.bgAlt, borderRadius:14, padding:'16px 18px', marginBottom:18 }}>
                <div style={{ fontSize:13, fontWeight:700, color:t.textLight, letterSpacing:1, marginBottom:8, textTransform:'uppercase' }}>Resumen de tu compra</div>
                <div style={{ display:'flex', justifyContent:'space-between', fontSize:15, color:t.text, marginBottom:6 }}>
                  <span>Precio del objeto</span>
                  <strong>{product.price}€</strong>
                </div>
                {shippingInfo && (
                  <div style={{ display:'flex', justifyContent:'space-between', fontSize:14, color:t.textMid, marginBottom:6 }}>
                    <span>Envío {shippingInfo.dot} {shippingInfo.label}</span>
                    <span>{shippingInfo.price}</span>
                  </div>
                )}
                {!shippingInfo && (
                  <div style={{ fontSize:13, color:t.textLight, fontStyle:'italic', marginBottom:6 }}>+ Envío a calcular según tu dirección</div>
                )}
                {total && (
                  <div style={{ borderTop:`1px solid ${t.border}`, marginTop:8, paddingTop:8, display:'flex', justifyContent:'space-between', fontSize:18, fontWeight:900, color:t.text }}>
                    <span>Total</span>
                    <span style={{ color:t.primary }}>{total}€</span>
                  </div>
                )}
              </div>

              <div style={{ background:'#dcfce7', border:'1px solid #86efac', borderRadius:10, padding:'10px 14px', marginBottom:18, fontSize:13, color:'#15803d', lineHeight:1.5 }}>
                ✅ <strong>Compra inmediata:</strong> al confirmar, tu compra queda reservada y recibirás el enlace de pago en breve.
              </div>

              {/* Datos comprador */}
              <label style={{ fontSize:14, fontWeight:700, color:t.text, display:'block', marginBottom:6 }}>Tu nombre</label>
              <input
                type="text" value={name} onChange={e=>setName(e.target.value)} autoCapitalize="words"
                placeholder="Nombre y apellido"
                style={{ width:'100%', padding:'12px 14px', borderRadius:10, border:`1px solid ${t.border}`, background:t.card, fontSize:15, color:t.text, fontFamily:'Outfit,sans-serif', outline:'none', marginBottom:14, boxSizing:'border-box' }}
              />

              <label style={{ fontSize:14, fontWeight:700, color:t.text, display:'block', marginBottom:6 }}>Tu teléfono (con WhatsApp)</label>
              <input
                type="tel" inputMode="tel" value={phone} onChange={e=>setPhone(e.target.value)}
                placeholder="699 601 627"
                style={{ width:'100%', padding:'12px 14px', borderRadius:10, border:`1px solid ${t.border}`, background:t.card, fontSize:15, color:t.text, fontFamily:'Outfit,sans-serif', outline:'none', marginBottom:14, boxSizing:'border-box' }}
              />

              <label style={{ fontSize:14, fontWeight:700, color:t.text, display:'block', marginBottom:6 }}>Email <span style={{ color:t.textLight, fontWeight:400 }}>(opcional)</span></label>
              <input
                type="email" inputMode="email" value={email} onChange={e=>setEmail(e.target.value)}
                placeholder="tu@email.com"
                style={{ width:'100%', padding:'12px 14px', borderRadius:10, border:`1px solid ${t.border}`, background:t.card, fontSize:15, color:t.text, fontFamily:'Outfit,sans-serif', outline:'none', marginBottom:18, boxSizing:'border-box' }}
              />

              <button
                onClick={handleConfirm}
                disabled={!validForm || submitting}
                style={{
                  width:'100%', padding:'16px', borderRadius:100, border:'none',
                  background: validForm ? t.primary : t.border,
                  color:'#fff', fontSize:17, fontWeight:800, fontFamily:'Outfit,sans-serif',
                  cursor: validForm && !submitting ? 'pointer' : 'not-allowed',
                  boxShadow: validForm ? '0 4px 14px rgba(61,87,64,0.3)' : 'none',
                }}
              >
                {submitting ? 'Procesando...' : `💳 Confirmar compra · ${product.price}€`}
              </button>

              <p style={{ fontSize:12, color:t.textLight, textAlign:'center', marginTop:12, lineHeight:1.5 }}>
                Tras confirmar, te contactaremos para coordinar el pago y el envío.
              </p>
            </div>
          </>
        )}

        {step === 2 && (
          <div style={{ padding:'48px 16px', boxSizing:'border-box', overflowX:'hidden', textAlign:'center' }}>
            <div style={{ fontSize:60, marginBottom:14 }}>✅</div>
            <h2 style={{ fontSize:22, fontWeight:900, color:t.text, marginBottom:8 }}>¡Compra confirmada!</h2>
            <p style={{ fontSize:15, color:t.textMid, lineHeight:1.6, marginBottom:14 }}>
              Has comprado <strong style={{ color:t.text }}>{product.title}</strong> por <strong style={{ color:t.primary }}>{product.price}€</strong>.
            </p>
            <p style={{ fontSize:14, color:t.textMid, lineHeight:1.6, marginBottom:14 }}>
              Te contactaremos al <strong style={{ color:t.text }}>{phone}</strong> en las próximas horas con el enlace de pago seguro.
            </p>
            <p style={{ fontSize:13, color:t.textLight, fontStyle:'italic' }}>
              El objeto queda reservado a tu nombre.
            </p>
          </div>
        )}

      </div>
    </div>
  );
}

/* ── OFFER MODAL ── Modal para que el comprador haga oferta */
function OfferModal({ t, product, shippingInfo, onClose, onSent, initialAmount }) {
  const suggestedAmount = initialAmount !== undefined ? String(initialAmount) : String(Math.round(Number(product.price) * 0.9));
  const [step, setStep] = React.useState(1);  // 1=datos, 2=enviado
  const [amount, setAmount] = React.useState(suggestedAmount);
  const [name, setName] = React.useState(() => localStorage.getItem('zeus_buyer_name') || '');
  const [phone, setPhone] = React.useState(() => localStorage.getItem('zeus_buyer_phone') || '');
  const [email, setEmail] = React.useState(() => localStorage.getItem('zeus_buyer_email') || '');
  const [message, setMessage] = React.useState('');
  const [submitting, setSubmitting] = React.useState(false);

  // Validaciones más robustas
  const numAmount = Number(amount);
  const numPrice = Number(product.price);
  const cleanPhone = (phone || '').replace(/\D/g, '');  // Solo dígitos
  const cleanName = (name || '').trim();

  const validAmount = !isNaN(numAmount) && numAmount > 0 && numAmount <= numPrice;
  const validName = cleanName.length >= 2;
  const validPhone = cleanPhone.length >= 9;
  const validForm = validAmount && validName && validPhone;

  const handleSubmit = async () => {
    if (!validForm) return;
    setSubmitting(true);
    const result = makeOffer(product.id, {
      buyerName: cleanName,
      buyerPhone: phone.trim(),
      buyerEmail: email.trim(),
      amount: numAmount,
      message: message.trim(),
    });
    if (result.ok) {
      // Recordar al comprador en este navegador para mostrarle sus contraofertas
      try {
        localStorage.setItem('zeus_buyer_phone', phone.trim());
        localStorage.setItem('zeus_buyer_name', cleanName);
        if (email.trim()) localStorage.setItem('zeus_buyer_email', email.trim());
      } catch {}
      setStep(2);
      setTimeout(() => { onSent(); }, 2500);
    } else {
      alert(result.error || 'No se pudo enviar la oferta. Inténtalo más tarde.');
      setSubmitting(false);
    }
  };

  return (
    <div onClick={onClose} style={{ position:'fixed', inset:0, background:'rgba(0,0,0,0.6)', zIndex:1000, display:'flex', alignItems:'center', justifyContent:'center', padding:16 }}>
      <div onClick={e=>e.stopPropagation()} style={{ background:t.bg, borderRadius:20, width:'100%', maxWidth:480, maxHeight:'90vh', overflow:'auto' }}>

        {step === 1 && (
          <>
            {/* Header */}
            <div style={{ background:t.primary, padding:'20px 24px', borderRadius:'20px 20px 0 0', display:'flex', justifyContent:'space-between', alignItems:'center' }}>
              <div>
                <div style={{ fontSize:20, fontWeight:900, color:'#fff' }}>💬 Hacer oferta</div>
                <div style={{ fontSize:13, color:'rgba(255,255,255,0.75)', marginTop:2 }}>{product.title}</div>
              </div>
              <button onClick={onClose} style={{ background:'rgba(255,255,255,0.2)', color:'#fff', border:'none', cursor:'pointer', width:32, height:32, borderRadius:'50%', fontSize:18, fontWeight:700, fontFamily:'Outfit,sans-serif' }}>✕</button>
            </div>

            {/* Body */}
            <div style={{ padding:'22px 24px' }}>

              {/* Aviso */}
              <div style={{ background:t.bgAlt, borderRadius:12, padding:'12px 14px', marginBottom:18, fontSize:13, color:t.textMid, lineHeight:1.5 }}>
                ℹ️ Tu oferta se enviará al vendedor a través de Zeus Ventas. Te avisamos en 24-48h cuando responda.
              </div>

              {/* Importe */}
              <label style={{ fontSize:14, fontWeight:700, color:t.text, display:'block', marginBottom:6 }}>Tu oferta (€) <span style={{ color:t.textLight, fontWeight:400, fontSize:12 }}>· precio pedido {product.price}€</span></label>
              <input
                type="number" inputMode="decimal" min="1" max={product.price}
                value={amount}
                onChange={e=>setAmount(e.target.value)}
                placeholder="Escribe tu oferta"
                style={{ width:'100%', padding:'14px 16px', borderRadius:12, border:`2px solid ${validAmount ? '#15803d' : t.border}`, background:t.card, fontSize:18, fontWeight:700, color:t.text, fontFamily:'Outfit,sans-serif', outline:'none', marginBottom:6, boxSizing:'border-box' }}
              />
              {amount && !validAmount && (
                <div style={{ fontSize:12, color:'#dc2626', marginBottom:8 }}>La oferta debe ser entre 1€ y {product.price}€</div>
              )}
              {shippingInfo && shippingInfo.priceNum && validAmount && (
                <div style={{ fontSize:13, color:t.textLight, marginBottom:14, lineHeight:1.5 }}>
                  + Envío {shippingInfo.dot} {shippingInfo.label}: {shippingInfo.price} · <strong style={{ color:t.text }}>Total: {(Number(amount) + shippingInfo.priceNum).toFixed(2).replace('.', ',')}€</strong>
                </div>
              )}
              {(!shippingInfo || !shippingInfo.priceNum) && validAmount && (
                <div style={{ fontSize:13, color:t.textLight, marginBottom:14, lineHeight:1.5, fontStyle:'italic' }}>+ Envío a calcular según tu dirección</div>
              )}

              {/* Datos comprador */}
              <label style={{ fontSize:14, fontWeight:700, color:t.text, display:'block', marginBottom:6 }}>Tu nombre</label>
              <input
                type="text" value={name} onChange={e=>setName(e.target.value)} autoCapitalize="words"
                placeholder="Nombre y apellido"
                style={{ width:'100%', padding:'12px 14px', borderRadius:10, border:`1px solid ${t.border}`, background:t.card, fontSize:15, color:t.text, fontFamily:'Outfit,sans-serif', outline:'none', marginBottom:14, boxSizing:'border-box' }}
              />

              <label style={{ fontSize:14, fontWeight:700, color:t.text, display:'block', marginBottom:6 }}>Tu teléfono (con WhatsApp)</label>
              <input
                type="tel" inputMode="tel" value={phone} onChange={e=>setPhone(e.target.value)}
                placeholder="699 601 627"
                style={{ width:'100%', padding:'12px 14px', borderRadius:10, border:`1px solid ${t.border}`, background:t.card, fontSize:15, color:t.text, fontFamily:'Outfit,sans-serif', outline:'none', marginBottom:14, boxSizing:'border-box' }}
              />

              <label style={{ fontSize:14, fontWeight:700, color:t.text, display:'block', marginBottom:6 }}>Email <span style={{ color:t.textLight, fontWeight:400 }}>(opcional)</span></label>
              <input
                type="email" inputMode="email" value={email} onChange={e=>setEmail(e.target.value)}
                placeholder="tu@email.com"
                style={{ width:'100%', padding:'12px 14px', borderRadius:10, border:`1px solid ${t.border}`, background:t.card, fontSize:15, color:t.text, fontFamily:'Outfit,sans-serif', outline:'none', marginBottom:14, boxSizing:'border-box' }}
              />

              <label style={{ fontSize:14, fontWeight:700, color:t.text, display:'block', marginBottom:6 }}>Mensaje al vendedor <span style={{ color:t.textLight, fontWeight:400 }}>(opcional)</span></label>
              <textarea
                value={message} onChange={e=>setMessage(e.target.value)}
                placeholder="Ej: ¿está en buen estado? ¿Funciona?"
                style={{ width:'100%', padding:'12px 14px', borderRadius:10, border:`1px solid ${t.border}`, background:t.card, fontSize:15, color:t.text, fontFamily:'Outfit,sans-serif', outline:'none', marginBottom:18, boxSizing:'border-box', minHeight:70, resize:'vertical' }}
              />

              <button
                onClick={handleSubmit}
                disabled={!validForm || submitting}
                style={{
                  width:'100%', padding:'16px', borderRadius:100, border:'none',
                  background: validForm ? '#25d366' : t.border,
                  color:'#fff', fontSize:17, fontWeight:800, fontFamily:'Outfit,sans-serif',
                  cursor: validForm && !submitting ? 'pointer' : 'not-allowed',
                  boxShadow: validForm ? '0 4px 14px rgba(37,211,102,0.3)' : 'none',
                }}
              >
                {submitting ? 'Enviando...' : '💬 Enviar oferta'}
              </button>

              <p style={{ fontSize:12, color:t.textLight, textAlign:'center', marginTop:12, lineHeight:1.5 }}>
                Al enviar aceptas que tu nombre y teléfono se compartan con el vendedor a través de Zeus Ventas.
              </p>
            </div>
          </>
        )}

        {step === 2 && (
          <div style={{ padding:'48px 16px', boxSizing:'border-box', overflowX:'hidden', textAlign:'center' }}>
            <div style={{ fontSize:60, marginBottom:14 }}>✅</div>
            <h2 style={{ fontSize:22, fontWeight:900, color:t.text, marginBottom:8 }}>Oferta enviada</h2>
            <p style={{ fontSize:15, color:t.textMid, lineHeight:1.6, marginBottom:20 }}>
              Hemos enviado tu oferta de <strong style={{ color:t.text }}>{amount}€</strong> al vendedor.
              Te avisaremos por WhatsApp al <strong style={{ color:t.text }}>{phone}</strong> en cuanto responda.
            </p>
            <p style={{ fontSize:13, color:t.textLight, fontStyle:'italic' }}>
              Normalmente responden en 24-48h.
            </p>
          </div>
        )}

      </div>
    </div>
  );
}

function Detail({ t, product, setPage }) {
  const products = useProducts();
  const favs = useFavorites();
  const [contacted, setContacted] = React.useState(false);
  const [lightbox, setLightbox] = React.useState(false);
  const [shareOpen, setShareOpen] = React.useState(false);
  const [offerSent, setOfferSent] = React.useState(false);
  const [offerModal, setOfferModal] = React.useState(false);
  const [buyNowModal, setBuyNowModal] = React.useState(false);
  const [paymentModalOpen, setPaymentModalOpen] = React.useState(false);
  const [activePhoto, setActivePhoto] = React.useState(0);
  const [op, setOp] = React.useState(null);
  const [refresh, setRefresh] = React.useState(0);

  const p = product || (products.length > 0 ? products[0] : null);
  const fav = p ? favs.includes(p.id) : false;

  React.useEffect(() => { if (p) incrementViews(p.id); }, [p?.id]);

  // Cargar/actualizar la operación del producto
  React.useEffect(() => {
    if (!p) return;
    setOp(getProductOperation(p.id));
    const handler = () => { setOp(getProductOperation(p.id)); setRefresh(r => r+1); };
    window.addEventListener('zeus:operations-updated', handler);
    return () => window.removeEventListener('zeus:operations-updated', handler);
  }, [p?.id]);

  if (!p) return (
    <div className="zv-section" style={{ background:t.bg, minHeight:'100vh', padding:'80px 32px' }}>
      <div style={{ maxWidth:600, margin:'0 auto' }}>
        <EmptyState t={t} icon="🔍" title="Anuncio no disponible" subtitle="Este anuncio ya no existe." actionLabel="Volver a productos" onAction={() => setPage('shop')} />
      </div>
    </div>
  );

  const productUrl = window.location.origin + window.location.pathname + '#product/' + p.id;

  // Mapeo de tamaño a precio de envío y etiqueta
  const SHIPPING_TIERS = {
    pequeno:    { dot:'🟢', label:'Pequeño',    price:'7,90€',   priceNum: 7.90,  desc:'Caja pequeña, hasta 3 kg' },
    mediano:    { dot:'🟡', label:'Mediano',    price:'13,90€',  priceNum: 13.90, desc:'Caja grande, hasta 10 kg' },
    grande:     { dot:'🟠', label:'Grande',     price:'24,90€',  priceNum: 24.90, desc:'Voluminoso, hasta 25 kg' },
    voluminoso: { dot:'🔴', label:'Voluminoso', price:'A medida',priceNum: null,  desc:'Mueble grande o pesado' },
  };
  const shippingInfo = p.size ? SHIPPING_TIERS[p.size] : null;

  return (
    <div className="zv-section" style={{ background:t.bg, minHeight:'100vh', padding:'48px 16px', boxSizing:'border-box', overflowX:'hidden' }}>
      {lightbox && p.photo && <Lightbox src={p.photo} alt={p.title} onClose={() => setLightbox(false)} />}
      {shareOpen && <ShareMenu product={p} t={t} onClose={() => setShareOpen(false)} />}
      {offerModal && <OfferModal t={t} product={p} shippingInfo={shippingInfo} onClose={()=>setOfferModal(false)} onSent={()=>{ setOfferSent(true); setOfferModal(false); }} />}
      {buyNowModal && <BuyNowModal t={t} product={p} shippingInfo={shippingInfo} onClose={()=>setBuyNowModal(false)} onConfirmed={()=>{ setOfferSent(true); setBuyNowModal(false); }} />}

      <div style={{ maxWidth:1000, margin:'0 auto' }}>
        <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:24, flexWrap:'wrap', gap:12 }}>
          <button onClick={() => setPage('shop')} style={{ background:'none', border:'none', color:t.primary, cursor:'pointer', fontSize:17, fontWeight:600, fontFamily:'Outfit,sans-serif' }}>← Volver</button>
          <div style={{ display:'flex', gap:10 }}>
            <button onClick={() => toggleFavorite(p.id)} style={{ padding:'10px 20px', borderRadius:100, border:`2px solid ${fav ? '#e53e3e' : t.border}`, background: fav ? '#fff0f0' : t.card, cursor:'pointer', fontFamily:'Outfit,sans-serif', fontWeight:700, fontSize:15, color: fav?'#e53e3e':t.textMid }}>
              {fav ? '❤️ Guardado' : '🤍 Guardar'}
            </button>
            <button onClick={() => setShareOpen(true)} style={{ padding:'10px 20px', borderRadius:100, border:`2px solid ${t.border}`, background:t.card, cursor:'pointer', fontFamily:'Outfit,sans-serif', fontWeight:700, fontSize:15, color:t.textMid }}>↑ Compartir</button>
          </div>
        </div>

        <div className="zv-detail-grid" style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:40 }}>
          {/* Galería de fotos */}
          <div>
            {/* Foto principal */}
            <div style={{ borderRadius:16, overflow:'hidden', cursor:'zoom-in', marginBottom:10, background:t.bgAlt }} onClick={() => setLightbox(true)}>
              {(() => {
                const allPhotos = p.photos?.length ? p.photos : (p.photo ? [{ dataUrl: p.photo }] : []);
                const current = allPhotos[activePhoto];
                const src = current?.dataUrl || current?.url || current || p.photo || '';
                return src
                  ? <img src={src} alt={p.title} style={{ width:'100%', height:340, objectFit:'cover', display:'block' }} />
                  : <div style={{ width:'100%', height:340, display:'flex', alignItems:'center', justifyContent:'center', fontSize:48 }}>📦</div>;
              })()}
            </div>

            {/* Miniaturas */}
            {(() => {
              const allPhotos = p.photos?.length ? p.photos : (p.photo ? [{ dataUrl: p.photo }] : []);
              if (allPhotos.length <= 1) return null;
              return (
                <div style={{ display:'flex', gap:8, overflowX:'auto', paddingBottom:4 }}>
                  {allPhotos.map((ph, i) => {
                    const src = ph?.dataUrl || ph?.url || ph || '';
                    return (
                      <div key={i} onClick={() => setActivePhoto(i)}
                        style={{ flexShrink:0, width:72, height:72, borderRadius:10, overflow:'hidden', cursor:'pointer', border: activePhoto===i ? `3px solid ${t.primary}` : `2px solid ${t.border}`, transition:'border 0.15s' }}>
                        <img src={src} alt="" style={{ width:'100%', height:'100%', objectFit:'cover', display:'block' }} />
                      </div>
                    );
                  })}
                </div>
              );
            })()}

            <div style={{ textAlign:'center', fontSize:13, color:t.textLight, marginTop:6 }}>
              {(() => {
                const allPhotos = p.photos?.length ? p.photos : (p.photo ? [p.photo] : []);
                return allPhotos.length > 1 ? `${activePhoto+1} / ${allPhotos.length} fotos · Clic para ampliar` : 'Clic para ampliar';
              })()}
            </div>
          </div>

          {/* Info */}
          <div>
            <div style={{ display:'flex', gap:8, flexWrap:'wrap', marginBottom:12 }}>
              <span style={{ background:t.accentLight, color:t.accent, borderRadius:100, padding:'5px 14px', fontSize:14, fontWeight:700 }}>{p.cat||'Otros'}</span>
              <StatusBadge status={p.status} />
            </div>
            <h1 className="zv-big-title" style={{ fontSize:'clamp(28px,5vw,38px)', fontWeight:900, color:t.text, marginBottom:12, lineHeight:1.15 }}>{p.title}</h1>
            <div style={{ fontSize:'clamp(36px,7vw,46px)', fontWeight:900, color:t.primary, marginBottom:8 }}>{p.price}€</div>
            <p style={{ fontSize:14, color:t.textLight, marginBottom:20 }}>{p.views||0} personas han visto este anuncio</p>

            {p.desc && <p style={{ fontSize:17, color:t.textMid, lineHeight:1.7, marginBottom:24 }}>{p.desc}</p>}

            {/* Seller card */}
            <div style={{ background:t.card, border:`1px solid ${t.border}`, borderRadius:16, padding:20, marginBottom:24 }}>
              <div style={{ display:'flex', alignItems:'center', gap:14 }}>
                <div style={{ width:48, height:48, borderRadius:'50%', background:t.primary, display:'flex', alignItems:'center', justifyContent:'center' }}>
                  <span style={{ color:'#fff', fontWeight:900, fontSize:18 }}>{(p.seller||p.sellerName||'V')[0]}</span>
                </div>
                <div>
                  <div style={{ fontWeight:700, fontSize:17, color:t.text }}>{p.seller||abbreviateName(p.sellerName)}</div>
                  <div style={{ fontSize:14, color:t.textLight }}>Verificado · {p.location||p.city||'—'}</div>
                </div>
              </div>
            </div>

            {/* Offer input */}
            {/* Envío visible para el comprador */}
            {shippingInfo && p.status !== 'vendido' && (
              <div style={{ background:t.card, border:`1px solid ${t.border}`, borderRadius:14, padding:'14px 16px', marginBottom:14, display:'flex', alignItems:'center', gap:12 }}>
                <div style={{ fontSize:22, lineHeight:1 }}>{shippingInfo.dot}</div>
                <div style={{ flex:1, minWidth:0 }}>
                  <div style={{ fontSize:12, fontWeight:700, color:t.textLight, letterSpacing:1, textTransform:'uppercase' }}>📦 Envío</div>
                  <div style={{ fontSize:14, color:t.text }}>
                    <strong>{shippingInfo.label}</strong> · {shippingInfo.desc}
                  </div>
                </div>
                <div style={{ fontSize:18, fontWeight:900, color:t.primary, whiteSpace:'nowrap' }}>{shippingInfo.price}</div>
              </div>
            )}

            {/* Total para el comprador */}
            {shippingInfo && shippingInfo.priceNum !== null && p.status !== 'vendido' && (
              <div style={{ background:t.bgAlt, borderRadius:12, padding:'10px 16px', marginBottom:16, fontSize:14, color:t.textMid, display:'flex', justifyContent:'space-between', alignItems:'center' }}>
                <span>Total: producto + envío</span>
                <strong style={{ fontSize:18, color:t.text }}>{(Number(p.price) + shippingInfo.priceNum).toFixed(2).replace('.', ',')}€</strong>
              </div>
            )}

            {/* ── Badge de estado actual ── */}
            {op && op.status !== 'disponible' && (() => {
              const cfg = OP_LABELS[op.status];
              return (
                <div style={{ background:cfg.bg, color:cfg.color, padding:'10px 14px', borderRadius:10, marginBottom:14, fontSize:14, fontWeight:700, textAlign:'center', border:`1px solid ${cfg.color}30` }}>
                  {cfg.dot} Estado: {cfg.label}
                </div>
              );
            })()}

            {/* ── Bloque para comprador: ofertas/contraofertas dirigidas a él ── */}
            <BuyerActionsBlock t={t} product={p} op={op} shippingInfo={shippingInfo} />

            {/* ── Botones de acción (compra directa + oferta) ── */}
            
            {/* FORMA DE PAGO - SIEMPRE VISIBLE */}
            <div style={{ marginBottom:24 }}>
              <FormaPago 
                t={t}
                product={p}
                envio={shippingInfo?.priceNum || 0}
              />
            </div>

            {/* Botones secundarios */}
            {!offerSent && p.status !== 'vendido' && (!op || ['disponible', 'con_oferta'].includes(op.status)) && !hasMyOfferPending(op) && (
              <button onClick={() => setOfferModal(true)} style={{ background:'transparent', color:t.primary, border:`2px solid ${t.primary}`, cursor:'pointer', padding:'14px', borderRadius:100, fontSize:15, fontWeight:700, fontFamily:'Outfit,sans-serif', width:'100%', marginBottom:16 }}>
                💬 Hacer una oferta más baja
              </button>
            )}

            {offerSent && (
              <div style={{ background:'#dcfce7', border:'1px solid #86efac', borderRadius:14, padding:16, marginBottom:16, fontSize:15, fontWeight:600, color:'#15803d', textAlign:'center' }}>
                ✓ Oferta enviada<br/>
                <span style={{ fontWeight:400, fontSize:13, color:'#166534' }}>Te avisamos en 24-48h cuando el vendedor responda.</span>
              </div>
            )}

            {/* Contact button */}
            {contacted ? (
              <div style={{ background:t.accentLight, borderRadius:16, padding:20, textAlign:'center' }}>
                <div style={{ fontSize:28 }}>✅</div>
                <div style={{ fontSize:17, fontWeight:700, color:t.text, marginTop:6 }}>¡Mensaje enviado!</div>
              </div>
            ) : p.status === 'vendido' ? (
              <div style={{ background:t.bgAlt, borderRadius:16, padding:20, textAlign:'center', color:t.textLight, fontWeight:600 }}>Este artículo ya ha sido vendido</div>
            ) : (
              <button onClick={() => setContacted(true)} style={{ background:t.primary, color:'#fff', border:'none', cursor:'pointer', padding:'18px', borderRadius:100, fontSize:18, fontWeight:700, fontFamily:'Outfit,sans-serif', width:'100%' }}>Contactar al vendedor</button>
            )}

            {/* QR + share link */}
            <div style={{ marginTop:20, padding:16, background:t.card, borderRadius:14, border:`1px solid ${t.border}` }}>
              <div style={{ fontSize:13, color:t.textLight, marginBottom:10, fontWeight:600 }}>Enlace directo a este anuncio</div>
              <div style={{ display:'flex', gap:10, alignItems:'center', flexWrap:'wrap' }}>
                <div style={{ flex:1, fontSize:13, color:t.textMid, wordBreak:'break-all', fontFamily:'monospace', background:t.bgAlt, borderRadius:8, padding:'8px 12px' }}>{productUrl}</div>
                <img src={qrUrl(productUrl, 80)} alt="QR" style={{ width:60, height:60, borderRadius:8 }} />
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* Payment Modal - Sistema de pagos */}
      {paymentModalOpen && (
        <PaymentModal 
          t={t}
          product={p}
          shippingCost={shippingInfo?.priceNum || 0}
          onClose={() => setPaymentModalOpen(false)}
          onSuccess={(transaction) => {
            console.log('✅ Pago completado:', transaction);
            setOfferSent(true);
            setPaymentModalOpen(false);
            alert('¡Compra completada! Próximo paso: coordinación de entrega');
          }}
        />
      )}
    </div>
  );
}

/* ── HOW IT WORKS ── */
function HowItWorks({ t, setPage }) {
  const steps=[
    {n:'01',icon:'📸',title:'Haz una foto',body:'Con el móvil. No importa la calidad.'},
    {n:'02',icon:'🤖',title:'La IA valora',body:'Identifica el objeto y calcula el precio de mercado.'},
    {n:'03',icon:'✅',title:'Publicamos',body:'En nuestra web y otras plataformas. Completamente gratis.'},
    {n:'04',icon:'📦',title:'Recogemos y embalamos',body:'Vamos a tu domicilio y nos encargamos del packaging.'},
    {n:'05',icon:'🚚',title:'Enviamos con seguro',body:'Transporte asegurado hasta el comprador final.'},
    {n:'06',icon:'💶',title:'Cobras',body:'El dinero se ingresa cuando el comprador confirma la recepción.'},
  ];
  return (
    <div className="zv-section" style={{ background:t.bg, minHeight:'100vh', padding:'56px 32px' }}>
      <div style={{ maxWidth:800, margin:'0 auto' }}>
        <h1 className="zv-big-title" style={{ fontSize:'clamp(36px,7vw,52px)', fontWeight:900, color:t.text, marginBottom:6, lineHeight:1.1 }}>Cómo funciona</h1>
        <p style={{ fontSize:18, color:t.textMid, marginBottom:52 }}>Vender es fácil con Zeus Ventas.</p>
        <div style={{ display:'flex', flexDirection:'column' }}>
          {steps.map((s,i)=>(
            <div key={s.n} style={{ display:'flex', gap:24, paddingBottom:40, borderLeft:i<steps.length-1?`3px solid ${t.border}`:'3px solid transparent', marginLeft:24, paddingLeft:40, position:'relative' }}>
              <div style={{ position:'absolute', left:-24, top:0, width:48, height:48, borderRadius:'50%', background:t.primary, display:'flex', alignItems:'center', justifyContent:'center' }}>
                <span style={{ fontSize:22 }}>{s.icon}</span>
              </div>
              <div>
                <div style={{ fontSize:12, fontWeight:700, color:t.textLight, letterSpacing:2, marginBottom:4 }}>PASO {s.n}</div>
                <h3 style={{ fontSize:22, fontWeight:800, color:t.text, marginBottom:8 }}>{s.title}</h3>
                <p style={{ fontSize:16, color:t.textMid, lineHeight:1.6 }}>{s.body}</p>
              </div>
            </div>
          ))}
        </div>
        <div style={{ background:t.primary, borderRadius:20, padding:'32px 28px', textAlign:'center', marginTop:24 }}>
          <h2 style={{ fontSize:'clamp(24px,4vw,30px)', fontWeight:900, color:'#fff', marginBottom:10 }}>¿Listo para empezar?</h2>
          <p style={{ fontSize:17, color:'rgba(255,255,255,0.75)', marginBottom:24 }}>Publica tu primer anuncio en 5 minutos</p>
          <button onClick={()=>setPage('publish')} style={{ background:'#fff', color:t.primary, border:'none', cursor:'pointer', padding:'16px 32px', borderRadius:100, fontSize:17, fontWeight:700, fontFamily:'Outfit,sans-serif' }}>Vender un objeto</button>
        </div>
      </div>
    </div>
  );
}

/* ── SELLER PORTAL ── */
/* ── SELLER OFFERS BLOCK ── Gestión de ofertas para el vendedor */
function SellerOffersBlock({ t, product }) {
  const [op, setOp] = React.useState(() => getProductOperation(product.id));
  const [counterModal, setCounterModal] = React.useState(null);  // {offer} cuando se abre

  React.useEffect(() => {
    const handler = () => setOp(getProductOperation(product.id));
    window.addEventListener('zeus:operations-updated', handler);
    return () => window.removeEventListener('zeus:operations-updated', handler);
  }, [product.id]);

  if (!op || op.status === 'disponible') {
    return (
      <div style={{ background:'#f0f9ff', border:'1px dashed #bae6fd', borderRadius:12, padding:'14px 16px', marginBottom:14, fontSize:13, color:'#0369a1', textAlign:'center' }}>
        Aún no hay ofertas para este objeto. Te avisaremos cuando llegue alguna.
      </div>
    );
  }

  const pendingOffers = (op.offers || []).filter(o => o.status === 'pendiente');
  const pendingCounters = (op.counterOffers || []).filter(c => c.status === 'pendiente');
  const acceptedOffer = (op.offers || []).find(o => o.status === 'aceptada');
  const acceptedCounter = (op.counterOffers || []).find(c => c.status === 'aceptada');

  const handleAccept = (offer) => {
    if (!confirm(`¿Aceptar la oferta de ${offer.amount}€ de ${offer.buyerName}?`)) return;
    // Calcular envío según tier del producto
    const SHIPPING_PRICES = { pequeno: 7.90, mediano: 13.90, grande: 24.90, voluminoso: null };
    const shippingPrice = product.size ? SHIPPING_PRICES[product.size] : null;
    acceptOffer(op.id, offer.id, product.size, shippingPrice);
  };
  const handleReject = (offer) => {
    const reason = prompt(`Motivo del rechazo (opcional):\n\nOferta de ${offer.amount}€ de ${offer.buyerName}`);
    if (reason === null) return;
    rejectOffer(op.id, offer.id, reason);
  };

  // ── Si ya hay oferta aceptada → mostrar resumen ──
  if (acceptedOffer || acceptedCounter) {
    const accepted = acceptedCounter || acceptedOffer;
    const cfg = OP_LABELS[op.status];
    return (
      <div style={{ background:cfg.bg, border:`1px solid ${cfg.color}40`, borderRadius:12, padding:'14px 16px', marginBottom:14 }}>
        <div style={{ fontSize:13, fontWeight:700, color:cfg.color, letterSpacing:1, marginBottom:6, textTransform:'uppercase' }}>
          {cfg.dot} {cfg.label}
        </div>
        <div style={{ fontSize:14, color:t.text, lineHeight:1.5 }}>
          Oferta aceptada de <strong>{accepted.buyerName}</strong>: <strong style={{ color:cfg.color }}>{accepted.amount}€</strong>
        </div>
        {op.status === 'reservado' && (
          <div style={{ fontSize:12, color:t.textMid, marginTop:6, fontStyle:'italic' }}>Esperando que el comprador realice el pago. Te avisamos cuando se confirme.</div>
        )}
        {op.status === 'pagado' && (
          <div style={{ fontSize:12, color:t.textMid, marginTop:6, fontStyle:'italic' }}>✅ Pago recibido. Coordinaremos contigo el envío en breve.</div>
        )}
        {op.status === 'en_transito' && op.shipping?.trackingCode && (
          <div style={{ fontSize:12, color:t.textMid, marginTop:6 }}>📦 En tránsito · {op.shipping.carrier} · {op.shipping.trackingCode}</div>
        )}
      </div>
    );
  }

  // ── Hay ofertas pendientes (incluye contraofertas tuyas pendientes de respuesta) ──
  return (
    <div style={{ marginBottom:14 }}>
      {counterModal && (
        <CounterOfferModal
          t={t}
          offer={counterModal}
          opId={op.id}
          maxAmount={product.price}
          onClose={()=>setCounterModal(null)}
          onSent={()=>setCounterModal(null)}
        />
      )}

      {pendingOffers.length > 0 && (
        <div style={{ background:'#fef3c7', border:'1px solid #fcd34d', borderRadius:12, padding:'14px 16px', marginBottom:10 }}>
          <div style={{ fontSize:13, fontWeight:800, color:'#92400e', letterSpacing:1, marginBottom:10, textTransform:'uppercase' }}>
            🟡 {pendingOffers.length === 1 ? 'Tienes 1 oferta nueva' : `Tienes ${pendingOffers.length} ofertas nuevas`}
          </div>
          {pendingOffers.map(offer => (
            <div key={offer.id} style={{ background:'#fff', borderRadius:10, padding:'12px 14px', marginBottom:8, border:'1px solid #fde68a' }}>
              <div style={{ display:'flex', justifyContent:'space-between', alignItems:'flex-start', gap:10, marginBottom:8, flexWrap:'wrap' }}>
                <div>
                  <div style={{ fontSize:20, fontWeight:900, color:'#92400e' }}>{offer.amount}€</div>
                  <div style={{ fontSize:13, color:t.textMid }}>de {offer.buyerName} · {timeSince(offer.time)}</div>
                </div>
                <div style={{ fontSize:12, color:t.textLight, textAlign:'right' }}>
                  Pediste {product.price}€<br/>
                  <strong style={{ color: offer.amount >= product.price * 0.85 ? '#15803d' : '#a16207' }}>
                    {Math.round(offer.amount / product.price * 100)}%
                  </strong> del precio
                </div>
              </div>
              {offer.message && (
                <div style={{ background:t.bgAlt, borderRadius:8, padding:'8px 10px', marginBottom:10, fontSize:13, color:t.textMid, fontStyle:'italic' }}>
                  💬 "{offer.message}"
                </div>
              )}
              <div style={{ display:'flex', gap:6, flexWrap:'wrap' }}>
                <button
                  onClick={()=>handleAccept(offer)}
                  style={{ flex:'1 1 auto', minWidth:90, background:'#15803d', color:'#fff', border:'none', cursor:'pointer', padding:'10px 12px', borderRadius:100, fontSize:13, fontWeight:700, fontFamily:'Outfit,sans-serif' }}
                >
                  ✅ Aceptar
                </button>
                <button
                  onClick={()=>setCounterModal(offer)}
                  style={{ flex:'1 1 auto', minWidth:90, background:'#c4773a', color:'#fff', border:'none', cursor:'pointer', padding:'10px 12px', borderRadius:100, fontSize:13, fontWeight:700, fontFamily:'Outfit,sans-serif' }}
                >
                  💬 Contraoferta
                </button>
                <button
                  onClick={()=>handleReject(offer)}
                  style={{ flex:'1 1 auto', minWidth:90, background:'#fff', color:'#b91c1c', border:'1px solid #fecaca', cursor:'pointer', padding:'10px 12px', borderRadius:100, fontSize:13, fontWeight:700, fontFamily:'Outfit,sans-serif' }}
                >
                  ❌ Rechazar
                </button>
              </div>
            </div>
          ))}
        </div>
      )}

      {pendingCounters.length > 0 && (
        <div style={{ background:'#ede9fe', border:'1px solid #c4b5fd', borderRadius:12, padding:'14px 16px' }}>
          <div style={{ fontSize:13, fontWeight:800, color:'#5b21b6', letterSpacing:1, marginBottom:10, textTransform:'uppercase' }}>
            🟣 Contraofertas tuyas pendientes
          </div>
          {pendingCounters.map(c => (
            <div key={c.id} style={{ background:'#fff', borderRadius:10, padding:'10px 14px', marginBottom:8, fontSize:13, color:t.text }}>
              Pediste <strong>{c.amount}€</strong> a {c.buyerName} · {timeSince(c.time)} · esperando respuesta…
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

/* ── COUNTER OFFER MODAL ── Modal para que el vendedor envíe contraoferta */
function CounterOfferModal({ t, offer, opId, maxAmount, onClose, onSent }) {
  const [amount, setAmount] = React.useState(String(Math.round((Number(offer.amount) + Number(maxAmount)) / 2)));
  const [message, setMessage] = React.useState('');
  const [submitting, setSubmitting] = React.useState(false);

  const valid = amount && Number(amount) > Number(offer.amount) && Number(amount) <= Number(maxAmount);

  const handleSubmit = () => {
    if (!valid) return;
    setSubmitting(true);
    counterOffer(opId, offer.id, Number(amount), message.trim());
    onSent();
  };

  return (
    <div onClick={onClose} style={{ position:'fixed', inset:0, background:'rgba(0,0,0,0.6)', zIndex:1000, display:'flex', alignItems:'center', justifyContent:'center', padding:16 }}>
      <div onClick={e=>e.stopPropagation()} style={{ background:t.bg, borderRadius:20, width:'100%', maxWidth:440, padding:'24px 24px 20px' }}>
        <div style={{ display:'flex', justifyContent:'space-between', alignItems:'flex-start', marginBottom:16 }}>
          <h3 style={{ fontSize:20, fontWeight:900, color:t.text, margin:0 }}>💬 Contraoferta</h3>
          <button onClick={onClose} style={{ background:'none', border:'none', cursor:'pointer', fontSize:20, color:t.textLight, fontFamily:'Outfit,sans-serif' }}>✕</button>
        </div>

        <div style={{ background:t.bgAlt, borderRadius:10, padding:'10px 12px', marginBottom:16, fontSize:13, color:t.textMid, lineHeight:1.5 }}>
          <strong style={{ color:t.text }}>{offer.buyerName}</strong> ofreció <strong style={{ color:'#a16207' }}>{offer.amount}€</strong>.<br/>
          Tu precio pedido: <strong>{maxAmount}€</strong>
        </div>

        <label style={{ fontSize:14, fontWeight:700, color:t.text, display:'block', marginBottom:6 }}>Tu contraoferta (€)</label>
        <input
          type="number" inputMode="decimal" min={Number(offer.amount) + 1} max={maxAmount}
          value={amount}
          onChange={e=>setAmount(e.target.value)}
          style={{ width:'100%', padding:'14px 16px', borderRadius:12, border:`2px solid ${valid ? t.primary : t.border}`, background:t.card, fontSize:18, fontWeight:700, color:t.text, fontFamily:'Outfit,sans-serif', outline:'none', marginBottom:6, boxSizing:'border-box' }}
        />
        {amount && !valid && (
          <div style={{ fontSize:12, color:'#dc2626', marginBottom:8 }}>
            Debe ser entre {Number(offer.amount) + 1}€ y {maxAmount}€
          </div>
        )}

        <label style={{ fontSize:14, fontWeight:700, color:t.text, display:'block', marginTop:14, marginBottom:6 }}>Mensaje <span style={{ color:t.textLight, fontWeight:400 }}>(opcional)</span></label>
        <textarea
          value={message} onChange={e=>setMessage(e.target.value)}
          placeholder="Ej: Te lo dejo en este precio si lo recoges esta semana"
          style={{ width:'100%', padding:'12px 14px', borderRadius:10, border:`1px solid ${t.border}`, background:t.card, fontSize:14, color:t.text, fontFamily:'Outfit,sans-serif', outline:'none', marginBottom:18, boxSizing:'border-box', minHeight:60, resize:'vertical' }}
        />

        <button
          onClick={handleSubmit}
          disabled={!valid || submitting}
          style={{ width:'100%', padding:'14px', borderRadius:100, border:'none', background: valid ? t.primary : t.border, color:'#fff', fontSize:16, fontWeight:800, fontFamily:'Outfit,sans-serif', cursor: valid && !submitting ? 'pointer' : 'not-allowed' }}
        >
          {submitting ? 'Enviando...' : 'Enviar contraoferta'}
        </button>
      </div>
    </div>
  );
}

function SellerPortal({ t }) {
  const products = useProducts();
  const [phone, setPhone] = React.useState(() => localStorage.getItem('zeus_seller_phone') || '');
  const [submitted, setSubmitted] = React.useState(!!localStorage.getItem('zeus_seller_phone'));

  const myProducts = submitted
    ? products.filter(p => (p.phone||'').replace(/\s/g,'') === phone.replace(/\s/g,''))
    : [];

  const flow = ['nuevo','valorado','publicado','oferta','enviado','vendido'];

  const handleSearch = () => {
    if (phone.length < 9) return alert('Introduce un teléfono válido');
    setSubmitted(true);
  };

  return (
    <div className="zv-section" style={{ background:t.bg, minHeight:'100vh', padding:'48px 16px', boxSizing:'border-box', overflowX:'hidden', width:'100%' }}>
      <div style={{ maxWidth:700, margin:'0 auto', width:'100%', boxSizing:'border-box' }}>
        <h1 className="zv-big-title" style={{ fontSize:'clamp(26px,5vw,44px)', fontWeight:900, color:t.text, marginBottom:8 }}>Mi Zona de Vendedor</h1>
        <p style={{ fontSize:17, color:t.textMid, marginBottom:36 }}>Introduce tu teléfono para ver el estado de tus anuncios.</p>

        <div style={{ display:'flex', flexDirection:'column', gap:10, marginBottom:28 }}>
          <input
            type="tel"
            name="phone"
            autoComplete="tel"
            inputMode="tel"
            enterKeyHint="search"
            value={phone}
            onChange={e => { setPhone(e.target.value); setSubmitted(false); }}
            placeholder="Ej: 612 345 678"
            style={{ width:'100%', padding:'15px 20px', fontSize:17, borderRadius:100, border:`2px solid ${t.border}`, background:t.card, color:t.text, fontFamily:'Outfit,sans-serif', outline:'none', letterSpacing:2, boxSizing:'border-box' }}
          />
          <button onClick={handleSearch} style={{ width:'100%', background:t.primary, color:'#fff', border:'none', cursor:'pointer', padding:'15px 20px', borderRadius:100, fontSize:16, fontWeight:700, fontFamily:'Outfit,sans-serif' }}>Ver mis anuncios</button>
        </div>

        {submitted && myProducts.length === 0 && (
          <EmptyState t={t} icon="🔍" title="No encontramos anuncios" subtitle={`No hay anuncios registrados con el teléfono ${phone}. ¿Quizás usaste otro número?`} />
        )}

        {myProducts.map(p => {
          const statusIdx = flow.indexOf(p.status || 'nuevo');
          const earned = Math.round((p.price - p.price * commissionRate(p.price)) * 100) / 100;
          return (
            <div key={p.id} style={{ background:t.card, border:`2px solid ${t.border}`, borderRadius:20, padding:'20px 16px', marginBottom:20, boxSizing:'border-box' }}>
              <div style={{ display:'flex', gap:16, alignItems:'flex-start', marginBottom:20, flexWrap:'wrap' }}>
                <ProductImage product={p} h={80} style={{ width:80, height:80, borderRadius:12, flex:'0 0 80px' }} />
                <div style={{ flex:1 }}>
                  <h3 style={{ fontSize:20, fontWeight:800, color:t.text, marginBottom:4 }}>{p.title}</h3>
                  <div style={{ fontSize:24, fontWeight:900, color:t.primary }}>{p.price}€</div>
                  <div style={{ fontSize:14, color:t.textLight, marginTop:2 }}>Publicado {timeSince(p.publishedAt)}</div>
                </div>
                <StatusBadge status={p.status} />
              </div>

              {/* Progress bar */}
              <div style={{ marginBottom:16 }}>
                <div style={{ display:'flex', gap:4, marginBottom:8 }}>
                  {flow.map((s, i) => (
                    <div key={s} style={{ flex:1, height:6, borderRadius:100, background: i <= statusIdx ? t.primary : t.border, transition:'background 0.3s' }} />
                  ))}
                </div>
                <div style={{ display:'flex', justifyContent:'space-between', fontSize:11, color:t.textLight }}>
                  <span>Nuevo</span><span>Valorado</span><span>Publicado</span><span>Oferta</span><span>Enviado</span><span>Vendido</span>
                </div>
              </div>

              {/* Stats row */}
              <div style={{ display:'grid', gridTemplateColumns:'repeat(3,1fr)', gap:12, marginBottom:16 }}>
                <div style={{ background:t.bgAlt, borderRadius:12, padding:'12px 16px', textAlign:'center' }}>
                  <div style={{ fontSize:22, fontWeight:900, color:t.text }}>{p.views||0}</div>
                  <div style={{ fontSize:12, color:t.textLight }}>Visitas</div>
                </div>
                <div style={{ background:t.bgAlt, borderRadius:12, padding:'12px 16px', textAlign:'center' }}>
                  <div style={{ fontSize:22, fontWeight:900, color:t.primary }}>{earned}€</div>
                  <div style={{ fontSize:12, color:t.textLight }}>Recibirás</div>
                </div>
                <div style={{ background:t.bgAlt, borderRadius:12, padding:'12px 16px', textAlign:'center' }}>
                  <div style={{ fontSize:22, fontWeight:900, color:t.text }}>{Math.round(commissionRate(p.price)*100)}%</div>
                  <div style={{ fontSize:12, color:t.textLight }}>Comisión</div>
                </div>
              </div>

              {/* ── Bloque de ofertas activas ── */}
              <SellerOffersBlock t={t} product={p} />

              {/* WA contact */}
              <a href={WA_TEMPLATES.status(phone)} target="_blank" rel="noopener noreferrer" style={{ textDecoration:'none', display:'block' }}>
                <button style={{ width:'100%', background:'#25d366', color:'#fff', border:'none', cursor:'pointer', padding:'14px', borderRadius:100, fontSize:16, fontWeight:700, fontFamily:'Outfit,sans-serif', display:'flex', alignItems:'center', justifyContent:'center', gap:10 }}>
                  <svg width="20" height="20" viewBox="0 0 32 32" fill="white"><path d="M16 2C8.27 2 2 8.27 2 16c0 2.47.67 4.79 1.84 6.78L2 30l7.42-1.82A13.9 13.9 0 0016 30c7.73 0 14-6.27 14-14S23.73 2 16 2zm7.27 19.27c-.3.85-1.77 1.63-2.44 1.7-.62.07-1.22.3-4.13-.86-3.47-1.38-5.7-4.93-5.87-5.16-.17-.23-1.4-1.86-1.4-3.54s.89-2.51 1.2-2.86c.3-.34.66-.43.88-.43l.63.01c.2.01.48-.08.75.57.28.67.95 2.31.97 2.48.04.17.07.37-.04.57-.1.2-.15.32-.3.5-.15.17-.32.39-.45.52-.15.15-.3.31-.13.6.17.3.77 1.27 1.65 2.06 1.13 1.01 2.09 1.32 2.39 1.47.3.15.48.13.65-.08.18-.2.75-.88.95-1.18.2-.3.4-.25.67-.15.27.1 1.72.81 2.01.96.3.15.5.22.57.34.08.12.08.72-.22 1.47z"/></svg>
                  Preguntar por WhatsApp
                </button>
              </a>
            </div>
          );
        })}
      </div>
    </div>
  );
}

/* ── INSTALL APP (PWA) ── */
function InstallApp({ t }) {
  // Estados de instalación
  const [installPrompt, setInstallPrompt] = React.useState(window.__zeusInstallPrompt || null);
  const [installed, setInstalled] = React.useState(
    window.matchMedia('(display-mode: standalone)').matches ||
    window.navigator.standalone === true
  );
  const [installing, setInstalling] = React.useState(false);
  const [shareMsg, setShareMsg] = React.useState('');

  // Detectar plataforma
  const ua = navigator.userAgent || '';
  const isIOS = /iPad|iPhone|iPod/.test(ua) && !window.MSStream;
  const isAndroid = /Android/.test(ua);
  const isSafari = /^((?!chrome|android).)*safari/i.test(ua);

  // Escuchar eventos globales del install prompt
  React.useEffect(() => {
    const onAvailable = (e) => setInstallPrompt(e.detail || window.__zeusInstallPrompt);
    const onInstalled = () => { setInstalled(true); setInstallPrompt(null); };
    window.addEventListener('zeus:install-available', onAvailable);
    window.addEventListener('appinstalled', onInstalled);
    return () => {
      window.removeEventListener('zeus:install-available', onAvailable);
      window.removeEventListener('appinstalled', onInstalled);
    };
  }, []);

  const handleInstall = async () => {
    if (!installPrompt) return;
    setInstalling(true);
    try {
      await installPrompt.prompt();
      const choice = await installPrompt.userChoice;
      if (choice.outcome === 'accepted') {
        setInstalled(true);
      }
      window.__zeusInstallPrompt = null;
      setInstallPrompt(null);
    } catch (err) {
      console.warn('Install prompt error:', err);
    } finally {
      setInstalling(false);
    }
  };

  const siteUrl = window.location.origin + window.location.pathname.replace(/index\.html$/, '');

  const handleShare = async () => {
    const result = await shareZeusVentas('app');
    if (result === 'copied') {
      setShareMsg('Enlace copiado — pégalo en WhatsApp');
      setTimeout(() => setShareMsg(''), 3500);
    }
  };

  /* ── Render ── */
  return (
    <div className="zv-section" style={{ background:t.bg, minHeight:'100vh', padding:'48px 16px', boxSizing:'border-box', overflowX:'hidden' }}>
      <div style={{ maxWidth:720, margin:'0 auto' }}>

        {/* Hero */}
        <div style={{ textAlign:'center', marginBottom:40 }}>
          <div style={{ display:'inline-flex', alignItems:'center', justifyContent:'center', width:88, height:88, borderRadius:22, background:t.primary, marginBottom:20, boxShadow:'0 10px 30px rgba(61,87,64,0.25)' }}>
            <div style={{ width:62, height:62, borderRadius:14, background:t.accent, display:'flex', alignItems:'center', justifyContent:'center' }}>
              <span style={{ color:'#fff', fontWeight:900, fontSize:36, fontFamily:'Outfit,sans-serif' }}>Z</span>
            </div>
          </div>
          <h1 className="zv-big-title" style={{ fontSize:'clamp(32px,6vw,46px)', fontWeight:900, color:t.text, marginBottom:10, lineHeight:1.1 }}>
            Zeus Ventas en tu móvil
          </h1>
          <p style={{ fontSize:18, color:t.textMid, lineHeight:1.5, maxWidth:500, margin:'0 auto' }}>
            Instala la app en tu teléfono. Un icono en la pantalla de inicio, se abre al instante y funciona sin necesidad del navegador.
          </p>
        </div>

        {/* Estado: ya instalada */}
        {installed && (
          <div style={{ background:'#f0fdf4', border:'2px solid #16a34a', borderRadius:20, padding:'28px 24px', textAlign:'center', marginBottom:32 }}>
            <div style={{ fontSize:44, marginBottom:8 }}>✓</div>
            <h3 style={{ fontSize:20, fontWeight:800, color:'#15803d', marginBottom:6 }}>Ya tienes la app instalada</h3>
            <p style={{ fontSize:15, color:'#15803d', marginBottom:20 }}>Estás usando Zeus Ventas como aplicación. Puedes cerrar esta página.</p>
            <button
              onClick={handleShare}
              style={{
                background:'#fff', color:'#15803d', border:'2px solid #16a34a',
                cursor:'pointer', padding:'12px 24px', borderRadius:100,
                fontSize:15, fontWeight:700, fontFamily:'Outfit,sans-serif',
                display:'inline-flex', alignItems:'center', gap:8
              }}
            >
              <span style={{ fontSize:17 }}>📤</span> Invita a un amigo
            </button>
            {shareMsg && <div style={{ fontSize:13, color:'#15803d', marginTop:10 }}>{shareMsg}</div>}
          </div>
        )}

        {/* Estado: instalación automática disponible (Android/Chrome/Edge) */}
        {!installed && installPrompt && (
          <div style={{ background:t.card, border:`2px solid ${t.border}`, borderRadius:20, padding:'28px 24px', marginBottom:32, textAlign:'center' }}>
            <div style={{ fontSize:15, color:t.textMid, marginBottom:18 }}>
              Tu navegador permite instalar la app con un solo toque:
            </div>
            <button
              onClick={handleInstall}
              disabled={installing}
              style={{
                background:t.primary, color:'#fff', border:'none',
                cursor:installing?'wait':'pointer',
                padding:'18px 36px', borderRadius:100,
                fontSize:19, fontWeight:800, fontFamily:'Outfit,sans-serif',
                display:'inline-flex', alignItems:'center', gap:12,
                boxShadow:'0 8px 24px rgba(61,87,64,0.35)',
                opacity: installing ? 0.7 : 1
              }}
            >
              <span style={{ fontSize:22 }}>⬇</span>
              {installing ? 'Instalando…' : 'Instalar aplicación'}
            </button>
            <div style={{ fontSize:13, color:t.textLight, marginTop:14 }}>
              Gratis · Sin anuncios · 0 MB extra de datos
            </div>
          </div>
        )}

        {/* Instrucciones iOS (Safari no soporta beforeinstallprompt) */}
        {!installed && isIOS && (
          <div style={{ background:t.card, border:`2px solid ${t.border}`, borderRadius:20, padding:'28px 24px', marginBottom:24 }}>
            <div style={{ display:'flex', alignItems:'center', gap:12, marginBottom:18 }}>
              <span style={{ fontSize:28 }}>🍎</span>
              <h3 style={{ fontSize:20, fontWeight:800, color:t.text }}>Instalar en iPhone / iPad</h3>
            </div>
            {[
              { n:'1', text:'Toca el botón compartir ', icon:'⬆️', extra:'(cuadrado con flecha hacia arriba) en la barra inferior de Safari.' },
              { n:'2', text:'Desliza y pulsa ', icon:'➕', extra:'"Añadir a pantalla de inicio".' },
              { n:'3', text:'Pulsa ', icon:'✓', extra:'"Añadir" arriba a la derecha. El icono aparecerá en tu pantalla como una app.' }
            ].map(s => (
              <div key={s.n} style={{ display:'flex', gap:14, padding:'14px 0', borderBottom:`1px solid ${t.border}` }}>
                <div style={{ flex:'0 0 32px', width:32, height:32, borderRadius:'50%', background:t.primary, color:'#fff', display:'flex', alignItems:'center', justifyContent:'center', fontWeight:800, fontSize:15 }}>{s.n}</div>
                <div style={{ flex:1, fontSize:16, color:t.text, lineHeight:1.5 }}>
                  {s.text}<span style={{ fontSize:20 }}>{s.icon}</span>{' '}{s.extra}
                </div>
              </div>
            ))}
            <div style={{ marginTop:16, padding:'12px 16px', background:t.bgAlt, borderRadius:12, fontSize:14, color:t.textMid }}>
              💡 Si no ves el botón compartir, asegúrate de estar usando <strong>Safari</strong> (no Chrome en iPhone).
            </div>
          </div>
        )}

        {/* Instrucciones Android sin prompt automático */}
        {!installed && !installPrompt && isAndroid && (
          <div style={{ background:t.card, border:`2px solid ${t.border}`, borderRadius:20, padding:'28px 24px', marginBottom:24 }}>
            <div style={{ display:'flex', alignItems:'center', gap:12, marginBottom:18 }}>
              <span style={{ fontSize:28 }}>🤖</span>
              <h3 style={{ fontSize:20, fontWeight:800, color:t.text }}>Instalar en Android</h3>
            </div>
            {[
              { n:'1', text:'Pulsa el menú de Chrome (tres puntos ⋮ arriba a la derecha).' },
              { n:'2', text:'Selecciona "Instalar aplicación" o "Añadir a pantalla de inicio".' },
              { n:'3', text:'Confirma pulsando "Instalar". El icono aparecerá en tu pantalla.' }
            ].map(s => (
              <div key={s.n} style={{ display:'flex', gap:14, padding:'14px 0', borderBottom:`1px solid ${t.border}` }}>
                <div style={{ flex:'0 0 32px', width:32, height:32, borderRadius:'50%', background:t.primary, color:'#fff', display:'flex', alignItems:'center', justifyContent:'center', fontWeight:800, fontSize:15 }}>{s.n}</div>
                <div style={{ flex:1, fontSize:16, color:t.text, lineHeight:1.5 }}>{s.text}</div>
              </div>
            ))}
          </div>
        )}

        {/* Instrucciones para escritorio (Chrome/Edge) sin prompt */}
        {!installed && !installPrompt && !isAndroid && !isIOS && (
          <div style={{ background:t.card, border:`2px solid ${t.border}`, borderRadius:20, padding:'28px 24px', marginBottom:24 }}>
            <div style={{ display:'flex', alignItems:'center', gap:12, marginBottom:18 }}>
              <span style={{ fontSize:28 }}>💻</span>
              <h3 style={{ fontSize:20, fontWeight:800, color:t.text }}>Instalar en ordenador</h3>
            </div>
            <p style={{ fontSize:16, color:t.textMid, marginBottom:16, lineHeight:1.5 }}>
              En Chrome o Edge, busca el icono de instalación <strong>⊕</strong> en la barra de direcciones (a la derecha de la URL) y haz clic en él.
            </p>
            <p style={{ fontSize:15, color:t.textLight, lineHeight:1.5 }}>
              Si no lo ves, abre esta página desde el móvil — la experiencia está pensada para teléfono y tablet.
            </p>
          </div>
        )}

        {/* QR para instalar en el móvil desde ordenador */}
        {!isIOS && !isAndroid && !installed && (
          <div style={{ background:t.card, border:`2px solid ${t.border}`, borderRadius:20, padding:'28px 24px', marginBottom:24, textAlign:'center' }}>
            <h3 style={{ fontSize:18, fontWeight:800, color:t.text, marginBottom:6 }}>¿Quieres instalarla en el móvil?</h3>
            <p style={{ fontSize:14, color:t.textMid, marginBottom:16 }}>
              Escanea este código QR con la cámara de tu teléfono:
            </p>
            <img
              src={qrUrl(siteUrl + '#download', 220)}
              alt="Código QR para abrir Zeus Ventas en el móvil"
              width={220}
              height={220}
              style={{ borderRadius:16, border:`2px solid ${t.border}`, background:'#fff', padding:8 }}
            />
            <div style={{ fontSize:12, color:t.textLight, marginTop:12, wordBreak:'break-all' }}>
              o abre en el móvil: {siteUrl}
            </div>
          </div>
        )}

        {/* Beneficios */}
        <div style={{ marginTop:40 }}>
          <h2 style={{ fontSize:22, fontWeight:800, color:t.text, marginBottom:20, textAlign:'center' }}>
            ¿Por qué instalarla?
          </h2>
          <div className="zv-grid-2" style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:16 }}>
            {[
              { icon:'⚡', title:'Se abre al instante', body:'Sin tener que teclear la dirección cada vez.' },
              { icon:'📱', title:'Como una app normal', body:'Un icono en la pantalla de inicio y pantalla completa.' },
              { icon:'🔔', title:'Avisos de ofertas', body:'Cuando alguien se interesa por tus anuncios.' },
              { icon:'📶', title:'Funciona sin internet', body:'Puedes consultar tus anuncios aunque no tengas cobertura.' }
            ].map(b => (
              <div key={b.title} style={{ background:t.card, border:`2px solid ${t.border}`, borderRadius:16, padding:'20px 18px' }}>
                <div style={{ fontSize:28, marginBottom:8 }}>{b.icon}</div>
                <h4 style={{ fontSize:16, fontWeight:800, color:t.text, marginBottom:4 }}>{b.title}</h4>
                <p style={{ fontSize:14, color:t.textMid, lineHeight:1.4 }}>{b.body}</p>
              </div>
            ))}
          </div>
        </div>

        {/* Compartir con un amigo (solo si no está ya instalada y no hay flujo visible) */}
        {!installed && (
          <div style={{ marginTop:36, padding:'24px 22px', background:t.card, border:`2px solid ${t.border}`, borderRadius:16, textAlign:'center' }}>
            <div style={{ fontSize:28, marginBottom:8 }}>📤</div>
            <div style={{ fontSize:16, fontWeight:700, color:t.text, marginBottom:6 }}>¿Conoces a alguien a quien le iría bien?</div>
            <div style={{ fontSize:14, color:t.textMid, marginBottom:16 }}>Envíaselo en un segundo por WhatsApp.</div>
            <button
              onClick={handleShare}
              style={{
                background:t.primary, color:'#fff', border:'none',
                cursor:'pointer', padding:'14px 28px', borderRadius:100,
                fontSize:16, fontWeight:700, fontFamily:'Outfit,sans-serif',
                display:'inline-flex', alignItems:'center', gap:10
              }}
            >
              <span style={{ fontSize:18 }}>📤</span> Compartir con un amigo
            </button>
            {shareMsg && <div style={{ fontSize:13, color:t.textMid, marginTop:10 }}>{shareMsg}</div>}
          </div>
        )}

        {/* Ayuda */}
        <div style={{ marginTop:20, padding:'20px 22px', background:t.bgAlt, borderRadius:16, textAlign:'center' }}>
          <div style={{ fontSize:14, color:t.textMid, marginBottom:8 }}>¿Necesitas ayuda para instalarla?</div>
          <a href={waUrl('Hola, necesito ayuda para instalar la app de Zeus Ventas en mi móvil.')} target="_blank" rel="noopener noreferrer" style={{ color:t.primary, fontWeight:700, textDecoration:'none', fontSize:15 }}>
            Te ayudamos por WhatsApp →
          </a>
        </div>

      </div>
    </div>
  );
}

/* ── ABOUT / Quiénes somos ── */
function About({ t, setPage }) {
  return (
    <div className="zv-section" style={{ background:t.bg, minHeight:'100vh', padding:'48px 28px' }}>
      <div style={{ maxWidth:720, margin:'0 auto' }}>

        {/* Hero misión */}
        <div style={{ textAlign:'center', marginBottom:40 }}>
          <img
            src="https://images.unsplash.com/photo-1758686253708-f0e21317d2aa?w=1200&q=80"
            alt="Pareja mayor sonriendo"
            loading="lazy"
            style={{ width:260, height:260, objectFit:'cover', borderRadius:'50%', marginBottom:22, boxShadow:'0 14px 40px rgba(61,87,64,0.25)' }}
          />
          <h1 className="zv-big-title" style={{ fontSize:'clamp(30px,6vw,44px)', fontWeight:900, color:t.text, marginBottom:14, lineHeight:1.15 }}>
            Ayudamos a nuestros mayores a dar una segunda vida a sus objetos
          </h1>
          <p style={{ fontSize:18, color:t.textMid, lineHeight:1.6, maxWidth:560, margin:'0 auto' }}>
            Muchas casas están llenas de muebles, herramientas y pequeños tesoros que ya no se usan. En Zeus Ventas los convertimos en ingresos extras para quien más lo necesita.
          </p>
        </div>

        {/* Bloque: cómo lo hacemos */}
        <div style={{ background:t.card, border:`2px solid ${t.border}`, borderRadius:20, padding:'32px 26px', marginBottom:28 }}>
          <h2 style={{ fontSize:22, fontWeight:900, color:t.text, marginBottom:16 }}>Nuestro compromiso</h2>
          <p style={{ fontSize:16, color:t.textMid, lineHeight:1.7, marginBottom:14 }}>
            Vender por internet asusta a mucha gente mayor. Las apps complicadas, las fotos que no quedan bien, los chats con desconocidos, el miedo a equivocarse con los envíos… Entendemos.
          </p>
          <p style={{ fontSize:16, color:t.textMid, lineHeight:1.7, marginBottom:14 }}>
            Por eso Zeus Ventas funciona distinto: <strong style={{ color:t.text }}>tú solo haces una foto</strong> y nos la envías por WhatsApp. Nosotros nos encargamos de todo lo demás — valorar el objeto a precio de mercado, escribir la descripción, publicarlo en varias plataformas, atender a los interesados, coordinar la recogida con la empresa de transporte, asegurar que llegue bien al comprador y depositar el dinero en tu cuenta.
          </p>
          <p style={{ fontSize:16, color:t.textMid, lineHeight:1.7 }}>
            Tú solo decides el precio mínimo que aceptas. Si se vende, ganas. Si no se vende, no pagas nada.
          </p>
        </div>

        {/* Bloque: pide ayuda a un nieto o amigo */}
        <div style={{ background:t.primary, borderRadius:20, padding:'32px 26px', marginBottom:28, color:'#fff' }}>
          <div style={{ display:'flex', alignItems:'center', gap:18, marginBottom:14, flexWrap:'wrap' }}>
            <img
              src="https://images.unsplash.com/photo-1641736257757-2c4cce5f9ed5?w=1200&q=80"
              alt="Señora mayor mirando el móvil en casa"
              loading="lazy"
              style={{ width:110, height:110, objectFit:'cover', borderRadius:'50%', flex:'0 0 auto', boxShadow:'0 6px 18px rgba(0,0,0,0.25)', border:'3px solid rgba(255,255,255,0.5)' }}
            />
            <div style={{ fontSize:36 }}>🤝</div>
          </div>
          <h2 style={{ fontSize:22, fontWeight:900, marginBottom:14 }}>
            ¿El móvil te lía un poco? Pide ayuda, no pasa nada.
          </h2>
          <p style={{ fontSize:16, lineHeight:1.7, marginBottom:14, color:'rgba(255,255,255,0.9)' }}>
            No hace falta que hagas esto solo. Un nieto, un sobrino, un vecino o un amigo pueden ayudarte a sacar las fotos y enviárnoslas. Cinco minutos de su tiempo valen mucho.
          </p>
          <p style={{ fontSize:16, lineHeight:1.7, color:'rgba(255,255,255,0.9)' }}>
            Y si no tienes a nadie cerca, llámanos. Vamos nosotros.
          </p>
          <div style={{ display:'flex', gap:10, marginTop:22, flexWrap:'wrap' }}>
            <a href={waUrl('Hola, necesito ayuda para publicar un objeto en Zeus Ventas.')} target="_blank" rel="noopener noreferrer" style={{ textDecoration:'none', flex:'1 1 auto', minWidth:180 }}>
              <button style={{ width:'100%', background:'#25d366', color:'#fff', border:'none', cursor:'pointer', padding:'14px 22px', borderRadius:100, fontSize:16, fontWeight:800, fontFamily:'Outfit,sans-serif' }}>
                📱 Pedir ayuda por WhatsApp
              </button>
            </a>
            <a href={'tel:+34' + WA_NUMBER.slice(2)} style={{ textDecoration:'none', flex:'1 1 auto', minWidth:180 }}>
              <button style={{ width:'100%', background:'rgba(255,255,255,0.15)', color:'#fff', border:'2px solid rgba(255,255,255,0.3)', cursor:'pointer', padding:'14px 22px', borderRadius:100, fontSize:16, fontWeight:700, fontFamily:'Outfit,sans-serif' }}>
                ☎ Llamar 699 601 627
              </button>
            </a>
          </div>
        </div>

        {/* Bloque: para quien nos recomienda a un familiar mayor */}
        <div style={{ background:t.card, border:`2px dashed ${t.primary}`, borderRadius:20, padding:'28px 24px', marginBottom:28 }}>
          <div style={{ fontSize:32, marginBottom:8 }}>💚</div>
          <h3 style={{ fontSize:20, fontWeight:900, color:t.text, marginBottom:10 }}>
            ¿Tienes un padre, madre o abuelo que podría beneficiarse?
          </h3>
          <p style={{ fontSize:15, color:t.textMid, lineHeight:1.6, marginBottom:18 }}>
            Muchos mayores tienen objetos de valor olvidados en casa y no saben cómo sacarles partido. Si les echas una mano con las fotos una sola vez, pueden tener un ingreso extra cada mes sin salir de casa.
          </p>
          <button
            onClick={async () => {
              const res = await shareZeusVentas('site');
              if (res === 'copied') alert('Enlace copiado. Pégalo en WhatsApp.');
            }}
            style={{ background:t.primary, color:'#fff', border:'none', cursor:'pointer', padding:'12px 24px', borderRadius:100, fontSize:15, fontWeight:700, fontFamily:'Outfit,sans-serif', display:'inline-flex', alignItems:'center', gap:10 }}
          >
            <span style={{ fontSize:17 }}>📤</span> Enviar a un familiar
          </button>
        </div>

        {/* Valores */}
        <div style={{ marginBottom:28 }}>
          <h2 style={{ fontSize:22, fontWeight:900, color:t.text, marginBottom:18, textAlign:'center' }}>Cómo trabajamos</h2>
          <div style={{ display:'flex', flexDirection:'column', gap:14 }}>
            {[
              { icon:'🔒', title:'Sin letra pequeña', body:'Si el objeto se vende, tú cobras. Si no se vende, no pagas nada. La comisión está siempre publicada.' },
              { icon:'🏡', title:'Recogemos en casa', body:'No tienes que ir a ningún sitio. Vamos nosotros al domicilio con cita previa.' },
              { icon:'📞', title:'Trato humano', body:'Siempre que llames, al otro lado hay una persona. Nada de bots ni menús interminables.' },
              { icon:'🎁', title:'Un proyecto social', body:'Nuestro objetivo no es hacerse rico. Es que nuestros mayores tengan un euro más cada mes con lo que ya tienen en casa.' }
            ].map(v => (
              <div key={v.title} style={{ display:'flex', gap:16, background:t.card, border:`1px solid ${t.border}`, borderRadius:16, padding:'18px 20px' }}>
                <div style={{ fontSize:28, flex:'0 0 36px' }}>{v.icon}</div>
                <div>
                  <h4 style={{ fontSize:17, fontWeight:800, color:t.text, marginBottom:4 }}>{v.title}</h4>
                  <p style={{ fontSize:14, color:t.textMid, lineHeight:1.55 }}>{v.body}</p>
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* CTA final */}
        <div style={{ background:t.accent, borderRadius:20, padding:'28px 24px', textAlign:'center', color:'#fff', marginBottom:28 }}>
          <h3 style={{ fontSize:22, fontWeight:900, marginBottom:8 }}>¿Tienes algo para vender?</h3>
          <p style={{ fontSize:15, marginBottom:20, color:'rgba(255,255,255,0.9)' }}>Empieza con una foto. Nos ocupamos del resto.</p>
          <button onClick={()=>setPage('publish')} style={{ background:'#fff', color:t.accent, border:'none', cursor:'pointer', padding:'14px 28px', borderRadius:100, fontSize:16, fontWeight:800, fontFamily:'Outfit,sans-serif' }}>
            Empezar ahora
          </button>
        </div>

        {/* Datos legales / razón social */}
        <div style={{ background:t.bgAlt, borderRadius:14, padding:'20px 22px', fontSize:13, color:t.textMid, lineHeight:1.7 }}>
          <div style={{ fontWeight:700, color:t.text, marginBottom:8, fontSize:14 }}>Información legal</div>
          <div>Titular: <em>[Pendiente de completar — razón social]</em></div>
          <div>NIF / CIF: <em>[Pendiente]</em></div>
          <div>Domicilio: España</div>
          <div>Contacto: 699 601 627 · zeusventas.es</div>
          <div style={{ marginTop:10, paddingTop:10, borderTop:`1px solid ${t.border}` }}>
            Para más información, consulta los <span onClick={()=>setPage('terms')} style={{ color:t.primary, fontWeight:700, cursor:'pointer' }}>términos y condiciones</span>.
          </div>
        </div>

      </div>
    </div>
  );
}

/* ── FEEDBACK / Buzón de sugerencias ── */
function Feedback({ t, setPage }) {
  const [answers, setAnswers] = React.useState({
    claridad: '', usarias: '', tipo_objetos: '', freno: '', origen: '', comentario: ''
  });
  const [status, setStatus] = React.useState('form'); // 'form' | 'sending' | 'done' | 'error'
  const [copied, setCopied] = React.useState(false);

  const PROMO_CODE = 'GRACIAS-ZEUS-2026';

  const preguntas = [
    {
      key: 'claridad',
      titulo: '1. ¿Entiendes bien para qué sirve Zeus Ventas?',
      tipo: 'escala',
      opciones: [
        { v:'1', l:'Nada claro', icon:'😕' },
        { v:'2', l:'Poco claro', icon:'😐' },
        { v:'3', l:'Más o menos', icon:'🙂' },
        { v:'4', l:'Bastante', icon:'😃' },
        { v:'5', l:'Muy claro', icon:'🤩' },
      ]
    },
    {
      key: 'usarias',
      titulo: '2. ¿Usarías Zeus Ventas para vender algo tuyo?',
      tipo: 'simple',
      opciones: [
        { v:'si', l:'Sí, seguro', icon:'✅' },
        { v:'quiza', l:'Quizás', icon:'🤔' },
        { v:'no', l:'No, de momento', icon:'❌' },
      ]
    },
    {
      key: 'tipo_objetos',
      titulo: '3. ¿Qué tipo de objetos tienes para vender?',
      tipo: 'simple',
      opciones: [
        { v:'muebles', l:'Muebles', icon:'🪑' },
        { v:'hogar', l:'Cosas de casa', icon:'🏠' },
        { v:'ropa', l:'Ropa y textiles', icon:'👕' },
        { v:'electro', l:'Electrodomésticos', icon:'📺' },
        { v:'coleccion', l:'Coleccionismo', icon:'🎨' },
        { v:'otros', l:'Otros', icon:'📦' },
      ]
    },
    {
      key: 'freno',
      titulo: '4. ¿Qué es lo que más te frenaría para usarlo?',
      tipo: 'simple',
      opciones: [
        { v:'comision', l:'La comisión', icon:'💰' },
        { v:'confianza', l:'Desconfianza', icon:'🤨' },
        { v:'entender', l:'No entiendo cómo funciona', icon:'❓' },
        { v:'nada', l:'Nada, me parece bien', icon:'👍' },
      ]
    },
    {
      key: 'origen',
      titulo: '5. ¿Cómo has conocido Zeus Ventas?',
      tipo: 'simple',
      opciones: [
        { v:'amigo', l:'Un amigo/familiar', icon:'👨‍👩‍👧' },
        { v:'redes', l:'Redes sociales', icon:'📱' },
        { v:'google', l:'Buscando en internet', icon:'🔍' },
        { v:'cartel', l:'Cartel o folleto', icon:'📋' },
        { v:'otro', l:'Otro', icon:'💬' },
      ]
    },
  ];

  const allAnswered = preguntas.every(p => answers[p.key]);
  const progress = preguntas.filter(p => answers[p.key]).length;

  const setA = (k, v) => setAnswers(a => ({ ...a, [k]: v }));

  const submit = async () => {
    if (!allAnswered) return;
    setStatus('sending');
    try {
      const body = new URLSearchParams({
        'form-name': 'feedback',
        'bot-field': '',
        ...answers,
      }).toString();
      const res = await fetch('/', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body,
      });
      if (!res.ok) throw new Error('Error al enviar');
      setStatus('done');
      window.scrollTo({ top: 0, behavior: 'smooth' });
    } catch (e) {
      console.error(e);
      setStatus('error');
    }
  };

  const copyCode = async () => {
    try {
      await navigator.clipboard.writeText(PROMO_CODE);
      setCopied(true);
      setTimeout(() => setCopied(false), 2500);
    } catch {}
  };

  // ── PANTALLA DE ÉXITO ──
  if (status === 'done') {
    return (
      <div className="zv-section" style={{ background:t.bg, padding:'60px 20px 80px', minHeight:'80vh' }}>
        <div style={{ maxWidth:620, margin:'0 auto', textAlign:'center' }}>
          <div style={{ fontSize:72, marginBottom:10 }}>🎉</div>
          <h1 style={{ fontSize:'clamp(32px,6vw,48px)', fontWeight:900, color:t.text, lineHeight:1.1, marginBottom:16 }}>
            ¡Muchísimas gracias!
          </h1>
          <p style={{ fontSize:18, color:t.textMid, lineHeight:1.6, marginBottom:36 }}>
            Tu opinión nos ayuda a mejorar Zeus Ventas para que sea más útil para todos.
          </p>

          {/* Tarjeta de la promoción */}
          <div style={{ background:t.primary, color:'#fff', borderRadius:24, padding:'36px 28px', marginBottom:24, boxShadow:'0 10px 30px rgba(61,87,64,0.3)' }}>
            <div style={{ fontSize:56, marginBottom:8 }}>🎯</div>
            <h2 style={{ fontSize:26, fontWeight:900, marginBottom:10 }}>
              Tu regalo: Valoración Premium GRATIS
            </h2>
            <p style={{ fontSize:16, lineHeight:1.6, opacity:0.92, marginBottom:22 }}>
              Cuando nos envíes tu primera foto por WhatsApp, te haremos un <strong>informe detallado</strong> con precio recomendado, análisis de mercado y estrategia de venta. Sin coste.
            </p>

            <div style={{ background:'rgba(255,255,255,0.15)', borderRadius:14, padding:'18px 16px', marginBottom:20 }}>
              <div style={{ fontSize:12, letterSpacing:1, opacity:0.8, marginBottom:6, textTransform:'uppercase' }}>Tu código</div>
              <div style={{ fontSize:'clamp(22px,5vw,30px)', fontWeight:900, letterSpacing:1, fontFamily:'monospace', marginBottom:12 }}>
                {PROMO_CODE}
              </div>
              <button onClick={copyCode} style={{ background:'#fff', color:t.primary, border:'none', cursor:'pointer', padding:'10px 20px', borderRadius:100, fontSize:14, fontWeight:700, fontFamily:'Outfit,sans-serif' }}>
                {copied ? '✓ Copiado' : '📋 Copiar código'}
              </button>
            </div>

            <p style={{ fontSize:14, opacity:0.85, marginBottom:20, lineHeight:1.5 }}>
              Pega este código en tu primer mensaje de WhatsApp junto con la foto del objeto.
            </p>

            <a
              href={`https://wa.me/34699601627?text=${encodeURIComponent(`Hola! Tengo el código ${PROMO_CODE} para la Valoración Premium gratis. Os mando la foto de mi objeto 👇`)}`}
              style={{ display:'inline-block', background:'#25d366', color:'#fff', textDecoration:'none', padding:'16px 32px', borderRadius:100, fontSize:17, fontWeight:700, fontFamily:'Outfit,sans-serif', boxShadow:'0 6px 18px rgba(37,211,102,0.4)' }}
            >
              💬 Usar ahora por WhatsApp
            </a>
          </div>

          <button onClick={() => setPage('home')} style={{ background:'none', color:t.primary, border:`2px solid ${t.primary}`, cursor:'pointer', padding:'12px 24px', borderRadius:100, fontSize:15, fontWeight:700, fontFamily:'Outfit,sans-serif' }}>
            ← Volver al inicio
          </button>
        </div>
      </div>
    );
  }

  // ── PANTALLA DE FORMULARIO ──
  return (
    <div className="zv-section" style={{ background:t.bg, padding:'40px 20px 80px' }}>
      <div style={{ maxWidth:720, margin:'0 auto' }}>

        {/* Cabecera */}
        <div style={{ textAlign:'center', marginBottom:28 }}>
          <div style={{ fontSize:56, marginBottom:8 }}>💬</div>
          <h1 style={{ fontSize:'clamp(30px,5.5vw,44px)', fontWeight:900, color:t.text, lineHeight:1.1, marginBottom:12 }}>
            Tu opinión vale oro
          </h1>
          <p style={{ fontSize:17, color:t.textMid, lineHeight:1.5, maxWidth:520, margin:'0 auto' }}>
            Ayúdanos a mejorar con 5 preguntas rápidas (2 minutos) y llévate una <strong style={{ color:t.primary }}>Valoración Premium gratis</strong>.
          </p>
        </div>

        {/* Barra de progreso */}
        <div style={{ background:t.border, borderRadius:100, height:8, marginBottom:32, overflow:'hidden' }}>
          <div style={{ background:t.primary, height:'100%', width:`${(progress/5)*100}%`, transition:'width 0.3s ease' }} />
        </div>

        {/* Preguntas */}
        {preguntas.map((p) => (
          <div key={p.key} style={{ background:t.card, borderRadius:20, padding:'24px 20px', marginBottom:18, border:`2px solid ${answers[p.key] ? t.primary : t.border}`, transition:'border 0.2s ease' }}>
            <h3 style={{ fontSize:'clamp(17px,3vw,19px)', fontWeight:700, color:t.text, lineHeight:1.3, marginBottom:16 }}>
              {p.titulo}
            </h3>
            <div style={{ display:'grid', gridTemplateColumns: p.tipo === 'escala' ? 'repeat(auto-fit, minmax(90px, 1fr))' : 'repeat(auto-fit, minmax(140px, 1fr))', gap:10 }}>
              {p.opciones.map(o => {
                const selected = answers[p.key] === o.v;
                return (
                  <button
                    key={o.v}
                    onClick={() => setA(p.key, o.v)}
                    style={{
                      background: selected ? t.primary : t.bg,
                      color: selected ? '#fff' : t.text,
                      border: `2px solid ${selected ? t.primary : t.border}`,
                      cursor:'pointer',
                      padding:'14px 10px',
                      borderRadius:14,
                      fontSize:14,
                      fontWeight:600,
                      fontFamily:'Outfit,sans-serif',
                      minHeight:64,
                      display:'flex',
                      flexDirection:'column',
                      alignItems:'center',
                      justifyContent:'center',
                      gap:4,
                      transition:'all 0.15s ease'
                    }}
                  >
                    <span style={{ fontSize:24 }}>{o.icon}</span>
                    <span style={{ fontSize:13, lineHeight:1.2 }}>{o.l}</span>
                  </button>
                );
              })}
            </div>
          </div>
        ))}

        {/* Comentario opcional */}
        <div style={{ background:t.card, borderRadius:20, padding:'24px 20px', marginBottom:24, border:`2px solid ${t.border}` }}>
          <h3 style={{ fontSize:17, fontWeight:700, color:t.text, marginBottom:12 }}>
            ¿Algo más que quieras contarnos? <span style={{ color:t.textLight, fontWeight:400 }}>(opcional)</span>
          </h3>
          <textarea
            value={answers.comentario}
            onChange={e => setA('comentario', e.target.value)}
            placeholder="Cuéntanos lo que quieras... ideas, dudas, cosas que mejorarías..."
            rows={4}
            style={{
              width:'100%',
              padding:14,
              borderRadius:12,
              border:`2px solid ${t.border}`,
              background:t.bg,
              color:t.text,
              fontSize:15,
              fontFamily:'Outfit,sans-serif',
              resize:'vertical',
              boxSizing:'border-box',
            }}
          />
        </div>

        {/* Nota de anonimato */}
        <p style={{ textAlign:'center', fontSize:13, color:t.textLight, marginBottom:20 }}>
          🔒 Tus respuestas son <strong>anónimas</strong>. No guardamos tu nombre, email ni teléfono.
        </p>

        {/* Botón enviar */}
        <button
          onClick={submit}
          disabled={!allAnswered || status === 'sending'}
          style={{
            width:'100%',
            background: allAnswered ? t.primary : t.border,
            color:'#fff',
            border:'none',
            cursor: allAnswered && status !== 'sending' ? 'pointer' : 'not-allowed',
            padding:'18px 28px',
            borderRadius:100,
            fontSize:18,
            fontWeight:700,
            fontFamily:'Outfit,sans-serif',
            boxShadow: allAnswered ? '0 8px 24px rgba(61,87,64,0.3)' : 'none',
            transition:'all 0.2s ease',
            opacity: status === 'sending' ? 0.7 : 1,
          }}
        >
          {status === 'sending' ? 'Enviando...' : allAnswered ? `Enviar y recibir mi regalo 🎁` : `Responde las ${5-progress} preguntas pendientes`}
        </button>

        {status === 'error' && (
          <p style={{ textAlign:'center', color:'#b00020', marginTop:16, fontSize:14 }}>
            ❌ No hemos podido enviar. Inténtalo de nuevo en un momento.
          </p>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { cats, Home, Shop, Detail, HowItWorks, SellerPortal, InstallApp, About, Feedback });

/* ── CONTACT ── Página dedicada con cara, teléfono, dirección y horario */
function Contact({ t, setPage }) {
  const [copied, setCopied] = React.useState('');
  const copy = async (text, key) => {
    try { await navigator.clipboard.writeText(text); setCopied(key); setTimeout(()=>setCopied(''), 2000); } catch {}
  };

  return (
    <div className="zv-section" style={{ background:t.bg, minHeight:'100vh', padding:'48px 28px' }}>
      <div style={{ maxWidth:720, margin:'0 auto' }}>

        {/* Cabecera con avatar + nombre */}
        <div style={{ textAlign:'center', marginBottom:32 }}>
          <div style={{ width:140, height:140, borderRadius:'50%', background:t.primary, color:'#fff', display:'flex', alignItems:'center', justifyContent:'center', fontSize:64, fontWeight:900, margin:'0 auto 18px', boxShadow:'0 10px 30px rgba(61,87,64,0.3)', border:`5px solid ${t.bg}` }}>
            J
          </div>
          <h1 className="zv-big-title" style={{ fontSize:'clamp(30px,5.5vw,40px)', fontWeight:900, color:t.text, lineHeight:1.15, marginBottom:10 }}>
            Hablemos. Estoy aquí.
          </h1>
          <p style={{ fontSize:17, color:t.textMid, lineHeight:1.55, maxWidth:520, margin:'0 auto' }}>
            Soy <strong style={{ color:t.text }}>Josep</strong>, el responsable de Zeus Ventas. Llámame, escríbeme o pásate. Sin compromiso.
          </p>
        </div>

        {/* WhatsApp destacado */}
        <a href={waUrl('Hola Josep, quería preguntarte por Zeus Ventas.')} target="_blank" rel="noopener noreferrer" style={{ textDecoration:'none', display:'block', marginBottom:14 }}>
          <div style={{ background:'#25d366', color:'#fff', borderRadius:18, padding:'22px 24px', display:'flex', alignItems:'center', gap:18, cursor:'pointer', boxShadow:'0 6px 20px rgba(37,211,102,0.35)' }}>
            <div style={{ fontSize:42, lineHeight:1 }}>💬</div>
            <div style={{ flex:1 }}>
              <div style={{ fontSize:13, fontWeight:700, opacity:0.85, letterSpacing:1, textTransform:'uppercase' }}>La forma más rápida</div>
              <div style={{ fontSize:20, fontWeight:900, marginTop:2 }}>Escríbeme por WhatsApp</div>
              <div style={{ fontSize:14, opacity:0.85, marginTop:2 }}>Respondo en menos de 2 horas en horario laboral</div>
            </div>
            <div style={{ fontSize:24, opacity:0.8 }}>→</div>
          </div>
        </a>

        {/* Bloques de contacto */}
        <div style={{ display:'grid', gridTemplateColumns:'repeat(auto-fit, minmax(220px, 1fr))', gap:14, marginBottom:14 }}>

          {/* Teléfono */}
          <div style={{ background:t.card, border:`2px solid ${t.border}`, borderRadius:18, padding:'22px 20px' }}>
            <div style={{ fontSize:32, marginBottom:8 }}>📞</div>
            <div style={{ fontSize:13, fontWeight:700, color:t.textLight, letterSpacing:1, textTransform:'uppercase', marginBottom:4 }}>Teléfono</div>
            <a href={'tel:+34' + WA_NUMBER.slice(2)} style={{ fontSize:22, fontWeight:900, color:t.text, textDecoration:'none', display:'block', marginBottom:8 }}>
              699 601 627
            </a>
            <button onClick={()=>copy('699601627', 'tel')} style={{ background:'none', border:'none', color:t.primary, fontSize:13, fontWeight:700, cursor:'pointer', fontFamily:'Outfit,sans-serif', padding:0 }}>
              {copied === 'tel' ? '✓ Copiado' : '📋 Copiar número'}
            </button>
          </div>

          {/* Email */}
          <div style={{ background:t.card, border:`2px solid ${t.border}`, borderRadius:18, padding:'22px 20px' }}>
            <div style={{ fontSize:32, marginBottom:8 }}>✉️</div>
            <div style={{ fontSize:13, fontWeight:700, color:t.textLight, letterSpacing:1, textTransform:'uppercase', marginBottom:4 }}>Email</div>
            <a href="mailto:hola@zeusventas.es" style={{ fontSize:18, fontWeight:800, color:t.text, textDecoration:'none', display:'block', marginBottom:8, wordBreak:'break-all' }}>
              hola@zeusventas.es
            </a>
            <button onClick={()=>copy('hola@zeusventas.es', 'mail')} style={{ background:'none', border:'none', color:t.primary, fontSize:13, fontWeight:700, cursor:'pointer', fontFamily:'Outfit,sans-serif', padding:0 }}>
              {copied === 'mail' ? '✓ Copiado' : '📋 Copiar email'}
            </button>
          </div>

          {/* Ubicación */}
          <div style={{ background:t.card, border:`2px solid ${t.border}`, borderRadius:18, padding:'22px 20px' }}>
            <div style={{ fontSize:32, marginBottom:8 }}>📍</div>
            <div style={{ fontSize:13, fontWeight:700, color:t.textLight, letterSpacing:1, textTransform:'uppercase', marginBottom:4 }}>Operamos en</div>
            <div style={{ fontSize:18, fontWeight:800, color:t.text, marginBottom:4 }}>Toda España</div>
            <div style={{ fontSize:13, color:t.textLight, marginTop:6, fontStyle:'italic' }}>Mensajería profesional con seguro</div>
          </div>

          {/* Horario */}
          <div style={{ background:t.card, border:`2px solid ${t.border}`, borderRadius:18, padding:'22px 20px' }}>
            <div style={{ fontSize:32, marginBottom:8 }}>🕐</div>
            <div style={{ fontSize:13, fontWeight:700, color:t.textLight, letterSpacing:1, textTransform:'uppercase', marginBottom:4 }}>Horario</div>
            <div style={{ fontSize:14, color:t.text, lineHeight:1.6 }}>
              <div><strong>Lun – Vie:</strong> 9:00 – 19:00</div>
              <div><strong>Sábado:</strong> 10:00 – 14:00</div>
              <div style={{ color:t.textLight }}><strong>Domingo:</strong> cerrado</div>
            </div>
          </div>
        </div>

        {/* Datos legales */}
        <div style={{ background:t.card, border:`1px solid ${t.border}`, borderRadius:14, padding:'20px 22px', fontSize:13, color:t.textMid, lineHeight:1.7 }}>
          <div style={{ fontWeight:700, color:t.text, marginBottom:8, fontSize:14 }}>📋 Información legal</div>
          <div>Titular: <em>[Pendiente de completar — razón social]</em></div>
          <div>NIF / CIF: <em>[Pendiente]</em></div>
          <div>Domicilio: España</div>
          <div style={{ marginTop:10, paddingTop:10, borderTop:`1px solid ${t.border}` }}>
            Para más información, consulta los <span onClick={()=>setPage('terms')} style={{ color:t.primary, fontWeight:700, cursor:'pointer' }}>términos y condiciones</span>.
          </div>
        </div>

        {/* CTA al final */}
        <div style={{ textAlign:'center', marginTop:32 }}>
          <button onClick={()=>setPage('publish')} style={{ background:t.primary, color:'#fff', border:'none', cursor:'pointer', padding:'16px 32px', borderRadius:100, fontSize:16, fontWeight:700, fontFamily:'Outfit,sans-serif' }}>
            Empezar a vender →
          </button>
        </div>

      </div>
    </div>
  );
}

Object.assign(window, { Contact });

/* ── SHIPPING ── Página dedicada: cómo funciona el envío en detalle */
function Shipping({ t, setPage }) {
  const [openFaq, setOpenFaq] = React.useState(null);

  const tiers = [
    { dot:'🟢', tier:'Pequeño',    price:'7,90€',  weight:'Hasta 3 kg',  desc:'Cabe en una caja de zapatos.', ej:'Vajilla, libros, ropa, herramientas pequeñas, juguetes, joyas' },
    { dot:'🟡', tier:'Mediano',    price:'13,90€', weight:'Hasta 10 kg', desc:'Cabe en una caja grande.',     ej:'Lámparas, microondas, robots de cocina, bolsos grandes, instrumentos pequeños' },
    { dot:'🟠', tier:'Grande',     price:'24,90€', weight:'Hasta 25 kg', desc:'Entre dos personas.',          ej:'Televisores, bicicletas, sillas, hornos, palos de golf' },
    { dot:'🔴', tier:'Voluminoso', price:'A medida', weight:'+25 kg o gran tamaño', desc:'Furgoneta o transporte especial.', ej:'Armarios, sofás, lavadoras, mesas grandes, pianos' },
  ];

  const faqs = [
    {
      q: '¿Y si el objeto llega roto al comprador?',
      a: 'Todos nuestros envíos van con seguro de transporte. Si llega dañado, el comprador nos lo notifica con fotos en 48h y nosotros gestionamos la reclamación con la empresa de transporte. Tú no pierdes el dinero — el seguro cubre el valor declarado.'
    },
    {
      q: '¿Cuánto tarda en llegar?',
      a: 'Para envíos pequeños y medianos: 24-72 horas dentro de la península. Baleares y Canarias: 3-5 días. Para muebles voluminosos: 3-7 días según destino. El comprador recibe siempre un código de seguimiento.'
    },
    {
      q: '¿Tengo que embalar yo el objeto?',
      a: 'No es obligatorio. Si tienes una caja adecuada, perfecto. Si no, te indicamos qué materiales necesitas o coordinamos un servicio de embalaje. Para objetos delicados, recomendamos siempre embalaje profesional — el coste se descuenta de la venta.'
    },
    {
      q: '¿El transportista pasa por mi casa?',
      a: 'Sí, normalmente sí. Concertamos día y franja horaria contigo. Si prefieres llevarlo tú a un punto de recogida (más barato y más flexible), también podemos hacerlo así. Tú eliges.'
    },
    {
      q: '¿Y si el comprador no quiere el objeto al recibirlo?',
      a: 'Tiene 48h desde la entrega para reclamar si el objeto no es como se anunció. Si la reclamación es justificada, el transportista lo recoge y vuelve a ti. Si es un capricho del comprador, el envío de vuelta lo paga él.'
    },
    {
      q: '¿Cómo se calcula el precio del envío de un mueble?',
      a: 'Para muebles voluminosos pedimos cotización a transportistas especializados (Mudango, TransGloba) con las medidas y origen-destino. En 24h tenemos un precio en firme que comunicamos al comprador antes de cerrar la venta.'
    },
    {
      q: '¿Qué pasa si me equivoco al estimar el tamaño?',
      a: 'Nada grave. Cuando recibimos el objeto verificamos el tamaño real. Si quedó en una categoría más alta, lo ajustamos antes de cerrar la venta — el comprador acepta el nuevo precio o cancela. Si quedó en una más baja, mejor para todos.'
    },
    {
      q: '¿Puedo enviar a Baleares, Canarias, Ceuta o Melilla?',
      a: 'Sí. El precio es algo más alto y el plazo más largo (3-7 días). Avisamos al comprador antes de cerrar la operación.'
    },
  ];

  return (
    <div className="zv-section" style={{ background:t.bg, minHeight:'100vh', padding:'48px 24px' }}>
      <div style={{ maxWidth:840, margin:'0 auto' }}>

        {/* Cabecera */}
        <div style={{ textAlign:'center', marginBottom:36 }}>
          <div style={{ fontSize:13, fontWeight:700, color:t.primary, letterSpacing:1.5, marginBottom:10, textTransform:'uppercase' }}>
            Envíos a toda España
          </div>
          <h1 className="zv-big-title" style={{ fontSize:'clamp(32px,6vw,48px)', fontWeight:900, color:t.text, lineHeight:1.1, marginBottom:14 }}>
            Cómo funciona el envío
          </h1>
          <p style={{ fontSize:17, color:t.textMid, lineHeight:1.55, maxWidth:600, margin:'0 auto' }}>
            Trabajamos con empresas de transporte profesionales y aseguradas. <strong style={{ color:t.text }}>Tú no pagas nada del envío</strong> — el comprador lo asume al hacer la compra.
          </p>
        </div>

        {/* 4 pasos */}
        <div style={{ background:t.card, border:`1px solid ${t.border}`, borderRadius:18, padding:'28px 24px', marginBottom:30 }}>
          <h2 style={{ fontSize:22, fontWeight:900, color:t.text, marginBottom:20, textAlign:'center' }}>El proceso, paso a paso</h2>
          <div style={{ display:'flex', flexDirection:'column', gap:18 }}>
            {[
              { n:'1', title:'Calculamos el envío al publicar', body:'Cuando subimos tu anuncio, asignamos una categoría de tamaño (Pequeño, Mediano, Grande o Voluminoso). El precio del envío se muestra en el anuncio desde el primer momento.' },
              { n:'2', title:'El comprador acepta y paga', body:'El comprador ve el precio del objeto + el envío + los plazos antes de pagar. No hay sorpresas. El dinero queda retenido hasta que reciba el objeto.' },
              { n:'3', title:'Coordinamos la recogida contigo', body:'Te llamamos para acordar día y hora. El transportista pasa por tu casa con la etiqueta ya impresa, o si lo prefieres llevas el paquete a un punto de recogida cercano.' },
              { n:'4', title:'Llega al comprador y tú cobras', body:'El comprador tiene 48h para confirmar que el objeto está bien. Pasado ese tiempo, te ingresamos el dinero (precio de venta menos comisión) en tu cuenta bancaria.' },
            ].map(s => (
              <div key={s.n} style={{ display:'flex', gap:16, alignItems:'flex-start' }}>
                <div style={{ width:38, height:38, borderRadius:'50%', background:t.primary, color:'#fff', display:'flex', alignItems:'center', justifyContent:'center', fontWeight:900, fontSize:16, flex:'0 0 auto' }}>{s.n}</div>
                <div>
                  <div style={{ fontSize:16, fontWeight:800, color:t.text, marginBottom:4 }}>{s.title}</div>
                  <div style={{ fontSize:14, color:t.textMid, lineHeight:1.55 }}>{s.body}</div>
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* Tarifas */}
        <h2 style={{ fontSize:24, fontWeight:900, color:t.text, marginBottom:14, textAlign:'center' }}>Tarifas por tamaño</h2>
        <p style={{ fontSize:14, color:t.textLight, marginBottom:20, textAlign:'center', fontStyle:'italic' }}>
          Precios fijos para envíos a península. Baleares, Canarias y Ceuta/Melilla: consultar.
        </p>

        <div style={{ display:'grid', gridTemplateColumns:'repeat(auto-fit, minmax(180px, 1fr))', gap:12, marginBottom:30 }}>
          {tiers.map(tr => (
            <div key={tr.tier} style={{ background:t.card, border:`1px solid ${t.border}`, borderRadius:14, padding:'18px 16px' }}>
              <div style={{ fontSize:24, marginBottom:4 }}>{tr.dot}</div>
              <div style={{ fontSize:12, fontWeight:700, color:t.textLight, letterSpacing:1, textTransform:'uppercase', marginBottom:2 }}>{tr.tier}</div>
              <div style={{ fontSize:13, color:t.textLight, marginBottom:6 }}>{tr.weight}</div>
              <div style={{ fontSize:22, fontWeight:900, color:t.primary, marginBottom:8 }}>{tr.price}</div>
              <div style={{ fontSize:12, color:t.text, marginBottom:6, fontStyle:'italic' }}>{tr.desc}</div>
              <div style={{ fontSize:11, color:t.textLight, lineHeight:1.45 }}>{tr.ej}</div>
            </div>
          ))}
        </div>

        {/* Garantías */}
        <div style={{ background:t.bgAlt, borderRadius:16, padding:'22px 24px', marginBottom:30 }}>
          <div style={{ fontSize:13, fontWeight:800, color:t.primary, letterSpacing:1, marginBottom:10, textTransform:'uppercase' }}>
            🛡️ Lo que está incluido siempre
          </div>
          <ul style={{ listStyle:'none', padding:0, margin:0, fontSize:15, color:t.textMid, lineHeight:1.8 }}>
            <li>✅ <strong style={{ color:t.text }}>Seguro de transporte</strong> con cobertura del valor del objeto</li>
            <li>✅ <strong style={{ color:t.text }}>Código de seguimiento</strong> para vendedor y comprador</li>
            <li>✅ <strong style={{ color:t.text }}>Custodia del dinero</strong> hasta que el objeto llegue bien</li>
            <li>✅ <strong style={{ color:t.text }}>Gestión de incidencias</strong> con la empresa de transporte (lo hacemos nosotros, no tú)</li>
            <li>✅ <strong style={{ color:t.text }}>Plazo de reclamación</strong> de 48h para el comprador</li>
          </ul>
        </div>

        {/* FAQ */}
        <h2 style={{ fontSize:24, fontWeight:900, color:t.text, marginBottom:18, textAlign:'center' }}>Preguntas frecuentes</h2>
        <div style={{ display:'flex', flexDirection:'column', gap:10, marginBottom:30 }}>
          {faqs.map((f, i) => (
            <div key={i} style={{ background:t.card, border:`1px solid ${t.border}`, borderRadius:12, overflow:'hidden' }}>
              <button
                onClick={()=>setOpenFaq(openFaq===i?null:i)}
                style={{
                  width:'100%',
                  background:'none',
                  border:'none',
                  cursor:'pointer',
                  padding:'16px 20px',
                  fontSize:15,
                  fontWeight:700,
                  color:t.text,
                  textAlign:'left',
                  fontFamily:'Outfit,sans-serif',
                  display:'flex',
                  justifyContent:'space-between',
                  alignItems:'center',
                  gap:12,
                }}
              >
                <span>{f.q}</span>
                <span style={{ fontSize:18, color:t.primary, transform:openFaq===i?'rotate(45deg)':'none', transition:'transform 0.2s', flex:'0 0 auto' }}>+</span>
              </button>
              {openFaq===i && (
                <div style={{ padding:'0 20px 16px', fontSize:14, color:t.textMid, lineHeight:1.6 }}>
                  {f.a}
                </div>
              )}
            </div>
          ))}
        </div>

        {/* CTA final */}
        <div style={{ textAlign:'center', padding:'32px 0' }}>
          <h3 style={{ fontSize:20, fontWeight:800, color:t.text, marginBottom:14 }}>¿Listo para vender?</h3>
          <BigWhatsAppButton t={t} />
          <p style={{ fontSize:14, color:t.textLight, marginTop:14 }}>
            ¿Tienes dudas sobre un objeto concreto? <a href={'tel:+34' + WA_NUMBER.slice(2)} style={{ color:t.primary, fontWeight:700, textDecoration:'none' }}>Llámanos al 699 601 627</a>
          </p>
        </div>

      </div>
    </div>
  );
}

Object.assign(window, { Shipping });

/* ── INBOX ── Buzón unificado: ofertas como comprador y vendedor en un solo sitio */
function Inbox({ t, setPage }) {
  const [tick, setTick] = React.useState(0);
  React.useEffect(() => {
    const handler = () => setTick(x => x + 1);
    window.addEventListener('zeus:operations-updated', handler);
    return () => window.removeEventListener('zeus:operations-updated', handler);
  }, []);

  const myBuyerPhone = (localStorage.getItem('zeus_buyer_phone') || '').replace(/\s/g,'');
  const mySellerPhone = (localStorage.getItem('zeus_seller_phone') || '').replace(/\s/g,'');
  const ops = loadOperations();
  const products = loadProducts();
  const productById = (id) => products.find(p => p.id === id);

  // Como COMPRADOR: ops donde he hecho oferta o me han contraofertado o aceptado
  const asBuyer = !myBuyerPhone ? [] : ops.filter(op => {
    const norm = s => (s || '').replace(/\s/g,'');
    return (op.offers || []).some(o => norm(o.buyerPhone) === myBuyerPhone)
        || (op.counterOffers || []).some(c => norm(c.buyerPhone) === myBuyerPhone);
  });

  // Como VENDEDOR: ops sobre mis productos con ofertas pendientes o en curso
  const asSeller = !mySellerPhone ? [] : ops.filter(op => {
    if (op.status === 'vendido' || op.status === 'cancelado') return false;
    const product = productById(op.productId);
    if (!product) return false;
    return (product.phone || '').replace(/\s/g,'') === mySellerPhone;
  });

  const renderBuyerItem = (op) => {
    const product = productById(op.productId);
    const myOffer = (op.offers || []).filter(o => (o.buyerPhone||'').replace(/\s/g,'') === myBuyerPhone).sort((a,b)=>b.time-a.time)[0];
    const myCounter = (op.counterOffers || []).filter(c => (c.buyerPhone||'').replace(/\s/g,'') === myBuyerPhone).sort((a,b)=>b.time-a.time)[0];
    let title = '', subtitle = '', color = t.textMid, urgent = false;
    if (myCounter && myCounter.status === 'pendiente') {
      title = `🟣 Tienes una contraoferta de ${myCounter.amount}€`; color = '#5b21b6'; urgent = true;
    } else if (myOffer && myOffer.status === 'aceptada') {
      title = `✅ Tu oferta de ${myOffer.amount}€ fue aceptada`; color = '#15803d'; urgent = true;
    } else if (myOffer && myOffer.status === 'pendiente') {
      title = `⏳ Tu oferta de ${myOffer.amount}€ está pendiente`; color = '#a16207';
    } else if (myOffer && myOffer.status === 'rechazada') {
      title = `❌ Tu oferta de ${myOffer.amount}€ fue rechazada`; color = '#b91c1c';
    } else if (myOffer && myOffer.status === 'retirada') {
      title = `↩️ Retiraste tu oferta de ${myOffer.amount}€`; color = t.textLight;
    }
    subtitle = product?.title || '(producto)';

    return (
      <div
        key={op.id}
        onClick={()=>{ if (product) { window.location.hash = 'product/' + op.productId; } }}
        style={{
          background: urgent ? color + '10' : t.card,
          border: `1px solid ${urgent ? color + '40' : t.border}`,
          borderRadius:12, padding:'12px 14px', marginBottom:8,
          cursor:'pointer', display:'flex', gap:12, alignItems:'center',
        }}
      >
        {product?.photo && <img src={product.photo} alt="" style={{ width:48, height:48, objectFit:'cover', borderRadius:8, flex:'0 0 auto' }} />}
        <div style={{ flex:1, minWidth:0 }}>
          <div style={{ fontSize:13, fontWeight:800, color, marginBottom:2 }}>{title}</div>
          <div style={{ fontSize:14, fontWeight:600, color:t.text, whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>{subtitle}</div>
          <div style={{ fontSize:11, color:t.textLight, marginTop:2 }}>{timeSince(op.updatedAt)}</div>
        </div>
        <div style={{ fontSize:18, color:t.textLight }}>›</div>
      </div>
    );
  };

  const renderSellerItem = (op) => {
    const product = productById(op.productId);
    const pending = (op.offers || []).filter(o => o.status === 'pendiente');
    let title = '', color = t.textMid, urgent = false;
    if (op.status === 'con_oferta' && pending.length) {
      title = `🟡 ${pending.length} oferta(s) nueva(s) — mejor: ${Math.max(...pending.map(o=>o.amount))}€`; color = '#a16207'; urgent = true;
    } else if (op.status === 'reservado') {
      title = `🟠 Reservado · ${op.finalPrice}€ · pendiente pago`; color = '#c2410c';
    } else if (op.status === 'pagado') {
      title = `💳 Pagado · pendiente envío`; color = '#7c3aed';
    } else if (op.status === 'en_transito') {
      title = `📦 En tránsito`; color = '#1d4ed8';
    } else {
      return null;
    }

    return (
      <div
        key={op.id}
        onClick={()=>{ if (product) { window.location.hash = 'seller/' + ((product.phone||'').replace(/\s/g,'') || ''); setPage('seller'); } }}
        style={{
          background: urgent ? color + '10' : t.card,
          border: `1px solid ${urgent ? color + '40' : t.border}`,
          borderRadius:12, padding:'12px 14px', marginBottom:8,
          cursor:'pointer', display:'flex', gap:12, alignItems:'center',
        }}
      >
        {product?.photo && <img src={product.photo} alt="" style={{ width:48, height:48, objectFit:'cover', borderRadius:8, flex:'0 0 auto' }} />}
        <div style={{ flex:1, minWidth:0 }}>
          <div style={{ fontSize:13, fontWeight:800, color, marginBottom:2 }}>{title}</div>
          <div style={{ fontSize:14, fontWeight:600, color:t.text, whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>{product?.title || '(producto)'}</div>
          <div style={{ fontSize:11, color:t.textLight, marginTop:2 }}>{timeSince(op.updatedAt)}</div>
        </div>
        <div style={{ fontSize:18, color:t.textLight }}>›</div>
      </div>
    );
  };

  const sellerItems = asSeller.map(renderSellerItem).filter(Boolean);

  return (
    <div className="zv-section" style={{ background:t.bg, minHeight:'100vh', padding:'40px 20px' }}>
      <div style={{ maxWidth:680, margin:'0 auto' }}>
        <h1 className="zv-big-title" style={{ fontSize:'clamp(28px,5.5vw,38px)', fontWeight:900, color:t.text, marginBottom:20 }}>💬 Buzón</h1>

        {/* COMO VENDEDOR */}
        {sellerItems.length > 0 && (
          <div style={{ marginBottom:24 }}>
            <h2 style={{ fontSize:14, fontWeight:800, color:t.textLight, letterSpacing:1.5, textTransform:'uppercase', marginBottom:10 }}>🏷️ Vendiendo</h2>
            {sellerItems}
          </div>
        )}

        {/* COMO COMPRADOR */}
        {asBuyer.length > 0 && (
          <div style={{ marginBottom:24 }}>
            <h2 style={{ fontSize:14, fontWeight:800, color:t.textLight, letterSpacing:1.5, textTransform:'uppercase', marginBottom:10 }}>🛒 Comprando</h2>
            {asBuyer.map(renderBuyerItem)}
          </div>
        )}

        {sellerItems.length === 0 && asBuyer.length === 0 && (
          <div style={{ background:t.card, border:`1px dashed ${t.border}`, borderRadius:14, padding:'40px 20px', textAlign:'center' }}>
            <div style={{ fontSize:48, marginBottom:12 }}>📭</div>
            <h2 style={{ fontSize:18, fontWeight:800, color:t.text, marginBottom:8 }}>Tu buzón está vacío</h2>
            <p style={{ fontSize:14, color:t.textMid, lineHeight:1.6, marginBottom:18 }}>
              Aquí verás las ofertas que hagas como comprador y las ofertas que recibas en tus anuncios como vendedor.
            </p>
            <div style={{ display:'flex', gap:8, justifyContent:'center', flexWrap:'wrap' }}>
              <button onClick={()=>setPage('shop')} style={{ background:t.primary, color:'#fff', border:'none', cursor:'pointer', padding:'10px 18px', borderRadius:100, fontSize:14, fontWeight:700, fontFamily:'Outfit,sans-serif' }}>
                🔍 Buscar productos
              </button>
              <button onClick={()=>setPage('publish')} style={{ background:'none', color:t.primary, border:`2px solid ${t.primary}`, cursor:'pointer', padding:'10px 18px', borderRadius:100, fontSize:14, fontWeight:700, fontFamily:'Outfit,sans-serif' }}>
                + Vender algo
              </button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

/* ── MY ACCOUNT ── Hub personal con dos botones grandes Compro/Vendo */
function MyAccount({ t, setPage }) {
  const buyerName = localStorage.getItem('zeus_buyer_name') || '';
  const buyerPhone = localStorage.getItem('zeus_buyer_phone') || '';
  const sellerPhone = localStorage.getItem('zeus_seller_phone') || '';
  const knownPhone = sellerPhone || buyerPhone;
  const knownName = buyerName || '';

  return (
    <div className="zv-section" style={{ background:t.bg, minHeight:'100vh', padding:'40px 20px' }}>
      <div style={{ maxWidth:600, margin:'0 auto' }}>

        {/* Saludo */}
        <div style={{ background:t.primary, color:'#fff', borderRadius:18, padding:'22px 24px', marginBottom:20, display:'flex', alignItems:'center', gap:14 }}>
          <div style={{ width:56, height:56, borderRadius:'50%', background:'rgba(255,255,255,0.25)', display:'flex', alignItems:'center', justifyContent:'center', fontSize:26, fontWeight:900, flex:'0 0 auto' }}>
            {(knownName ? knownName.charAt(0) : 'Z').toUpperCase()}
          </div>
          <div style={{ flex:1, minWidth:0 }}>
            <div style={{ fontSize:18, fontWeight:900 }}>{knownName ? `Hola, ${knownName.split(' ')[0]}` : 'Bienvenido'}</div>
            {knownPhone && <div style={{ fontSize:13, opacity:0.85 }}>📞 {knownPhone}</div>}
            {!knownPhone && <div style={{ fontSize:13, opacity:0.85 }}>Aún no has comprado ni vendido nada</div>}
          </div>
        </div>

        {/* Dos botones grandes Compro / Vendo */}
        <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:14, marginBottom:24 }}>
          <button onClick={()=>setPage('inbox')} style={{ background:t.card, border:`2px solid ${t.border}`, borderRadius:18, padding:'24px 16px', cursor:'pointer', textAlign:'center', fontFamily:'Outfit,sans-serif' }}>
            <div style={{ fontSize:42, marginBottom:8 }}>🛒</div>
            <div style={{ fontSize:18, fontWeight:900, color:t.text, marginBottom:4 }}>COMPRO</div>
            <div style={{ fontSize:12, color:t.textLight, lineHeight:1.4 }}>Mis ofertas y compras</div>
          </button>
          <button onClick={()=>setPage('seller')} style={{ background:t.card, border:`2px solid ${t.border}`, borderRadius:18, padding:'24px 16px', cursor:'pointer', textAlign:'center', fontFamily:'Outfit,sans-serif' }}>
            <div style={{ fontSize:42, marginBottom:8 }}>🏷️</div>
            <div style={{ fontSize:18, fontWeight:900, color:t.text, marginBottom:4 }}>VENDO</div>
            <div style={{ fontSize:12, color:t.textLight, lineHeight:1.4 }}>Mis anuncios</div>
          </button>
        </div>

        {/* Resto de opciones */}
        <div style={{ background:t.card, border:`1px solid ${t.border}`, borderRadius:14, overflow:'hidden' }}>
          {[
            { icon:'📞', label:'Contacto y soporte', page:'contact' },
            { icon:'📦', label:'Cómo funcionan los envíos', page:'shipping' },
            { icon:'❓', label:'Cómo funciona Zeus Ventas', page:'how' },
            { icon:'🧮', label:'Calculadora de comisiones', page:'calculator' },
            { icon:'📋', label:'Términos y condiciones', page:'terms' },
            { icon:'💚', label:'Quiénes somos', page:'about' },
            { icon:'💡', label:'Sugerencias', page:'feedback' },
            { icon:'📲', label:'Descargar app', page:'download' },
          ].map((it, i, arr) => (
            <button
              key={it.page}
              onClick={()=>setPage(it.page)}
              style={{
                background:'none', border:'none', cursor:'pointer',
                width:'100%', padding:'16px 18px', textAlign:'left',
                display:'flex', alignItems:'center', gap:14,
                fontFamily:'Outfit,sans-serif', color:t.text, fontSize:15, fontWeight:600,
                borderBottom: i < arr.length - 1 ? `1px solid ${t.border}` : 'none',
              }}
            >
              <span style={{ fontSize:22 }}>{it.icon}</span>
              <span style={{ flex:1 }}>{it.label}</span>
              <span style={{ fontSize:18, color:t.textLight }}>›</span>
            </button>
          ))}
        </div>

        {/* Cerrar sesión / limpiar datos */}
        {(buyerPhone || sellerPhone) && (
          <button
            onClick={()=>{
              if (!confirm('Esto borrará tu nombre y teléfono guardados en este dispositivo. ¿Continuar?')) return;
              localStorage.removeItem('zeus_buyer_phone');
              localStorage.removeItem('zeus_buyer_name');
              localStorage.removeItem('zeus_buyer_email');
              localStorage.removeItem('zeus_seller_phone');
              alert('Datos borrados.');
              setPage('home');
            }}
            style={{ background:'none', color:t.textLight, border:`1px solid ${t.border}`, cursor:'pointer', padding:'10px 18px', borderRadius:100, fontSize:13, fontWeight:600, fontFamily:'Outfit,sans-serif', marginTop:18, width:'100%' }}
          >
            🚪 Cerrar sesión (borrar datos de este dispositivo)
          </button>
        )}

      </div>
    </div>
  );
}

Object.assign(window, { Inbox, MyAccount });
