// zeus-admin.jsx — Admin panel with chart, CSV export, bulk actions

/* ── ADMIN OPERATIONS QUEUE ── Cola de operaciones agrupadas por estado */
function AdminOperationsQueue({ t }) {
  const [tick, setTick] = React.useState(0);
  const [expanded, setExpanded] = React.useState(null);

  React.useEffect(() => {
    const handler = () => setTick(x => x + 1);
    window.addEventListener('zeus:operations-updated', handler);
    return () => window.removeEventListener('zeus:operations-updated', handler);
  }, []);

  const ops = loadOperations();
  const products = loadProducts();
  const productById = (id) => products.find(p => p.id === id);

  // Agrupar operaciones por estado relevante
  const byStatus = {
    con_oferta:  ops.filter(o => o.status === 'con_oferta'),
    reservado:   ops.filter(o => o.status === 'reservado'),
    pagado:      ops.filter(o => o.status === 'pagado'),
    en_transito: ops.filter(o => o.status === 'en_transito'),
  };

  const totalOpen = byStatus.con_oferta.length + byStatus.reservado.length + byStatus.pagado.length + byStatus.en_transito.length;

  if (totalOpen === 0) {
    return (
      <div style={{ background:t.card, border:`1px dashed ${t.border}`, borderRadius:14, padding:'22px 18px', marginBottom:24, textAlign:'center', fontSize:14, color:t.textLight }}>
        📭 No hay operaciones en curso. Las ofertas, reservas y envíos aparecerán aquí.
      </div>
    );
  }

  const handleAction = (op, action, ...args) => {
    if (action === 'paid') {
      const method = prompt('Método de pago (transferencia / bizum / efectivo / otro):', 'transferencia');
      if (!method) return;
      markAsPaid(op.id, method);
    } else if (action === 'shipped') {
      const carrier = prompt('Empresa de transporte:', 'Correos Express');
      if (!carrier) return;
      const tracking = prompt('Código de seguimiento:', '');
      if (tracking === null) return;
      markAsShipped(op.id, carrier, tracking);
    } else if (action === 'delivered') {
      if (!confirm('¿Confirmar que el comprador ha recibido el objeto y todo está OK?')) return;
      markAsDelivered(op.id);
    } else if (action === 'cancel') {
      const reason = prompt('Motivo de cancelación:', '');
      if (reason === null) return;
      cancelOperation(op.id, reason);
    }
  };

  const renderQueue = (statusKey, items, ctaLabel, ctaAction, ctaColor) => {
    if (!items.length) return null;
    const cfg = OP_LABELS[statusKey];
    return (
      <div key={statusKey} style={{ background:t.card, border:`1px solid ${t.border}`, borderRadius:14, marginBottom:14, overflow:'hidden' }}>
        <div style={{ background:cfg.bg, padding:'12px 16px', display:'flex', justifyContent:'space-between', alignItems:'center', borderBottom:`1px solid ${cfg.color}30` }}>
          <div style={{ fontSize:14, fontWeight:800, color:cfg.color, letterSpacing:1, textTransform:'uppercase' }}>
            {cfg.dot} {cfg.label} <span style={{ background:cfg.color, color:'#fff', borderRadius:100, padding:'2px 10px', marginLeft:8, fontSize:12 }}>{items.length}</span>
          </div>
        </div>
        <div>
          {items.map(op => {
            const product = productById(op.productId);
            const pendingOffers = (op.offers || []).filter(o => o.status === 'pendiente');
            const acceptedOffer = (op.offers || []).find(o => o.status === 'aceptada') || (op.counterOffers || []).find(c => c.status === 'aceptada');
            const isExpanded = expanded === op.id;
            return (
              <div key={op.id} style={{ borderTop:`1px solid ${t.border}`, padding:'14px 16px' }}>
                <div style={{ display:'flex', gap:12, alignItems:'flex-start', flexWrap:'wrap' }}>
                  <div style={{ flex:'1 1 220px', minWidth:0 }}>
                    <div style={{ fontSize:14, fontWeight:800, color:t.text, marginBottom:3 }}>
                      {product?.title || '(producto eliminado)'}
                    </div>
                    <div style={{ fontSize:12, color:t.textMid, marginBottom:4 }}>
                      Vendedor: <strong style={{ color:t.text }}>{product?.sellerName || '—'}</strong> · {product?.phone || '—'}
                    </div>
                    {statusKey === 'con_oferta' && pendingOffers.length > 0 && (
                      <div style={{ fontSize:12, color:t.textMid }}>
                        💬 {pendingOffers.length} oferta(s) pendiente(s) · mejor: <strong style={{ color:'#a16207' }}>{Math.max(...pendingOffers.map(o => o.amount))}€</strong>
                      </div>
                    )}
                    {acceptedOffer && (
                      <div style={{ fontSize:12, color:t.textMid }}>
                        Comprador: <strong style={{ color:t.text }}>{op.buyer?.name || acceptedOffer.buyerName}</strong> · {op.buyer?.phone || acceptedOffer.buyerPhone} · <strong style={{ color:'#15803d' }}>{op.finalPrice}€</strong>
                      </div>
                    )}
                    {op.shipping?.trackingCode && (
                      <div style={{ fontSize:12, color:t.textMid, marginTop:2 }}>
                        📦 {op.shipping.carrier} · {op.shipping.trackingCode}
                      </div>
                    )}
                  </div>
                  <div style={{ display:'flex', gap:6, flexWrap:'wrap' }}>
                    {statusKey === 'con_oferta' && (
                      <a href={waNotifyVendor(product?.phone, product?.title, pendingOffers[0])} target="_blank" rel="noopener noreferrer" style={{ textDecoration:'none' }}>
                        <button style={{ background:'#25d366', color:'#fff', border:'none', cursor:'pointer', padding:'8px 12px', borderRadius:100, fontSize:12, fontWeight:700, fontFamily:'Outfit,sans-serif', whiteSpace:'nowrap' }}>
                          📲 Avisar al vendedor
                        </button>
                      </a>
                    )}
                    {ctaAction && (
                      <button
                        onClick={()=>handleAction(op, ctaAction)}
                        style={{ background:ctaColor, color:'#fff', border:'none', cursor:'pointer', padding:'8px 12px', borderRadius:100, fontSize:12, fontWeight:700, fontFamily:'Outfit,sans-serif', whiteSpace:'nowrap' }}
                      >
                        {ctaLabel}
                      </button>
                    )}
                    <button
                      onClick={()=>setExpanded(isExpanded ? null : op.id)}
                      style={{ background:'none', color:t.textMid, border:`1px solid ${t.border}`, cursor:'pointer', padding:'8px 12px', borderRadius:100, fontSize:12, fontWeight:700, fontFamily:'Outfit,sans-serif' }}
                    >
                      {isExpanded ? 'Cerrar' : 'Ver detalle'}
                    </button>
                  </div>
                </div>

                {isExpanded && (
                  <div style={{ marginTop:12, paddingTop:12, borderTop:`1px solid ${t.border}`, fontSize:12, color:t.textMid }}>
                    {/* Timeline */}
                    <div style={{ fontWeight:700, color:t.text, marginBottom:6 }}>Historial:</div>
                    <div style={{ marginBottom:10 }}>
                      {(op.timeline || []).slice().reverse().map((ev, i) => (
                        <div key={i} style={{ marginBottom:3 }}>
                          <span style={{ color:t.textLight }}>{formatDate(ev.time)}</span> — {ev.desc}
                        </div>
                      ))}
                    </div>
                    {/* Acciones secundarias */}
                    <div style={{ display:'flex', gap:6, flexWrap:'wrap' }}>
                      <button
                        onClick={()=>handleAction(op, 'cancel')}
                        style={{ background:'#fff', color:'#b91c1c', border:'1px solid #fecaca', cursor:'pointer', padding:'6px 12px', borderRadius:100, fontSize:11, fontWeight:700, fontFamily:'Outfit,sans-serif' }}
                      >
                        ❌ Cancelar operación
                      </button>
                    </div>
                  </div>
                )}
              </div>
            );
          })}
        </div>
      </div>
    );
  };

  return (
    <div style={{ marginBottom:24 }}>
      <h2 style={{ fontSize:18, fontWeight:800, color:t.text, marginBottom:12 }}>
        🔔 Cola de operaciones <span style={{ background:t.primary, color:'#fff', borderRadius:100, padding:'2px 10px', marginLeft:6, fontSize:13 }}>{totalOpen}</span>
      </h2>
      {renderQueue('con_oferta', byStatus.con_oferta, null, null, null)}
      {renderQueue('reservado', byStatus.reservado, '✅ Marcar pagado', 'paid', '#7c3aed')}
      {renderQueue('pagado', byStatus.pagado, '📦 Marcar enviado', 'shipped', '#1d4ed8')}
      {renderQueue('en_transito', byStatus.en_transito, '✅ Marcar entregado', 'delivered', '#15803d')}
    </div>
  );
}

function AdminChart({ t, products }) {
  const canvasRef = React.useRef();

  React.useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas) return;
    const ctx = canvas.getContext('2d');
    const W = canvas.width, H = canvas.height;
    ctx.clearRect(0, 0, W, H);

    // Build last 8 weeks buckets
    const now = Date.now();
    const WEEK = 7 * 24 * 60 * 60 * 1000;
    const buckets = Array.from({ length: 8 }, (_, i) => ({
      label: i === 0 ? 'Esta\nsemana' : `–${8 - i}s`,
      revenue: 0, count: 0,
    }));
    products.filter(p => p.status === 'vendido').forEach(p => {
      const age = Math.floor((now - p.publishedAt) / WEEK);
      const idx = 7 - Math.min(age, 7);
      if (idx >= 0) {
        buckets[idx].revenue += (p.price || 0) * commissionRate(p.price || 0);
        buckets[idx].count++;
      }
    });

    const maxRev = Math.max(...buckets.map(b => b.revenue), 1);
    const PAD = { top: 20, right: 20, bottom: 50, left: 50 };
    const chartW = W - PAD.left - PAD.right;
    const chartH = H - PAD.top - PAD.bottom;
    const barW = (chartW / buckets.length) * 0.55;
    const gap = chartW / buckets.length;

    // Y axis labels
    ctx.fillStyle = t.textLight;
    ctx.font = '11px Outfit, sans-serif';
    ctx.textAlign = 'right';
    for (let i = 0; i <= 4; i++) {
      const y = PAD.top + chartH - (i / 4) * chartH;
      ctx.fillText(Math.round((i / 4) * maxRev) + '€', PAD.left - 6, y + 4);
      ctx.strokeStyle = t.border;
      ctx.lineWidth = 1;
      ctx.setLineDash([4, 4]);
      ctx.beginPath();
      ctx.moveTo(PAD.left, y);
      ctx.lineTo(W - PAD.right, y);
      ctx.stroke();
      ctx.setLineDash([]);
    }

    // Bars
    buckets.forEach((b, i) => {
      const x = PAD.left + i * gap + (gap - barW) / 2;
      const barH = (b.revenue / maxRev) * chartH;
      const y = PAD.top + chartH - barH;

      // Bar
      ctx.fillStyle = b.count > 0 ? t.primary : t.border;
      ctx.beginPath();
      ctx.roundRect(x, y, barW, barH, [6, 6, 0, 0]);
      ctx.fill();

      // Value label
      if (b.revenue > 0) {
        ctx.fillStyle = t.primary;
        ctx.font = 'bold 11px Outfit, sans-serif';
        ctx.textAlign = 'center';
        ctx.fillText(Math.round(b.revenue) + '€', x + barW / 2, y - 5);
      }

      // X label
      ctx.fillStyle = t.textLight;
      ctx.font = '11px Outfit, sans-serif';
      ctx.textAlign = 'center';
      const lines = b.label.split('\n');
      lines.forEach((line, li) => {
        ctx.fillText(line, x + barW / 2, PAD.top + chartH + 16 + li * 14);
      });
    });
  }, [products, t]);

  return (
    <div style={{ background: t.card, border: `1px solid ${t.border}`, borderRadius: 16, padding: 24 }}>
      <div style={{ fontSize: 15, fontWeight: 700, color: t.text, marginBottom: 16 }}>Comisiones por semana (últimas 8)</div>
      <canvas ref={canvasRef} width={700} height={200} style={{ width: '100%', height: 'auto' }} />
    </div>
  );
}

function Admin({ t, setPage }) {
  const products = useProducts();
  const [tab, setTab] = React.useState('operaciones'); // operaciones | comisiones | productos | tabla
  const [filterStatus, setFilterStatus] = React.useState('todos');
  const [selected, setSelected] = React.useState(new Set());
  const [showChart, setShowChart] = React.useState(false);
  const [searchAdmin, setSearchAdmin] = React.useState('');

  const orders = products.map(p => ({
    id: 'ZV-' + String(p.id).slice(-6),
    productId: p.id,
    seller: p.seller || abbreviateName(p.sellerName) || '—',
    phone: p.phone || '—',
    object: p.title,
    price: Number(p.price) || 0,
    status: p.status || 'nuevo',
    city: p.location || p.city || '—',
    date: timeSince(p.publishedAt),
    views: p.views || 0,
  }));

  const filtered = orders.filter(o => {
    const matchStatus = filterStatus === 'todos' || o.status === filterStatus;
    const matchSearch = !searchAdmin || o.object.toLowerCase().includes(searchAdmin.toLowerCase()) || o.seller.toLowerCase().includes(searchAdmin.toLowerCase());
    return matchStatus && matchSearch;
  });

  const totalRevenue = orders.filter(o => o.status === 'vendido').reduce((s, o) => s + o.price * commissionRate(o.price), 0);
  const avgPrice = orders.length ? Math.round(orders.reduce((s, o) => s + o.price, 0) / orders.length) : 0;

  const advanceStatus = (pid) => {
    const flow = ['nuevo','valorado','publicado','oferta','enviado','vendido'];
    const product = products.find(p => p.id === pid);
    if (!product) return;
    const idx = flow.indexOf(product.status || 'nuevo');
    const nextStatus = flow[Math.min(idx + 1, flow.length - 1)];
    updateProduct(pid, { status: nextStatus });
    sendBrowserNotification('Zeus Ventas', `"${product.title}" avanzó a "${statusConfig[nextStatus]?.label}"`);
  };

  const removeOrder = (pid) => {
    if (confirm('¿Eliminar este anuncio permanentemente?')) deleteProduct(pid);
  };

  const bulkDelete = () => {
    if (!selected.size) return;
    if (confirm(`¿Eliminar ${selected.size} anuncio(s)?`)) {
      selected.forEach(pid => deleteProduct(pid));
      setSelected(new Set());
    }
  };

  const bulkMarkSold = () => {
    selected.forEach(pid => updateProduct(pid, { status: 'vendido' }));
    setSelected(new Set());
  };

  const toggleSelect = (pid) => {
    const next = new Set(selected);
    next.has(pid) ? next.delete(pid) : next.add(pid);
    setSelected(next);
  };

  const selectAll = () => {
    if (selected.size === filtered.length) setSelected(new Set());
    else setSelected(new Set(filtered.map(o => o.productId)));
  };

  const handleExportCSV = () => exportCSV(products);

  const notifPerm = 'Notification' in window ? Notification.permission : 'unsupported';

  return (
    <div style={{ background: t.bgAlt, minHeight: '100vh' }}>
      {/* Header */}
      <div className="zv-admin-header" style={{ background: t.primary, padding: '24px 32px', display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: 16 }}>
        <div>
          <div style={{ fontSize: 12, fontWeight: 700, color: 'rgba(255,255,255,0.5)', letterSpacing: 1 }}>ADMINISTRACIÓN</div>
          <div style={{ fontSize: 26, fontWeight: 900, color: '#fff' }}>Zeus Ventas</div>
        </div>
        <div className="zv-admin-stats" style={{ display: 'flex', gap: 20, flexWrap: 'wrap' }}>
          {[
            ['Total', orders.length],
            ['En curso', orders.filter(o => o.status !== 'vendido').length],
            ['Vendidos', orders.filter(o => o.status === 'vendido').length],
            [Math.round(totalRevenue) + '€', 'Comisiones'],
            [avgPrice + '€', 'Precio medio'],
          ].map(([v, l]) => (
            <div key={l} style={{ textAlign: 'center' }}>
              <div style={{ fontSize: 28, fontWeight: 900, color: '#fff' }}>{v}</div>
              <div style={{ fontSize: 13, color: 'rgba(255,255,255,0.55)' }}>{l}</div>
            </div>
          ))}
        </div>
      </div>

      {/* Tabs de navegación */}
      <div style={{ background: t.card, borderBottom: `1px solid ${t.border}`, padding: '0 32px', display:'flex', gap:4, overflowX:'auto' }}>
        {[
          { id:'operaciones', label:'🔔 Operaciones' },
          { id:'comisiones',  label:'💰 Comisiones' },
          { id:'productos',   label:'✏️ Productos' },
          { id:'tabla',       label:'📋 Tabla completa' },
        ].map(tb => (
          <button key={tb.id} onClick={() => setTab(tb.id)} style={{
            padding:'14px 20px', border:'none', background:'transparent', cursor:'pointer',
            fontFamily:'Outfit,sans-serif', fontSize:14, fontWeight: tab===tb.id ? 800 : 600,
            color: tab===tb.id ? t.primary : t.textMid,
            borderBottom: tab===tb.id ? `3px solid ${t.primary}` : '3px solid transparent',
            whiteSpace:'nowrap', transition:'all 0.2s',
          }}>{tb.label}</button>
        ))}
      </div>

      <div style={{ padding: '28px 32px', maxWidth: 1280, margin: '0 auto' }}>
        {/* Toolbar */}
        <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap', marginBottom: 20, alignItems: 'center' }}>
          <input value={searchAdmin} onChange={e => setSearchAdmin(e.target.value)} placeholder="Buscar anuncio o vendedor…" style={{ padding: '10px 18px', borderRadius: 100, border: `2px solid ${t.border}`, background: t.card, color: t.text, fontFamily: 'Outfit,sans-serif', fontSize: 15, outline: 'none', flex: '1 1 200px', minWidth: 0 }} />
          <button onClick={handleExportCSV} style={{ background: t.card, border: `2px solid ${t.border}`, cursor: 'pointer', padding: '10px 18px', borderRadius: 100, fontSize: 14, fontWeight: 700, color: t.text, fontFamily: 'Outfit,sans-serif', whiteSpace: 'nowrap' }}>⬇ CSV</button>
          <button onClick={() => setShowChart(v => !v)} style={{ background: showChart ? t.primary : t.card, color: showChart ? '#fff' : t.text, border: `2px solid ${showChart ? t.primary : t.border}`, cursor: 'pointer', padding: '10px 18px', borderRadius: 100, fontSize: 14, fontWeight: 700, fontFamily: 'Outfit,sans-serif', whiteSpace: 'nowrap' }}>📊 Gráfico</button>
          {notifPerm !== 'granted' && notifPerm !== 'unsupported' && (
            <button onClick={requestNotificationPermission} style={{ background: '#f59e0b', color: '#fff', border: 'none', cursor: 'pointer', padding: '10px 18px', borderRadius: 100, fontSize: 14, fontWeight: 700, fontFamily: 'Outfit,sans-serif', whiteSpace: 'nowrap' }}>🔔 Activar alertas</button>
          )}
        </div>

        {/* Chart */}
        {showChart && <div style={{ marginBottom: 20 }}><AdminChart t={t} products={products} /></div>}

        {tab === 'operaciones' && <AdminOperationsQueue t={t} />}
        {tab === 'comisiones'  && <AdminComisiones t={t} products={products} />}
        {tab === 'productos'   && <AdminProductEditor t={t} products={products} />}
        {tab === 'tabla' && (
          <div>

        {/* Bulk actions */}
        {selected.size > 0 && (
          <div style={{ background: t.accentLight, border: `2px solid ${t.accent}`, borderRadius: 12, padding: '12px 20px', marginBottom: 16, display: 'flex', gap: 12, alignItems: 'center', flexWrap: 'wrap' }}>
            <span style={{ fontSize: 15, fontWeight: 700, color: t.accent }}>{selected.size} seleccionado(s)</span>
            <button onClick={bulkMarkSold} style={{ background: '#16a34a', color: '#fff', border: 'none', cursor: 'pointer', padding: '8px 16px', borderRadius: 100, fontSize: 14, fontWeight: 700, fontFamily: 'Outfit,sans-serif' }}>✓ Marcar vendido</button>
            <button onClick={bulkDelete} style={{ background: '#dc2626', color: '#fff', border: 'none', cursor: 'pointer', padding: '8px 16px', borderRadius: 100, fontSize: 14, fontWeight: 700, fontFamily: 'Outfit,sans-serif' }}>🗑 Eliminar</button>
            <button onClick={() => setSelected(new Set())} style={{ background: 'none', border: `2px solid ${t.border}`, cursor: 'pointer', padding: '8px 16px', borderRadius: 100, fontSize: 14, color: t.textMid, fontFamily: 'Outfit,sans-serif' }}>Cancelar</button>
          </div>
        )}

        {/* Status filters */}
        <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginBottom: 16 }}>
          {['todos', ...Object.keys(statusConfig)].map(s => (
            <button key={s} onClick={() => setFilterStatus(s)} style={{ padding: '8px 16px', borderRadius: 100, fontSize: 14, fontWeight: 600, cursor: 'pointer', fontFamily: 'Outfit,sans-serif', border: `2px solid ${filterStatus === s ? t.primary : t.border}`, background: filterStatus === s ? t.primary : t.card, color: filterStatus === s ? '#fff' : t.textMid }}>
              {s === 'todos' ? `Todos (${orders.length})` : `${statusConfig[s].label} (${orders.filter(o => o.status === s).length})`}
            </button>
          ))}
        </div>

        {orders.length === 0 ? (
          <EmptyState t={t} icon="📭" title="Aún no hay anuncios" subtitle="Cuando publiques un anuncio, aparecerá aquí." actionLabel="Crear primer anuncio" onAction={() => setPage('publish')} />
        ) : (
          <div className="zv-table-wrap" style={{ background: t.card, border: `1px solid ${t.border}`, borderRadius: 16, overflow: 'hidden' }}>
            <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 15 }}>
              <thead>
                <tr style={{ background: t.bgAlt }}>
                  <th style={{ padding: '12px 16px', width: 40 }}>
                    <input type="checkbox" checked={selected.size === filtered.length && filtered.length > 0} onChange={selectAll} style={{ width: 16, height: 16, cursor: 'pointer' }} />
                  </th>
                  {['ID','Vendedor','Objeto','Precio','Visitas','Ciudad','Fecha','Estado','',''].map((h, i) => (
                    <th key={i} style={{ padding: '12px 14px', textAlign: 'left', fontSize: 12, fontWeight: 700, color: t.textLight, letterSpacing: 0.5 }}>{h}</th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {filtered.map(o => {
                  const sc = statusConfig[o.status];
                  return (
                    <tr key={o.id} style={{ borderTop: `1px solid ${t.border}`, background: selected.has(o.productId) ? t.accentLight : 'transparent' }}>
                      <td style={{ padding: '12px 16px' }}>
                        <input type="checkbox" checked={selected.has(o.productId)} onChange={() => toggleSelect(o.productId)} style={{ width: 16, height: 16, cursor: 'pointer' }} />
                      </td>
                      <td style={{ padding: '12px 14px', fontWeight: 700, color: t.text, fontFamily: 'monospace', fontSize: 13 }}>{o.id}</td>
                      <td style={{ padding: '12px 14px' }}>
                        <div style={{ fontWeight: 700, color: t.text, fontSize: 15 }}>{o.seller}</div>
                        <a href={`https://wa.me/${o.phone.replace(/\D/g,'')}`} target="_blank" rel="noopener noreferrer" style={{ fontSize: 12, color: '#25d366', textDecoration: 'none' }}>{o.phone}</a>
                      </td>
                      <td style={{ padding: '12px 14px', color: t.text, maxWidth: 180 }}>{o.object}</td>
                      <td style={{ padding: '12px 14px', fontWeight: 900, color: t.primary, fontSize: 17 }}>{o.price}€</td>
                      <td style={{ padding: '12px 14px', color: t.textLight, fontSize: 14 }}>{o.views}</td>
                      <td style={{ padding: '12px 14px', color: t.textMid, fontSize: 14 }}>{o.city}</td>
                      <td style={{ padding: '12px 14px', color: t.textLight, fontSize: 13 }}>{o.date}</td>
                      <td style={{ padding: '12px 14px' }}><StatusBadge status={o.status} /></td>
                      <td style={{ padding: '12px 14px' }}>
                        {o.status !== 'vendido' ? (
                          <button onClick={() => advanceStatus(o.productId)} style={{ background: t.primary, color: '#fff', border: 'none', cursor: 'pointer', padding: '6px 14px', borderRadius: 100, fontSize: 13, fontWeight: 700, fontFamily: 'Outfit,sans-serif', whiteSpace: 'nowrap' }}>Avanzar →</button>
                        ) : <span style={{ color: t.textLight, fontSize: 13 }}>✓</span>}
                      </td>
                      <td style={{ padding: '12px 14px' }}>
                        <button onClick={() => removeOrder(o.productId)} style={{ background: 'none', border: 'none', cursor: 'pointer', color: '#c00', fontSize: 18 }} title="Eliminar">🗑️</button>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
            <div style={{ padding: '10px 20px', fontSize: 13, color: t.textLight, borderTop: `1px solid ${t.border}` }}>
              {filtered.length} anuncios
            </div>
          </div>
        )}
          </div>
        )}
      </div>
    </div>
  );
}


/* ══════════════════════════════════════════════════════════════
   ADMIN DASHBOARD — KPIs + Comisiones + Editor de productos
   ══════════════════════════════════════════════════════════════ */

function AdminKPICard({ label, value, sub, color, icon }) {
  return (
    <div style={{ background:'#fff', borderRadius:16, padding:'20px 22px', flex:'1 1 160px', minWidth:140, boxShadow:'0 1px 4px rgba(0,0,0,0.08)', borderTop:`4px solid ${color}` }}>
      <div style={{ fontSize:28, marginBottom:6 }}>{icon}</div>
      <div style={{ fontSize:26, fontWeight:900, color:'#1a1a1a', lineHeight:1 }}>{value}</div>
      <div style={{ fontSize:13, fontWeight:700, color:'#666', marginTop:4 }}>{label}</div>
      {sub && <div style={{ fontSize:12, color:'#999', marginTop:2 }}>{sub}</div>}
    </div>
  );
}

function AdminComisiones({ t, products }) {
  const vendidos = products.filter(p => p.status === 'vendido');
  const totalBruto = vendidos.reduce((s, p) => s + (Number(p.price)||0), 0);
  const totalComision = vendidos.reduce((s, p) => s + (Number(p.price)||0) * commissionRate(Number(p.price)||0), 0);
  const totalVendedor = totalBruto - totalComision;

  // Agrupar por vendedor
  const byVendor = {};
  vendidos.forEach(p => {
    const key = (p.phone || p.sellerName || 'Desconocido').replace(/\s/g,'');
    if (!byVendor[key]) byVendor[key] = { name: p.sellerName || p.seller || 'Vendedor', phone: p.phone || '—', items: [], total: 0, comision: 0 };
    const com = (Number(p.price)||0) * commissionRate(Number(p.price)||0);
    byVendor[key].items.push(p);
    byVendor[key].total += Number(p.price)||0;
    byVendor[key].comision += com;
  });
  const vendors = Object.values(byVendor).sort((a,b) => b.total - a.total);

  return (
    <div>
      {/* Resumen */}
      <div style={{ display:'flex', gap:12, flexWrap:'wrap', marginBottom:24 }}>
        <AdminKPICard icon="💰" label="Facturación bruta" value={totalBruto.toFixed(0)+'€'} color="#3d5740" />
        <AdminKPICard icon="🏦" label="Comisiones Zeus" value={totalComision.toFixed(0)+'€'} color="#7c3aed" sub={`${((totalComision/totalBruto)*100||0).toFixed(1)}% del total`} />
        <AdminKPICard icon="🤝" label="Pago a vendedores" value={totalVendedor.toFixed(0)+'€'} color="#0ea5e9" />
        <AdminKPICard icon="📦" label="Objetos vendidos" value={vendidos.length} color="#f59e0b" />
      </div>

      {/* Tabla por vendedor */}
      {vendors.length === 0 ? (
        <div style={{ textAlign:'center', padding:40, color:'#999', fontSize:15 }}>Aún no hay ventas completadas</div>
      ) : (
        <div style={{ background:'#fff', borderRadius:14, overflow:'hidden', border:'1px solid #e5e7eb' }}>
          <div style={{ padding:'14px 20px', background:'#f9fafb', borderBottom:'1px solid #e5e7eb', fontSize:12, fontWeight:700, color:'#6b7280', display:'grid', gridTemplateColumns:'1fr 80px 80px 80px 80px', gap:8 }}>
            <span>VENDEDOR</span><span style={{textAlign:'right'}}>VENTAS</span><span style={{textAlign:'right'}}>BRUTO</span><span style={{textAlign:'right'}}>COMISIÓN</span><span style={{textAlign:'right'}}>NETO</span>
          </div>
          {vendors.map((v, i) => (
            <div key={i} style={{ padding:'14px 20px', borderBottom:'1px solid #f3f4f6', display:'grid', gridTemplateColumns:'1fr 80px 80px 80px 80px', gap:8, alignItems:'center' }}>
              <div>
                <div style={{ fontWeight:700, color:'#111', fontSize:15 }}>{v.name}</div>
                <a href={`https://wa.me/${v.phone.replace(/\D/g,'')}`} target="_blank" rel="noopener noreferrer" style={{ fontSize:12, color:'#25d366', textDecoration:'none' }}>📱 {v.phone}</a>
              </div>
              <div style={{ textAlign:'right', fontWeight:700, color:'#374151' }}>{v.items.length}</div>
              <div style={{ textAlign:'right', fontWeight:700, color:'#374151' }}>{v.total.toFixed(0)}€</div>
              <div style={{ textAlign:'right', fontWeight:900, color:'#7c3aed' }}>{v.comision.toFixed(0)}€</div>
              <div style={{ textAlign:'right', fontWeight:700, color:'#3d5740' }}>{(v.total-v.comision).toFixed(0)}€</div>
            </div>
          ))}
          <div style={{ padding:'12px 20px', background:'#f9fafb', borderTop:'2px solid #e5e7eb', display:'grid', gridTemplateColumns:'1fr 80px 80px 80px 80px', gap:8, fontSize:14, fontWeight:900 }}>
            <span style={{ color:'#374151' }}>TOTAL</span>
            <span style={{ textAlign:'right', color:'#374151' }}>{vendidos.length}</span>
            <span style={{ textAlign:'right', color:'#374151' }}>{totalBruto.toFixed(0)}€</span>
            <span style={{ textAlign:'right', color:'#7c3aed' }}>{totalComision.toFixed(0)}€</span>
            <span style={{ textAlign:'right', color:'#3d5740' }}>{totalVendedor.toFixed(0)}€</span>
          </div>
        </div>
      )}
    </div>
  );
}

function AdminProductEditor({ t, products }) {
  const [editingId, setEditingId]     = React.useState(null);
  const [editForm,  setEditForm]      = React.useState({});
  const [search,    setSearch]        = React.useState('');

  const filtered = products.filter(p =>
    !search || p.title?.toLowerCase().includes(search.toLowerCase()) || (p.sellerName||'').toLowerCase().includes(search.toLowerCase())
  );

  const startEdit = (p) => {
    setEditingId(p.id);
    setEditForm({ title: p.title||'', price: p.price||'', status: p.status||'nuevo', city: p.city||p.location||'', desc: p.desc||p.description||'' });
  };

  const saveEdit = () => {
    updateProduct(editingId, {
      title: editForm.title,
      price: Number(editForm.price)||0,
      status: editForm.status,
      city: editForm.city,
      location: editForm.city,
      desc: editForm.desc,
    });
    setEditingId(null);
  };

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

  return (
    <div>
      <input value={search} onChange={e => setSearch(e.target.value)} placeholder="Buscar producto o vendedor…"
        style={{ width:'100%', padding:'12px 18px', borderRadius:100, border:'2px solid #e5e7eb', fontSize:15, marginBottom:16, boxSizing:'border-box', fontFamily:'Outfit,sans-serif' }} />

      <div style={{ display:'flex', flexDirection:'column', gap:10 }}>
        {filtered.map(p => (
          <div key={p.id} style={{ background:'#fff', borderRadius:14, border:'1px solid #e5e7eb', overflow:'hidden' }}>
            {editingId === p.id ? (
              /* MODO EDICIÓN */
              <div style={{ padding:20 }}>
                <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:12, marginBottom:12 }}>
                  <div>
                    <label style={{ fontSize:12, fontWeight:700, color:'#6b7280', display:'block', marginBottom:4 }}>TÍTULO</label>
                    <input value={editForm.title} onChange={e => setEditForm({...editForm, title:e.target.value})}
                      style={{ width:'100%', padding:'10px 14px', borderRadius:10, border:'2px solid #e5e7eb', fontSize:14, boxSizing:'border-box', fontFamily:'Outfit,sans-serif' }} />
                  </div>
                  <div>
                    <label style={{ fontSize:12, fontWeight:700, color:'#6b7280', display:'block', marginBottom:4 }}>PRECIO (€)</label>
                    <input type="number" value={editForm.price} onChange={e => setEditForm({...editForm, price:e.target.value})}
                      style={{ width:'100%', padding:'10px 14px', borderRadius:10, border:'2px solid #e5e7eb', fontSize:14, boxSizing:'border-box', fontFamily:'Outfit,sans-serif' }} />
                  </div>
                  <div>
                    <label style={{ fontSize:12, fontWeight:700, color:'#6b7280', display:'block', marginBottom:4 }}>ESTADO</label>
                    <select value={editForm.status} onChange={e => setEditForm({...editForm, status:e.target.value})}
                      style={{ width:'100%', padding:'10px 14px', borderRadius:10, border:'2px solid #e5e7eb', fontSize:14, boxSizing:'border-box', fontFamily:'Outfit,sans-serif' }}>
                      {flow.map(s => <option key={s} value={s}>{statusConfig[s]?.label || s}</option>)}
                    </select>
                  </div>
                  <div>
                    <label style={{ fontSize:12, fontWeight:700, color:'#6b7280', display:'block', marginBottom:4 }}>CIUDAD</label>
                    <input value={editForm.city} onChange={e => setEditForm({...editForm, city:e.target.value})}
                      style={{ width:'100%', padding:'10px 14px', borderRadius:10, border:'2px solid #e5e7eb', fontSize:14, boxSizing:'border-box', fontFamily:'Outfit,sans-serif' }} />
                  </div>
                </div>
                <label style={{ fontSize:12, fontWeight:700, color:'#6b7280', display:'block', marginBottom:4 }}>DESCRIPCIÓN</label>
                <textarea value={editForm.desc} onChange={e => setEditForm({...editForm, desc:e.target.value})} rows={3}
                  style={{ width:'100%', padding:'10px 14px', borderRadius:10, border:'2px solid #e5e7eb', fontSize:14, boxSizing:'border-box', fontFamily:'Outfit,sans-serif', resize:'vertical', marginBottom:12 }} />
                <div style={{ display:'flex', gap:10 }}>
                  <button onClick={saveEdit} style={{ background:'#3d5740', color:'#fff', border:'none', cursor:'pointer', padding:'10px 22px', borderRadius:100, fontSize:14, fontWeight:800, fontFamily:'Outfit,sans-serif' }}>✅ Guardar</button>
                  <button onClick={() => setEditingId(null)} style={{ background:'none', border:'2px solid #e5e7eb', cursor:'pointer', padding:'10px 22px', borderRadius:100, fontSize:14, color:'#6b7280', fontFamily:'Outfit,sans-serif' }}>Cancelar</button>
                </div>
              </div>
            ) : (
              /* MODO VISTA */
              <div style={{ padding:'14px 18px', display:'flex', alignItems:'center', gap:14, flexWrap:'wrap' }}>
                {p.photo && <img src={p.photo} alt="" style={{ width:56, height:56, borderRadius:10, objectFit:'cover', flexShrink:0 }} />}
                <div style={{ flex:1, minWidth:0 }}>
                  <div style={{ fontWeight:800, fontSize:15, color:'#111', marginBottom:2 }}>{p.title}</div>
                  <div style={{ fontSize:13, color:'#6b7280' }}>{p.sellerName || p.seller} · {p.city || p.location || '—'}</div>
                </div>
                <div style={{ fontWeight:900, fontSize:20, color:'#3d5740', flexShrink:0 }}>{p.price}€</div>
                <StatusBadge status={p.status} />
                <div style={{ display:'flex', gap:8, flexShrink:0 }}>
                  <button onClick={() => startEdit(p)}
                    style={{ background:'#3d5740', color:'#fff', border:'none', cursor:'pointer', padding:'8px 16px', borderRadius:100, fontSize:13, fontWeight:700, fontFamily:'Outfit,sans-serif' }}>
                    ✏️ Editar
                  </button>
                  <button onClick={() => { if(confirm('¿Eliminar?')) deleteProduct(p.id); }}
                    style={{ background:'none', border:'1px solid #fecaca', color:'#b91c1c', cursor:'pointer', padding:'8px 16px', borderRadius:100, fontSize:13, fontWeight:700, fontFamily:'Outfit,sans-serif' }}>
                    🗑
                  </button>
                </div>
              </div>
            )}
          </div>
        ))}
        {filtered.length === 0 && (
          <div style={{ textAlign:'center', padding:40, color:'#999', fontSize:15 }}>No hay productos</div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { Admin });
