// zeus-components.jsx — Shared UI components

const themes = {
  verde: {
    bg: '#f0ece4', bgAlt: '#e8e3d8', primary: '#3d5740', accent: '#c4773a',
    accentLight: '#f5e8d8', text: '#1a1a17', textMid: '#4a4a44', textLight: '#7a7a72',
    card: '#faf8f3', border: '#d8d3c8'
  },
  naranja: {
    bg: '#fef7ee', bgAlt: '#faeedd', primary: '#c4610a', accent: '#3d5740',
    accentLight: '#e8f0e9', text: '#1a1410', textMid: '#4a3e30', textLight: '#7a6a58',
    card: '#fffcf7', border: '#e8d8c4'
  }
};

const statusConfig = {
  nuevo:    { label: 'Nuevo',       color: '#2563eb', bg: '#eff6ff' },
  valorado: { label: 'Valorado',    color: '#7c3aed', bg: '#f5f3ff' },
  publicado:{ label: 'Publicado',   color: '#0891b2', bg: '#ecfeff' },
  oferta:   { label: 'Con oferta',  color: '#d97706', bg: '#fffbeb' },
  enviado:  { label: 'En camino',   color: '#dc2626', bg: '#fef2f2' },
  vendido:  { label: 'Vendido',     color: '#16a34a', bg: '#f0fdf4' },
};

/* ── useProducts hook ── */
function useProducts() {
  const [products, setProducts] = React.useState(() => loadProducts());
  React.useEffect(() => {
    const handler = () => setProducts(loadProducts());
    window.addEventListener('zeus:products-updated', handler);
    window.addEventListener('storage', handler);
    return () => {
      window.removeEventListener('zeus:products-updated', handler);
      window.removeEventListener('storage', handler);
    };
  }, []);
  return products;
}

/* ── useFavorites hook ── */
function useFavorites() {
  const [favs, setFavs] = React.useState(() => loadFavorites());
  React.useEffect(() => {
    const handler = () => setFavs(loadFavorites());
    window.addEventListener('zeus:favorites-updated', handler);
    return () => window.removeEventListener('zeus:favorites-updated', handler);
  }, []);
  return favs;
}

/* ── EmptyState ── */
function EmptyState({ t, icon, title, subtitle, actionLabel, onAction }) {
  return (
    <div style={{ textAlign:'center', padding:'64px 24px', background:t.card, border:`2px dashed ${t.border}`, borderRadius:24 }}>
      <div style={{ fontSize:64, marginBottom:16 }}>{icon}</div>
      <h3 style={{ fontSize:24, fontWeight:800, color:t.text, marginBottom:8 }}>{title}</h3>
      <p style={{ fontSize:17, color:t.textMid, marginBottom:actionLabel?24:0, lineHeight:1.6 }}>{subtitle}</p>
      {actionLabel && (
        <button onClick={onAction} style={{ background:t.primary, color:'#fff', border:'none', cursor:'pointer', padding:'16px 32px', borderRadius:100, fontSize:17, fontWeight:700, fontFamily:'Outfit,sans-serif' }}>
          {actionLabel}
        </button>
      )}
    </div>
  );
}

/* ── ProductImage ── */
function ProductImage({ product, h=220, style={} }) {
  if (product?.photo) {
    return (
      <div style={{ width:'100%', height:h, overflow:'hidden', ...style }}>
        <img src={product.photo} alt={product.title} style={{ width:'100%', height:'100%', objectFit:'cover', display:'block' }} loading="lazy" />
      </div>
    );
  }
  const colors = ['#ddd8cc','#d4cfc4','#ccc8bc','#d8d3c4','#c8c4b8','#d0cbbf'];
  const c = colors[(product?.id||0) % colors.length];
  return (
    <div style={{ width:'100%', height:h, background:c, display:'flex', alignItems:'center', justifyContent:'center', ...style }}>
      <span style={{ fontFamily:'monospace', fontSize:13, color:'rgba(0,0,0,0.3)', textAlign:'center', padding:8 }}>
        {product?.title || 'Sin imagen'}
      </span>
    </div>
  );
}

/* ── Lightbox ── */
function Lightbox({ src, alt, onClose }) {
  React.useEffect(() => {
    const handler = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', handler);
    return () => window.removeEventListener('keydown', handler);
  }, [onClose]);
  return (
    <div onClick={onClose} style={{ position:'fixed', inset:0, background:'rgba(0,0,0,0.92)', zIndex:1000, display:'flex', alignItems:'center', justifyContent:'center', cursor:'zoom-out' }}>
      <img src={src} alt={alt} style={{ maxWidth:'90vw', maxHeight:'90vh', objectFit:'contain', borderRadius:8, boxShadow:'0 20px 80px rgba(0,0,0,0.8)' }} onClick={e => e.stopPropagation()} />
      <button onClick={onClose} style={{ position:'absolute', top:24, right:24, background:'rgba(255,255,255,0.15)', border:'none', color:'#fff', width:48, height:48, borderRadius:'50%', fontSize:22, cursor:'pointer', display:'flex', alignItems:'center', justifyContent:'center' }}>✕</button>
    </div>
  );
}

/* ── StatusBadge ── */
function StatusBadge({ status }) {
  const sc = statusConfig[status] || statusConfig.nuevo;
  return (
    <span style={{ background:sc.bg, color:sc.color, borderRadius:100, padding:'5px 12px', fontSize:13, fontWeight:700, whiteSpace:'nowrap' }}>
      {sc.label}
    </span>
  );
}

/* ── ShareMenu ── */
function ShareMenu({ product, t, onClose }) {
  const [copied, setCopied] = React.useState(false);
  const url = window.location.origin + window.location.pathname + '#product/' + product.id;

  const handleCopy = async () => {
    try { await navigator.clipboard.writeText(url); setCopied(true); setTimeout(() => setCopied(false), 2000); }
    catch { alert(url); }
  };
  const handleWA = () => {
    window.open(WA_TEMPLATES.product(product), '_blank');
    onClose();
  };
  const handleNative = async () => {
    await shareProduct(product);
    onClose();
  };

  return (
    <div style={{ position:'fixed', inset:0, zIndex:400, display:'flex', alignItems:'flex-end', justifyContent:'center', background:'rgba(0,0,0,0.4)' }} onClick={onClose}>
      <div style={{ background:t.card, borderRadius:'24px 24px 0 0', padding:'28px 24px', width:'100%', maxWidth:480 }} onClick={e => e.stopPropagation()}>
        <div style={{ fontWeight:800, fontSize:18, color:t.text, marginBottom:4 }}>Compartir anuncio</div>
        <div style={{ fontSize:14, color:t.textLight, marginBottom:20 }}>{product.title} · {product.price}€</div>
        <div style={{ display:'flex', flexDirection:'column', gap:10 }}>
          {navigator.share && (
            <button onClick={handleNative} style={{ background:t.primary, color:'#fff', border:'none', cursor:'pointer', padding:'16px', borderRadius:14, fontSize:16, fontWeight:700, fontFamily:'Outfit,sans-serif', display:'flex', alignItems:'center', gap:12, justifyContent:'center' }}>
              📤 Compartir (nativo)
            </button>
          )}
          <button onClick={handleWA} style={{ background:'#25d366', color:'#fff', border:'none', cursor:'pointer', padding:'16px', borderRadius:14, fontSize:16, fontWeight:700, fontFamily:'Outfit,sans-serif', display:'flex', alignItems:'center', gap:12, justifyContent:'center' }}>
            <svg width="22" height="22" 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>
          <button onClick={handleCopy} style={{ background:t.bgAlt, color:t.text, border:`2px solid ${t.border}`, cursor:'pointer', padding:'16px', borderRadius:14, fontSize:16, fontWeight:700, fontFamily:'Outfit,sans-serif' }}>
            {copied ? '✓ ¡Enlace copiado!' : '🔗 Copiar enlace'}
          </button>
        </div>
        <button onClick={onClose} style={{ width:'100%', marginTop:12, background:'none', border:`2px solid ${t.border}`, cursor:'pointer', padding:'12px', borderRadius:14, fontSize:15, color:t.textLight, fontFamily:'Outfit,sans-serif' }}>Cancelar</button>
      </div>
    </div>
  );
}

/* ── ProductCard ── */
function ProductCard({ p, t, onClick }) {
  const favs = useFavorites();
  const fav = favs.includes(p.id);
  const [shareOpen, setShareOpen] = React.useState(false);
  const sold = p.status === 'vendido';

  return (
    <>
      {shareOpen && <ShareMenu product={p} t={t} onClose={() => setShareOpen(false)} />}
      <div style={{ background:t.card, borderRadius:16, overflow:'hidden', cursor:'pointer', border:`1px solid ${t.border}`, transition:'transform 0.2s, box-shadow 0.2s', position:'relative', opacity: sold ? 0.75 : 1 }}
        onMouseEnter={e => { if (!sold) { e.currentTarget.style.transform='translateY(-4px)'; e.currentTarget.style.boxShadow='0 12px 32px rgba(0,0,0,0.1)'; }}}
        onMouseLeave={e => { e.currentTarget.style.transform=''; e.currentTarget.style.boxShadow=''; }}>

        {/* sold overlay */}
        {sold && <div style={{ position:'absolute', top:12, left:12, zIndex:3, background:'#16a34a', color:'#fff', borderRadius:100, padding:'5px 14px', fontSize:13, fontWeight:800 }}>VENDIDO</div>}

        {/* favorite + share buttons */}
        <div style={{ position:'absolute', top:10, right:10, zIndex:3, display:'flex', gap:6 }}>
          <button onClick={e => { e.stopPropagation(); setShareOpen(true); }}
            style={{ width:34, height:34, borderRadius:'50%', background:'rgba(255,255,255,0.9)', border:'none', cursor:'pointer', display:'flex', alignItems:'center', justifyContent:'center', fontSize:16, backdropFilter:'blur(4px)' }}
            title="Compartir">↑</button>
          <button onClick={e => { e.stopPropagation(); toggleFavorite(p.id); }}
            style={{ width:34, height:34, borderRadius:'50%', background:'rgba(255,255,255,0.9)', border:'none', cursor:'pointer', display:'flex', alignItems:'center', justifyContent:'center', fontSize:18, backdropFilter:'blur(4px)' }}
            title={fav ? 'Quitar de favoritos' : 'Guardar'}>
            {fav ? '❤️' : '🤍'}
          </button>
        </div>

        <div onClick={onClick}><ProductImage product={p} h={200} /></div>
        <div style={{ padding:'18px 18px 22px' }} onClick={onClick}>
          <div style={{ display:'flex', justifyContent:'space-between', alignItems:'flex-start', marginBottom:8, gap:8 }}>
            <span style={{ background:t.accentLight, color:t.accent, borderRadius:100, padding:'4px 12px', fontSize:12, fontWeight:700, whiteSpace:'nowrap' }}>{p.cat||'Otros'}</span>
            <span style={{ fontSize:22, fontWeight:900, color:t.primary, whiteSpace:'nowrap' }}>{p.price}€</span>
          </div>
          <h3 style={{ fontSize:18, fontWeight:700, color:t.text, marginBottom:6, lineHeight:1.3 }}>{p.title}</h3>
          <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center' }}>
            <p style={{ fontSize:14, color:t.textLight }}>📍 {p.location||p.city||'—'}</p>
            {p.views > 0 && <p style={{ fontSize:12, color:t.textLight }}>{p.views} visitas</p>}
          </div>
        </div>
      </div>
    </>
  );
}

/* ── BigWhatsAppButton ── */
function BigWhatsAppButton({ t, label='ENVIAR FOTO POR WHATSAPP' }) {
  const [pulse, setPulse] = React.useState(true);
  React.useEffect(() => { const id = setInterval(() => setPulse(p => !p), 1200); return () => clearInterval(id); }, []);
  return (
    <a href={WA_TEMPLATES.sell()} target="_blank" rel="noopener noreferrer" style={{ textDecoration:'none', display:'inline-block' }}>
      <div style={{ position:'relative', display:'inline-flex' }}>
        <div style={{ position:'absolute', inset:-12, borderRadius:100, background:'#25d366', opacity:pulse?0.2:0, transition:'opacity 1.2s ease-in-out', pointerEvents:'none' }} />
        <button className="zv-big-btn" style={{ background:'#25d366', color:'#fff', border:'none', cursor:'pointer', padding:'26px 48px', borderRadius:100, fontSize:'clamp(18px,3vw,26px)', fontWeight:900, fontFamily:'Outfit,sans-serif', letterSpacing:0.5, display:'flex', alignItems:'center', gap:16, boxShadow:'0 8px 40px rgba(37,211,102,0.45)', whiteSpace:'nowrap', maxWidth:'100%' }}>
          <svg width="32" height="32" 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>
          {label}
        </button>
      </div>
    </a>
  );
}

/* ── AIValuation ── */
function AIValuation({ t, imageBase64, onResult }) {
  const [status, setStatus] = React.useState('idle');
  const [result, setResult] = React.useState(null);
  const [errorMsg, setErrorMsg] = React.useState('');

  const compressImage = (base64) => new Promise((resolve) => {
    const img = new Image();
    img.onload = () => {
      const MAX=800; let w=img.width, h=img.height;
      if (w>MAX||h>MAX) { if(w>h){h=Math.round(h*MAX/w);w=MAX;}else{w=Math.round(w*MAX/h);h=MAX;} }
      const canvas=document.createElement('canvas'); canvas.width=w; canvas.height=h;
      canvas.getContext('2d').drawImage(img,0,0,w,h);
      resolve(canvas.toDataURL('image/jpeg',0.7).split(',')[1]);
    };
    img.src='data:image/jpeg;base64,'+base64;
  });

  const analyze = async () => {
    setStatus('loading'); setErrorMsg('');
    try {
      // Usar valuateImage del módulo zeus-claude.js (modo demo o api según config)
      if (typeof window.valuateImage !== 'function') {
        throw new Error('Módulo de valoración no cargado');
      }

      // Obtener pista del título del producto si está
      const userHint = (window.zeusCurrentDraft?.title || '') + ' ' + (window.zeusCurrentDraft?.cat || '');

      const claudeResult = await window.valuateImage(imageBase64, userHint);
      if (!claudeResult) throw new Error('Sin respuesta de la valoración');

      // Adaptar al formato esperado por el resto del código
      const json = {
        titulo: claudeResult.title,
        categoria: claudeResult.category === 'muebles' ? 'Muebles'
                 : claudeResult.category === 'hogar' ? 'Hogar'
                 : claudeResult.category === 'electronica' ? 'Electrodomésticos'
                 : claudeResult.category === 'coleccionismo' ? 'Coleccionismo'
                 : claudeResult.category === 'ropa' ? 'Ropa y textil'
                 : claudeResult.category === 'herramientas' ? 'Hogar'
                 : 'Otros',
        estado: claudeResult.condition === 'nuevo o casi nuevo' ? 'Excelente'
              : claudeResult.condition === 'usado pero en buen estado' ? 'Bueno'
              : claudeResult.condition === 'antigua/coleccionismo' ? 'Muy bueno'
              : 'Regular',
        precio_min: claudeResult.priceMin,
        precio_max: claudeResult.priceMax,
        precio_recomendado: claudeResult.suggestedPrice,
        descripcion: claudeResult.description,
        puntos_clave: ['Valoración por IA', 'Estado: ' + claudeResult.condition, 'Categoría: ' + claudeResult.category],
        size: claudeResult.suggestedSize,
        mode: claudeResult.mode,
      };

      setResult(json); setStatus('done'); onResult(json);
    } catch(e) {
      setErrorMsg(e.message||'Error');
      setStatus('error');
    }
  };

  React.useEffect(() => { if (imageBase64) analyze(); }, [imageBase64]);

  if (status==='loading') return (
    <div style={{ background:t.card, border:`1px solid ${t.border}`, borderRadius:20, padding:28, textAlign:'center', marginBottom:20 }}>
      <div style={{ fontSize:44, marginBottom:14 }}>🤖</div>
      <div style={{ fontSize:19, fontWeight:800, color:t.text, marginBottom:6 }}>Analizando con IA…</div>
      <div style={{ fontSize:15, color:t.textMid }}>Identificando objeto y calculando precio de mercado</div>
    </div>
  );
  if (status==='error') return (
    <div style={{ background:'#fff5f5', border:'1px solid #fcc', borderRadius:16, padding:18, marginBottom:20 }}>
      <p style={{ fontSize:15, color:'#c00', fontWeight:600, marginBottom:4 }}>No se pudo analizar automáticamente.</p>
      <p style={{ fontSize:14, color:'#800' }}>{errorMsg.includes('no disponible') ? 'Rellena los datos manualmente.' : errorMsg}</p>
    </div>
  );
  if (status==='done' && result) return (
    <div style={{ background:t.accentLight, border:`2px solid ${t.accent}`, borderRadius:20, padding:24, marginBottom:20 }}>
      <div style={{ display:'flex', alignItems:'center', gap:12, marginBottom:16 }}>
        <div style={{ fontSize:28 }}>🤖</div>
        <div style={{ flex:1 }}>
          <div style={{ fontSize:17, fontWeight:900, color:t.text }}>Análisis completado</div>
          <div style={{ fontSize:13, color:t.textMid }}>
            Valorado por <strong>Claude</strong> · Anthropic
            {result.mode === 'demo' && <span style={{ background:'#fef3c7', color:'#92400e', padding:'1px 8px', borderRadius:100, fontSize:11, marginLeft:6, fontWeight:700 }}>DEMO</span>}
          </div>
        </div>
      </div>
      <div style={{ background:t.card, borderRadius:14, padding:'14px 18px', marginBottom:14, display:'flex', justifyContent:'space-between', alignItems:'center', flexWrap:'wrap', gap:12 }}>
        <div>
          <div style={{ fontSize:12, fontWeight:700, color:t.textLight, letterSpacing:1 }}>PRECIO RECOMENDADO</div>
          <div style={{ fontSize:36, fontWeight:900, color:t.primary }}>{result.precio_recomendado}€</div>
          <div style={{ fontSize:13, color:t.textMid }}>{result.precio_min}€ – {result.precio_max}€</div>
        </div>
        <div style={{ textAlign:'right' }}>
          <div style={{ fontSize:12, fontWeight:700, color:t.textLight, letterSpacing:1 }}>ESTADO</div>
          <div style={{ fontSize:18, fontWeight:800, color:t.text, marginTop:4 }}>{result.estado}</div>
          <div style={{ fontSize:12, color:t.textMid, marginTop:2 }}>{result.categoria}</div>
        </div>
      </div>
      <div style={{ display:'flex', flexWrap:'wrap', gap:6 }}>
        {(result.puntos_clave||[]).map((pt,i) => (
          <span key={i} style={{ background:t.card, border:`1px solid ${t.border}`, borderRadius:100, padding:'5px 12px', fontSize:13, fontWeight:600, color:t.textMid }}>✓ {pt}</span>
        ))}
      </div>
    </div>
  );
  return null;
}

/* ── Calculator ── */
function Calculator({ t }) {
  const [price, setPrice] = React.useState(120);
  const commission = commissionRate(price);
  const transport=14, packaging=3;
  const insurance = Math.round(price*0.02*100)/100;
  const gateway  = Math.round((price*0.014+0.25)*100)/100;
  const grossComm= Math.round(price*commission*100)/100;
  const netProfit= Math.round((grossComm-transport-insurance-gateway-packaging)*100)/100;
  const sellerGets=Math.round((price-grossComm)*100)/100;

  const row=(label,val,bold,color)=>(
    <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', padding:'14px 0', borderBottom:`1px solid ${t.border}`, gap:12 }}>
      <span style={{ fontSize:16, color:bold?t.text:t.textMid, fontWeight:bold?700:400 }}>{label}</span>
      <span style={{ fontSize:18, fontWeight:bold?900:600, color:color||(bold?t.text:t.textMid), whiteSpace:'nowrap' }}>{val}</span>
    </div>
  );

  return (
    <div className="zv-section" style={{ background:t.bg, minHeight:'100vh', padding:'48px 32px' }}>
      <div style={{ maxWidth:900, margin:'0 auto' }}>
        <h1 className="zv-big-title" style={{ fontSize:48, fontWeight:900, color:t.text, marginBottom:8 }}>Calculadora de Comisión</h1>
        <p style={{ fontSize:18, color:t.textMid, marginBottom:48 }}>Calcula cuánto gana el vendedor y cuánto gana Zeus Ventas</p>
        <div style={{ background:t.card, border:`1px solid ${t.border}`, borderRadius:24, padding:32, marginBottom:32 }}>
          <div className="zv-calc-slider-header" style={{ display:'flex', justifyContent:'space-between', alignItems:'flex-end', marginBottom:24 }}>
            <div>
              <div style={{ fontSize:14, fontWeight:700, color:t.textLight, letterSpacing:1, marginBottom:4 }}>PRECIO DE VENTA</div>
              <div style={{ fontSize:'clamp(48px,10vw,72px)', fontWeight:900, color:t.primary, lineHeight:1 }}>{price}€</div>
            </div>
            <div style={{ textAlign:'right' }}>
              <div style={{ fontSize:14, color:t.textLight, marginBottom:4 }}>Comisión</div>
              <div style={{ fontSize:'clamp(28px,6vw,36px)', fontWeight:900, color:t.text }}>{Math.round(commission*100)}%</div>
            </div>
          </div>
          <input type="range" min="10" max="2000" step="10" value={price} onChange={e=>setPrice(Number(e.target.value))} style={{ width:'100%', height:8, accentColor:t.primary, cursor:'pointer' }} />
          <div style={{ display:'flex', justifyContent:'space-between', fontSize:13, color:t.textLight, marginTop:8 }}>
            <span>10€</span><span>500€</span><span>1.000€</span><span>2.000€</span>
          </div>
        </div>
        <div className="zv-calc-grid" style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:20 }}>
          <div style={{ background:t.card, border:`1px solid ${t.border}`, borderRadius:20, padding:28 }}>
            <div style={{ fontSize:14, fontWeight:700, color:t.textLight, letterSpacing:1, marginBottom:16 }}>VENDEDOR RECIBE</div>
            <div style={{ fontSize:'clamp(40px,8vw,56px)', fontWeight:900, color:t.primary, marginBottom:16, lineHeight:1 }}>{sellerGets}€</div>
          </div>
          <div style={{ background:t.primary, borderRadius:20, padding:28 }}>
            <div style={{ fontSize:14, fontWeight:700, color:'rgba(255,255,255,0.5)', letterSpacing:1, marginBottom:16 }}>ZEUS VENTAS GANA</div>
            <div style={{ fontSize:'clamp(40px,8vw,56px)', fontWeight:900, color:'#fff', marginBottom:16, lineHeight:1 }}>{Math.max(0,netProfit)}€</div>
          </div>
        </div>
        <div style={{ background:t.card, border:`1px solid ${t.border}`, borderRadius:20, padding:28, marginTop:20 }}>
          {row('Precio de venta', price+'€', true)}
          {row('Comisión bruta ('+Math.round(commission*100)+'%)', '-'+grossComm+'€', false, '#c4610a')}
          {row('Vendedor recibe', sellerGets+'€', true, t.primary)}
          <div style={{ height:12 }}/>
          <div style={{ fontSize:13, fontWeight:700, color:t.textLight, letterSpacing:1, marginBottom:4 }}>COSTES ZEUS</div>
          {row('Transporte','-'+transport+'€')}
          {row('Seguro (2%)','-'+insurance+'€')}
          {row('Pasarela','-'+gateway+'€')}
          {row('Embalaje','-'+packaging+'€')}
          {row('Beneficio neto', Math.max(0,netProfit)+'€', true, netProfit>0?t.primary:'#c00')}
        </div>
        <div style={{ marginTop:32 }}>
          <h2 style={{ fontSize:26, fontWeight:800, color:t.text, marginBottom:16 }}>Escala de comisiones</h2>
          <div className="zv-grid-4" style={{ display:'grid', gridTemplateColumns:'repeat(4,1fr)', gap:12 }}>
            {[['10-49€','30%'],['50-199€','25%'],['200-499€','20%'],['500€+','15%']].map(([rng,pct])=>(
              <div key={rng} style={{ background:t.card, border:`2px solid ${t.border}`, borderRadius:16, padding:20, textAlign:'center' }}>
                <div style={{ fontSize:28, fontWeight:900, color:t.primary }}>{pct}</div>
                <div style={{ fontSize:14, color:t.textMid, marginTop:4 }}>{rng}</div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

/* ── Terms ── */
function Terms({ t }) {
  const Section=({title,children})=>(
    <div style={{ marginBottom:40 }}>
      <h2 style={{ fontSize:24, fontWeight:800, color:t.text, marginBottom:14, paddingBottom:10, borderBottom:`2px solid ${t.border}` }}>{title}</h2>
      <div style={{ fontSize:17, color:t.textMid, lineHeight:1.8 }}>{children}</div>
    </div>
  );
  return (
    <div className="zv-section" style={{ background:t.bg, minHeight:'100vh', padding:'48px 32px' }}>
      <div style={{ maxWidth:800, margin:'0 auto' }}>
        <div style={{ background:t.primary, borderRadius:20, padding:'28px 32px', marginBottom:40 }}>
          <h1 style={{ fontSize:36, fontWeight:900, color:'#fff', marginBottom:8 }}>Términos y Condiciones</h1>
          <p style={{ fontSize:15, color:'rgba(255,255,255,0.65)' }}>Zeus Ventas · Abril 2026</p>
        </div>
        <Section title="1. Descripción del servicio">Zeus Ventas es una plataforma de intermediación para venta de objetos de segunda mano. El vendedor envía una foto, nosotros valoramos con IA, publicamos y gestionamos la logística.</Section>
        <Section title="2. Vendedores">
          <ul style={{ listStyle:'none', display:'flex', flexDirection:'column', gap:10 }}>
            {['El vendedor debe ser propietario legítimo del objeto.','El objeto debe coincidir con la descripción y fotos.','El vendedor acepta el precio antes de publicarse.','Una vez aceptada la oferta, el objeto debe estar disponible.','El pago se libera tras confirmación del comprador.','Zeus Ventas puede rechazar objetos inapropiados.'].map((item,i)=>(
              <li key={i} style={{ display:'flex', gap:12 }}><span style={{ color:t.primary, fontWeight:700 }}>✓</span>{item}</li>
            ))}
          </ul>
        </Section>
        <Section title="3. Comisiones">
          <div className="zv-grid-2" style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:10, marginBottom:14 }}>
            {[['10€-49€','30%'],['50€-199€','25%'],['200€-499€','20%'],['500€+','15%']].map(([rng,pct])=>(
              <div key={rng} style={{ background:t.card, border:`1px solid ${t.border}`, borderRadius:12, padding:'12px 16px' }}>
                <div style={{ fontWeight:700, color:t.text }}>{rng}</div>
                <div style={{ color:t.primary, fontWeight:800 }}>{pct} comisión</div>
              </div>
            ))}
          </div>
          Incluye valoración IA, retoque, publicación, gestión, recogida, embalaje, transporte y seguro. No se cobra si no se vende.
        </Section>
        <Section title="4. Logística">Zeus Ventas recoge, embala, asegura y entrega.</Section>
        <Section title="5. Compradores"><ul style={{ listStyle:'none', display:'flex', flexDirection:'column', gap:10 }}>{['Paga antes del envío.','Tiene 48h para confirmar recepción.','Puede reclamar disconformidad.','Tras confirmar, el pago se libera al vendedor.'].map((item,i)=><li key={i} style={{ display:'flex', gap:12 }}><span style={{ color:t.primary, fontWeight:700 }}>✓</span>{item}</li>)}</ul></Section>
        <Section title="6. Protección de datos">Conforme al RGPD y la LOPDGDD. Los datos solo se usan para gestión de transacciones.</Section>
        <Section title="7. Resolución de conflictos">Zeus Ventas media imparcialmente. En caso de desacuerdo, Juntas Arbitrales de Consumo.</Section>
        <div style={{ background:t.accentLight, borderRadius:16, padding:20, marginTop:16 }}>
          <p style={{ fontSize:15, color:t.accent, fontWeight:600 }}>¿Dudas? Llámanos al <strong>699 601 627</strong>.</p>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, {
  themes, statusConfig,
  useProducts, useFavorites,
  EmptyState, ProductImage, Lightbox, StatusBadge, ShareMenu, ProductCard,
  BigWhatsAppButton, AIValuation, Calculator, Terms,
});
