import React, { useState, useMemo, useRef } from 'react';
import { MOCK_PROJECTS, MOCK_TEAM } from '../../services/mockData';
import { useProject } from '../../context/ProjectContext';

// ── Mock Data ─────────────────────────────────────────────────────────────────

const MOCK_SUPPLIERS = [
  { id:'sup1', name:'Aceros del Norte S.A.',   contact:'Jorge Pérez',   email:'jperez@acerosnorte.com',    phone:'+57 310 555 0101', category:'Materiales', rating:4.2, deliveryCompliance:88, ncrs:1, city:'Medellín',    projectId:'p4' },
  { id:'sup2', name:'CementoMax Industrial',   contact:'Laura Gómez',   email:'lgomez@cementomax.com',     phone:'+57 314 555 0202', category:'Materiales', rating:4.7, deliveryCompliance:95, ncrs:0, city:'Bogotá',      projectId:'p4' },
  { id:'sup3', name:'ElectroSur Ltda.',        contact:'Marco Ríos',    email:'mrios@electrosur.com',      phone:'+57 318 555 0303', category:'Eléctricos', rating:3.8, deliveryCompliance:72, ncrs:3, city:'Cali',        projectId:'p4' },
  { id:'sup4', name:'Andamios & Equipos S.A.', contact:'Patricia Vera', email:'pvera@andamiosequipos.com', phone:'+57 315 555 0404', category:'Equipos',    rating:4.5, deliveryCompliance:91, ncrs:0, city:'Bogotá',      projectId:'p4' },
  { id:'sup5', name:'Ferretería La Torre',     contact:'Andrés López',  email:'alopez@latorre.com',        phone:'+57 311 555 0505', category:'Materiales', rating:4.0, deliveryCompliance:83, ncrs:2, city:'Barranquilla', projectId:'p4' },
];

// Responsable de compras por proyecto (por defecto: rol FINANCIERO o JEFE_AREA)
const DEFAULT_PURCHASER = { id:'u7', firstName:'Carmen', lastName:'Fuentes', avatar:'CF', color:'#8B5CF6', role:'FINANCIERO' };

const MOCK_RFQS = [
  { id:'rfq1', code:'RFQ-2026-001', projectId:'p4', projectCode:'PRY-2026-004',
    taskId:'t3', taskWbs:'2.1', taskTitle:'Desarrollo módulo inventarios', taskIsCritical:true,
    material:'Varilla corrugada 3/8"', unit:'und', qty:500, specs:'Norma NTC 2289, límite elástico mínimo 420 MPa',
    requiredDate:'2026-07-20', rfqDeadline:'2026-07-05',
    assignedTo:'u7', status:'CLOSED', invitedSuppliers:['sup1','sup5'],
    createdBy:'u1', createdAt:'2026-06-20T09:00:00' },
  { id:'rfq2', code:'RFQ-2026-002', projectId:'p4', projectCode:'PRY-2026-004',
    taskId:'t4', taskWbs:'2.2', taskTitle:'Integración con WMS externo', taskIsCritical:false,
    material:'Cemento gris Tipo I x saco 50kg', unit:'saco', qty:200, specs:'Norma NTC 121, resistencia 28MPa',
    requiredDate:'2026-07-25', rfqDeadline:'2026-07-08',
    assignedTo:'u7', status:'OPEN', invitedSuppliers:['sup2','sup5'],
    createdBy:'u1', createdAt:'2026-06-22T10:00:00' },
  { id:'rfq3', code:'RFQ-2026-003', projectId:'p4', projectCode:'PRY-2026-004',
    taskId:'t6', taskWbs:'2.4', taskTitle:'Migración datos históricos', taskIsCritical:false,
    material:'Andamios tubulares — renta 60 días', unit:'juego', qty:3, specs:'Cap. carga ≥ 250 kg/nivel, altura máx 8m',
    requiredDate:'2026-08-01', rfqDeadline:'2026-07-10',
    assignedTo:'u7', status:'OPEN', invitedSuppliers:['sup4'],
    createdBy:'u2', createdAt:'2026-06-23T11:00:00' },
  { id:'rfq4', code:'RFQ-2026-004', projectId:'p4', projectCode:'PRY-2026-004',
    taskId:'ar03', taskWbs:'1.3', taskTitle:'API auth JWT + RBAC', taskIsCritical:true,
    material:'Licencias software servidor — 12 meses', unit:'licencia', qty:5, specs:'Certificado ISO 27001, soporte 24/7',
    requiredDate:'2026-07-01', rfqDeadline:'2026-06-28',
    assignedTo:'u7', status:'ADJUDICATED', invitedSuppliers:['sup3'],
    createdBy:'u1', createdAt:'2026-06-15T08:00:00' },
];

const MOCK_QUOTES = [
  { id:'q1', rfqId:'rfq1', supplierId:'sup1', unitPrice:42000,  totalPrice:21000000, leadTimeDays:12, validUntil:'2026-07-20', paymentTerms:'30 días crédito',    technicalNote:'Certificado de calidad incluido. Entrega en obra.',      status:'RECEIVED', aiScore:null },
  { id:'q2', rfqId:'rfq1', supplierId:'sup5', unitPrice:39500,  totalPrice:19750000, leadTimeDays:18, validUntil:'2026-07-18', paymentTerms:'Pago anticipado 50%', technicalNote:'Sin certificado. Entrega en bodega.',                   status:'RECEIVED', aiScore:null },
  { id:'q3', rfqId:'rfq2', supplierId:'sup2', unitPrice:28000,  totalPrice:5600000,  leadTimeDays:3,  validUntil:'2026-07-25', paymentTerms:'15 días crédito',     technicalNote:'Norma certificada. Entrega inmediata Bogotá.',          status:'RECEIVED', aiScore:null },
  { id:'q4', rfqId:'rfq2', supplierId:'sup5', unitPrice:26500,  totalPrice:5300000,  leadTimeDays:7,  validUntil:'2026-07-22', paymentTerms:'Pago anticipado',     technicalNote:'Disponible en Medellín. Flete adicional.',             status:'RECEIVED', aiScore:null },
  { id:'q5', rfqId:'rfq4', supplierId:'sup3', unitPrice:850000, totalPrice:4250000,  leadTimeDays:5,  validUntil:'2026-07-01', paymentTerms:'Pago anticipado',     technicalNote:'Activación remota en 24h.',                           status:'SELECTED', aiScore:82 },
];

const MOCK_POS = [
  { id:'po1', code:'PO-2026-001', rfqId:'rfq4', quoteId:'q5', projectId:'p4', projectCode:'PRY-2026-004',
    supplierId:'sup3', material:'Licencias software servidor', qty:5, unitPrice:850000, total:4250000,
    status:'SENT', approvedBy:['u1','u7'], meetingRef:'J-2026-021',
    createdAt:'2026-06-16T10:00:00', expectedDelivery:'2026-06-21T00:00:00',
    notes:'Activación remota confirmada.', assignedTo:'u7' },
  { id:'po2', code:'PO-2026-002', rfqId:'rfq1', quoteId:'q1', projectId:'p4', projectCode:'PRY-2026-004',
    supplierId:'sup1', material:'Varilla corrugada 3/8" × 500 und', qty:500, unitPrice:42000, total:21000000,
    status:'DRAFT', approvedBy:[], meetingRef:null,
    createdAt:'2026-06-24T09:00:00', expectedDelivery:'2026-07-20T00:00:00',
    notes:'Pendiente aprobación junta J-2026-025.', assignedTo:'u7' },
];

const MOCK_MEETINGS = [
  { id:'m1', code:'J-2026-021', date:'2026-06-09T10:00:00', channel:'Zoom', duration:25,
    attendees:['u1','u2','u7'], quorum:true, projectId:'p4',
    items:[{ rfqId:'rfq4', poCode:'PO-2026-001', decision:'APROBADA', votes:{favor:3,contra:0,abstencion:0}, notes:'Único proveedor. Precio dentro de presupuesto.' }],
    objections:[], nextMeeting:'2026-06-16T10:00:00', minutesGenerated:true },
  { id:'m2', code:'J-2026-022', date:'2026-06-16T10:00:00', channel:'Zoom', duration:30,
    attendees:['u1','u4','u7'], quorum:true, projectId:'p4',
    items:[{ rfqId:'rfq3', poCode:null, decision:'RECHAZADA', votes:{favor:1,contra:2,abstencion:0}, notes:'Solicitar segunda cotización. Precio muy alto.' }],
    objections:['Jefe Área (u4): El precio de andamios excede el presupuesto en un 15%. Solicito nueva RFQ con más proveedores.'],
    nextMeeting:'2026-06-23T10:00:00', minutesGenerated:true },
  { id:'m3', code:'J-2026-023', date:'2026-06-23T10:00:00', channel:'Zoom', duration:20,
    attendees:['u1','u2','u7'], quorum:true, projectId:'p4',
    items:[], objections:[],
    nextMeeting:'2026-06-30T10:00:00', minutesGenerated:false },
];

// Tareas de compras generadas automáticamente por cada RFQ
const PROCUREMENT_TASKS = [
  { rfqCode:'RFQ-2026-001', assignedTo:'u7', status:'COMPLETADA', subtasks:['Enviar RFQ a proveedores','Recibir cotizaciones','Evaluar con IA','Presentar en junta','Emitir PO'] },
  { rfqCode:'RFQ-2026-002', assignedTo:'u7', status:'EN_PROCESO',  subtasks:['Enviar RFQ a proveedores','Recibir cotizaciones','Evaluar con IA','Presentar en junta','Emitir PO'] },
  { rfqCode:'RFQ-2026-003', assignedTo:'u7', status:'EN_PROCESO',  subtasks:['Enviar RFQ a proveedores','Recibir cotizaciones','Evaluar con IA','Presentar en junta','Emitir PO'] },
];

// ── AI Evaluator ──────────────────────────────────────────────────────────────
function evaluateQuotes(quotes, rfq) {
  if (!quotes.length) return [];
  const reqDays  = Math.max(1, Math.ceil((new Date(rfq.requiredDate) - new Date()) / 86400000));
  const minPrice = Math.min(...quotes.map(q => q.unitPrice));
  const minLead  = Math.min(...quotes.map(q => q.leadTimeDays));
  const supMap   = Object.fromEntries(MOCK_SUPPLIERS.map(s => [s.id, s]));
  const wtPrice  = rfq.taskIsCritical ? 0.25 : 0.40;
  const wtLead   = rfq.taskIsCritical ? 0.45 : 0.25;

  return quotes.map(q => {
    const sup          = supMap[q.supplierId] || {};
    const priceScore   = Math.round((minPrice / q.unitPrice) * 100);
    const leadOk       = q.leadTimeDays <= (reqDays - 2);
    const leadScore    = leadOk ? Math.round(100 - ((q.leadTimeDays - minLead) / Math.max(minLead,1)) * 30) : Math.max(0, 40 - (q.leadTimeDays - reqDays) * 5);
    const historyScore = Math.round(((sup.rating||3)/5)*60 + ((sup.deliveryCompliance||70)/100)*40);
    const payScore     = q.paymentTerms?.includes('crédito') ? 100 : q.paymentTerms?.includes('15') ? 80 : 50;
    const total        = Math.round(priceScore*wtPrice + leadScore*wtLead + historyScore*0.20 + payScore*0.15);
    return { ...q, aiScore:total, breakdown:{priceScore,leadScore,historyScore,payScore}, leadOk,
      warning: !leadOk ? `Entrega en ${q.leadTimeDays}d — tarea necesita en ${reqDays}d` : null };
  }).sort((a,b) => b.aiScore - a.aiScore).map((q,i) => ({ ...q, aiRank:i+1 }));
}

// ── Helpers ───────────────────────────────────────────────────────────────────
const fmtCOP  = n => `$${Number(n).toLocaleString('es-CO')}`;
const fmtDate = s => new Date(s).toLocaleDateString('es-CO', { day:'2-digit', month:'short', year:'numeric' });
const fmtDT   = s => new Date(s).toLocaleString('es-CO',    { day:'2-digit', month:'short', year:'numeric', hour:'2-digit', minute:'2-digit' });

const STATUS_RFQ       = { OPEN:'Abierta', CLOSED:'Cerrada', ADJUDICATED:'Adjudicada', DRAFT:'Borrador' };
const STATUS_PO        = { DRAFT:'Borrador', APPROVED:'Aprobada', SENT:'Enviada', RECEIVED:'Recibida', CANCELLED:'Cancelada' };
const STATUS_RFQ_COLOR = { OPEN:'bg-blue-100 text-blue-700 dark:bg-blue-500/20 dark:text-blue-300', CLOSED:'bg-amber-100 text-amber-700 dark:bg-amber-500/20 dark:text-amber-300', ADJUDICATED:'bg-emerald-100 text-emerald-700 dark:bg-emerald-500/20 dark:text-emerald-300', DRAFT:'bg-slate-100 text-slate-600 dark:bg-gray-500/20 dark:text-gray-400' };
const STATUS_PO_COLOR  = { DRAFT:'bg-slate-100 text-slate-600 dark:bg-gray-500/20 dark:text-gray-400', APPROVED:'bg-purple-100 text-purple-700 dark:bg-purple-500/20 dark:text-purple-300', SENT:'bg-blue-100 text-blue-700 dark:bg-blue-500/20 dark:text-blue-300', RECEIVED:'bg-emerald-100 text-emerald-700 dark:bg-emerald-500/20 dark:text-emerald-300', CANCELLED:'bg-red-100 text-red-700 dark:bg-red-500/20 dark:text-red-300' };
const TASK_STATUS_COLOR = { COMPLETADA:'text-emerald-600 dark:text-emerald-400', EN_PROCESO:'text-blue-600 dark:text-blue-400', PENDIENTE:'text-slate-400 dark:text-gray-500' };

function Badge({ label, color }) {
  return <span className={`text-xs px-2 py-0.5 rounded-full font-medium ${color}`}>{label}</span>;
}
function ScoreBar({ score }) {
  const color = score >= 80 ? '#10B981' : score >= 60 ? '#F59E0B' : '#EF4444';
  return (
    <div className="flex items-center gap-2">
      <div className="flex-1 h-1.5 bg-slate-100 dark:bg-surface-700 rounded-full overflow-hidden">
        <div className="h-full rounded-full" style={{ width:`${score}%`, background:color }}/>
      </div>
      <span className="text-xs font-bold tabular-nums w-7 text-right" style={{ color }}>{score}</span>
    </div>
  );
}
function Avatar({ member, size='sm' }) {
  const cls = size === 'sm' ? 'w-6 h-6 text-xs' : 'w-8 h-8 text-sm';
  return (
    <div className={`${cls} rounded-full font-bold flex items-center justify-center flex-shrink-0`}
      style={{ background:(member?.color||'#2563eb')+'22', color:member?.color||'#2563eb' }}
      title={`${member?.firstName} ${member?.lastName} · ${member?.role?.replace(/_/g,' ')}`}>
      {member?.avatar}
    </div>
  );
}

// ── Meeting Minutes Modal (print-ready) ──────────────────────────────────────
function MeetingMinutesModal({ meeting, onClose }) {
  const printRef = useRef(null);
  if (!meeting) return null;

  const memberMap = Object.fromEntries(MOCK_TEAM.map(m => [m.id, m]));
  const rfqMap    = Object.fromEntries(MOCK_RFQS.map(r => [r.id, r]));

  const handlePrint = () => {
    const content = printRef.current.innerHTML;
    const w = window.open('', '_blank', 'width=900,height=700');
    w.document.write(`
      <html><head><title>Acta ${meeting.code}</title>
      <style>
        body { font-family: 'Segoe UI', Arial, sans-serif; margin: 40px; color: #1e293b; font-size: 13px; }
        h1 { font-size: 20px; border-bottom: 2px solid #2563eb; padding-bottom: 8px; color: #1e3a8a; }
        h2 { font-size: 14px; color: #475569; margin-top: 20px; text-transform: uppercase; letter-spacing: 0.05em; }
        table { width: 100%; border-collapse: collapse; margin-top: 8px; }
        th { background: #f1f5f9; padding: 8px 10px; text-align: left; font-size: 11px; text-transform: uppercase; color: #64748b; }
        td { padding: 8px 10px; border-bottom: 1px solid #e2e8f0; }
        .aprobada { color: #059669; font-weight: 600; }
        .rechazada { color: #dc2626; font-weight: 600; }
        .badge { display:inline-block; padding: 2px 8px; border-radius: 999px; font-size: 11px; font-weight: 600; }
        .footer { margin-top: 40px; border-top: 1px solid #e2e8f0; padding-top: 16px; color: #94a3b8; font-size: 11px; }
        .signatures { display: flex; gap: 60px; margin-top: 60px; }
        .sig-line { border-top: 1px solid #1e293b; width: 180px; padding-top: 6px; font-size: 11px; }
        @media print { body { margin: 20mm; } }
      </style></head><body>${content}
      <div class="signatures">
        ${meeting.attendees.map(id => { const m = memberMap[id]; return m ? `<div class="sig-line">${m.firstName} ${m.lastName}<br/><span style="color:#64748b">${m.role?.replace(/_/g,' ')}</span></div>` : ''; }).join('')}
      </div>
      <div class="footer">Documento generado por ARPM · ${new Date().toLocaleString('es-CO')} · Este documento es copia oficial del acta de junta de compras.</div>
      </body></html>`);
    w.document.close();
    w.focus();
    setTimeout(() => w.print(), 400);
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/60 backdrop-blur-sm" onClick={onClose}>
      <div className="bg-white dark:bg-surface-800 rounded-2xl shadow-2xl w-full max-w-2xl max-h-[90vh] flex flex-col border border-slate-200 dark:border-surface-700"
        onClick={e => e.stopPropagation()}>
        {/* Header */}
        <div className="flex items-center justify-between px-6 py-4 border-b border-slate-100 dark:border-surface-700">
          <div>
            <p className="text-xs font-mono font-bold text-blue-600 dark:text-blue-400">{meeting.code}</p>
            <h2 className="text-base font-bold text-slate-900 dark:text-white mt-0.5">Acta de Junta de Compras</h2>
          </div>
          <div className="flex items-center gap-2">
            <button onClick={handlePrint}
              className="flex items-center gap-1.5 px-3 py-2 text-sm font-medium rounded-xl bg-blue-600 hover:bg-blue-700 text-white transition cursor-pointer">
              <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M17 17h2a2 2 0 002-2v-4a2 2 0 00-2-2H5a2 2 0 00-2 2v4a2 2 0 002 2h2m2 4h6a2 2 0 002-2v-4a2 2 0 00-2-2H9a2 2 0 00-2 2v4a2 2 0 002 2zm8-12V5a2 2 0 00-2-2H9a2 2 0 00-2 2v4h10z"/></svg>
              Imprimir / PDF
            </button>
            <button onClick={onClose} className="p-2 rounded-xl text-slate-400 hover:text-slate-600 dark:hover:text-gray-300 hover:bg-slate-100 dark:hover:bg-surface-700 transition cursor-pointer">
              <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12"/></svg>
            </button>
          </div>
        </div>

        {/* Printable content */}
        <div className="overflow-y-auto flex-1 px-6 py-4">
          <div ref={printRef}>
            <h1>Acta de Junta de Compras — {meeting.code}</h1>

            {/* Meta */}
            <table style={{marginBottom:16}}>
              <tbody>
                {[
                  ['Fecha y hora', fmtDT(meeting.date)],
                  ['Canal', meeting.channel],
                  ['Duración', `${meeting.duration} minutos`],
                  ['Quórum', meeting.quorum ? 'Alcanzado' : 'No alcanzado'],
                  ['Próxima junta', fmtDT(meeting.nextMeeting)],
                ].map(([k,v]) => (
                  <tr key={k} className="border-b border-slate-50 dark:border-surface-700">
                    <td className="py-2 pr-6 text-xs font-semibold text-slate-400 dark:text-gray-500 uppercase tracking-wider w-36">{k}</td>
                    <td className="py-2 text-sm text-slate-700 dark:text-gray-300">{v}</td>
                  </tr>
                ))}
              </tbody>
            </table>

            {/* Asistentes */}
            <h2 className="text-xs font-bold text-slate-500 dark:text-gray-400 uppercase tracking-wider mt-5 mb-2">Asistentes</h2>
            <div className="flex gap-2 flex-wrap mb-4">
              {meeting.attendees.map(id => {
                const m = memberMap[id];
                return m ? (
                  <div key={id} className="flex items-center gap-2 bg-slate-50 dark:bg-surface-700 rounded-lg px-3 py-2">
                    <Avatar member={m}/>
                    <div>
                      <p className="text-xs font-semibold text-slate-800 dark:text-gray-200">{m.firstName} {m.lastName}</p>
                      <p className="text-xs text-slate-400 dark:text-gray-500">{m.role?.replace(/_/g,' ')}</p>
                    </div>
                  </div>
                ) : null;
              })}
            </div>

            {/* Decisiones */}
            {meeting.items.length > 0 && <>
              <h2 className="text-xs font-bold text-slate-500 dark:text-gray-400 uppercase tracking-wider mb-2">Decisiones tomadas</h2>
              <div className="space-y-2 mb-4">
                {meeting.items.map((item, i) => {
                  const rfq = rfqMap[item.rfqId];
                  const isApproved = item.decision === 'APROBADA';
                  return (
                    <div key={i} className={`rounded-xl p-4 border ${isApproved ? 'bg-emerald-50 dark:bg-emerald-500/10 border-emerald-200 dark:border-emerald-500/20' : 'bg-red-50 dark:bg-red-500/10 border-red-200 dark:border-red-500/20'}`}>
                      <div className="flex items-center justify-between mb-1">
                        <div className="flex items-center gap-2">
                          <span className="text-xs font-mono font-bold text-slate-500 dark:text-gray-400">{rfq?.code || item.rfqId}</span>
                          {item.poCode && <span className="text-xs font-mono font-bold text-blue-600 dark:text-blue-400">→ {item.poCode}</span>}
                        </div>
                        <Badge label={item.decision} color={isApproved ? 'bg-emerald-100 text-emerald-700 dark:bg-emerald-500/20 dark:text-emerald-400' : 'bg-red-100 text-red-700 dark:bg-red-500/20 dark:text-red-400'}/>
                      </div>
                      {rfq && <p className="text-xs text-slate-600 dark:text-gray-300 mb-1">{rfq.material} · {rfq.qty} {rfq.unit} · {rfq.projectCode}</p>}
                      <p className="text-xs text-slate-600 dark:text-gray-400 italic">"{item.notes}"</p>
                      <p className="text-xs text-slate-400 dark:text-gray-500 mt-1.5">
                        Votación: {item.votes.favor} a favor · {item.votes.contra} en contra · {item.votes.abstencion} abstención
                      </p>
                    </div>
                  );
                })}
              </div>
            </>}

            {/* Objeciones */}
            {meeting.objections.length > 0 && <>
              <h2 className="text-xs font-bold text-slate-500 dark:text-gray-400 uppercase tracking-wider mb-2">Objeciones formales</h2>
              <div className="space-y-2 mb-4">
                {meeting.objections.map((obj, i) => (
                  <div key={i} className="bg-amber-50 dark:bg-amber-500/10 border border-amber-200 dark:border-amber-500/20 rounded-lg px-4 py-3 text-sm text-amber-700 dark:text-amber-300">
                    {obj}
                  </div>
                ))}
              </div>
            </>}

            {meeting.items.length === 0 && meeting.objections.length === 0 && (
              <p className="text-sm text-slate-400 dark:text-gray-500 italic py-4">Sin decisiones ni objeciones registradas en esta junta.</p>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

// ── Tab: RFQs ─────────────────────────────────────────────────────────────────
function TabRFQs({ rfqs, onSelectRFQ }) {
  const [search, setSearch] = useState('');
  const memberMap = Object.fromEntries(MOCK_TEAM.map(m => [m.id, m]));
  const filtered  = rfqs.filter(r => !search || `${r.code} ${r.material} ${r.projectCode}`.toLowerCase().includes(search.toLowerCase()));

  return (
    <div className="space-y-4">
      {/* Info bar */}
      <div className="flex items-center gap-2 bg-blue-50 dark:bg-blue-500/10 border border-blue-100 dark:border-blue-500/20 rounded-xl px-4 py-2.5">
        <svg className="w-4 h-4 text-blue-500 flex-shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>
        <p className="text-xs text-blue-700 dark:text-blue-300">
          Las RFQs se asignan automáticamente al <strong>Departamento de Compras</strong>. La fecha límite se calcula desde la entrega requerida menos el lead time máximo del proveedor.
        </p>
      </div>

      <div className="flex items-center justify-between gap-3">
        <div className="relative flex-1 max-w-xs">
          <svg className="absolute left-3 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-slate-400" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><circle cx="11" cy="11" r="8"/><path strokeLinecap="round" strokeLinejoin="round" d="M21 21l-4.35-4.35"/></svg>
          <input value={search} onChange={e => setSearch(e.target.value)} placeholder="Buscar RFQ..."
            className="w-full pl-8 pr-3 py-2 text-sm rounded-xl border border-slate-200 dark:border-surface-600 bg-white dark:bg-surface-700 text-slate-800 dark:text-gray-200 placeholder-slate-300 focus:outline-none focus:ring-1 focus:ring-blue-500"/>
        </div>
        <button className="flex items-center gap-2 px-4 py-2 text-sm font-medium rounded-xl bg-blue-600 hover:bg-blue-700 text-white transition cursor-pointer">
          <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M12 4v16m8-8H4"/></svg>
          Nueva RFQ
        </button>
      </div>

      <div className="overflow-x-auto">
        <table className="w-full text-sm">
          <thead>
            <tr className="border-b border-slate-100 dark:border-surface-700">
              {['Código','Proyecto','Material / Servicio','Cant.','Responsable','Fecha límite resp.','Entrega req.','Estado','Cotiz.',''].map(h => (
                <th key={h} className="text-left text-xs font-semibold text-slate-400 dark:text-gray-500 uppercase tracking-wider pb-3 pr-4 whitespace-nowrap">{h}</th>
              ))}
            </tr>
          </thead>
          <tbody className="divide-y divide-slate-50 dark:divide-surface-700/50">
            {filtered.map(rfq => {
              const quotes     = MOCK_QUOTES.filter(q => q.rfqId === rfq.id);
              const assignee   = memberMap[rfq.assignedTo] || DEFAULT_PURCHASER;
              return (
                <tr key={rfq.id} className="hover:bg-slate-50 dark:hover:bg-surface-700/30 transition-colors">
                  <td className="py-3 pr-4 font-mono text-xs font-bold text-blue-600 dark:text-blue-400">{rfq.code}</td>
                  <td className="py-3 pr-4 text-xs font-mono text-slate-400 dark:text-gray-500">{rfq.projectCode}</td>
                  <td className="py-3 pr-4">
                    <p className="font-medium text-slate-800 dark:text-gray-200">{rfq.material}</p>
                    <p className="text-xs text-slate-400 dark:text-gray-500">WBS {rfq.taskWbs} · {rfq.taskTitle}</p>
                    {rfq.taskIsCritical && <span className="text-xs text-red-500 font-semibold">⚡ Ruta crítica</span>}
                  </td>
                  <td className="py-3 pr-4 text-slate-700 dark:text-gray-300 whitespace-nowrap">{rfq.qty} {rfq.unit}</td>
                  <td className="py-3 pr-4">
                    <div className="flex items-center gap-1.5">
                      <Avatar member={assignee}/>
                      <span className="text-xs text-slate-600 dark:text-gray-300">{assignee.firstName}</span>
                    </div>
                  </td>
                  <td className="py-3 pr-4 text-xs text-slate-600 dark:text-gray-400 whitespace-nowrap">{fmtDate(rfq.rfqDeadline)}</td>
                  <td className="py-3 pr-4 text-xs text-slate-600 dark:text-gray-400 whitespace-nowrap">{fmtDate(rfq.requiredDate)}</td>
                  <td className="py-3 pr-4"><Badge label={STATUS_RFQ[rfq.status]} color={STATUS_RFQ_COLOR[rfq.status]}/></td>
                  <td className="py-3 pr-4">
                    <span className={`text-xs font-bold ${quotes.length > 0 ? 'text-blue-600 dark:text-blue-400' : 'text-slate-300 dark:text-gray-600'}`}>
                      {quotes.length}
                    </span>
                  </td>
                  <td className="py-3">
                    {quotes.length > 0 && rfq.status !== 'DRAFT' && (
                      <button onClick={() => onSelectRFQ(rfq)}
                        className="text-xs px-3 py-1.5 rounded-lg bg-violet-50 dark:bg-violet-500/10 text-violet-700 dark:text-violet-400 border border-violet-200 dark:border-violet-500/30 hover:bg-violet-100 dark:hover:bg-violet-500/20 transition cursor-pointer font-medium whitespace-nowrap">
                        Eval. IA
                      </button>
                    )}
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}

// ── Tab: Evaluación IA ────────────────────────────────────────────────────────
function TabEvaluacion({ rfqs, selectedRFQ, onSelectRFQ }) {
  const rfq       = selectedRFQ || rfqs.find(r => MOCK_QUOTES.some(q => q.rfqId === r.id));
  const supMap    = Object.fromEntries(MOCK_SUPPLIERS.map(s => [s.id, s]));
  if (!rfq) return <p className="text-slate-400 dark:text-gray-500 text-sm py-8 text-center">Selecciona una RFQ con cotizaciones recibidas.</p>;

  const rawQuotes = MOCK_QUOTES.filter(q => q.rfqId === rfq.id);
  const evaluated = evaluateQuotes(rawQuotes, rfq);
  const winner    = evaluated[0];
  const wtPrice   = rfq.taskIsCritical ? 25 : 40;
  const wtLead    = rfq.taskIsCritical ? 45 : 25;

  return (
    <div className="space-y-5">
      <div className="flex items-center gap-3 flex-wrap">
        <span className="text-sm text-slate-500 dark:text-gray-400">Evaluando:</span>
        <select value={rfq.id} onChange={e => onSelectRFQ(rfqs.find(r => r.id === e.target.value))}
          className="text-sm bg-white dark:bg-surface-700 border border-slate-200 dark:border-surface-600 rounded-lg px-3 py-1.5 text-slate-700 dark:text-gray-300 cursor-pointer focus:outline-none focus:ring-1 focus:ring-blue-500">
          {rfqs.filter(r => MOCK_QUOTES.some(q => q.rfqId === r.id)).map(r => (
            <option key={r.id} value={r.id}>{r.code} — {r.material}</option>
          ))}
        </select>
      </div>

      <div className={`rounded-xl p-4 border ${rfq.taskIsCritical ? 'bg-red-50 dark:bg-red-500/10 border-red-200 dark:border-red-500/20' : 'bg-slate-50 dark:bg-surface-700 border-slate-100 dark:border-surface-600'}`}>
        <p className="text-sm font-semibold text-slate-800 dark:text-gray-200">
          {rfq.taskIsCritical && <span className="text-red-500 mr-1.5">⚡</span>}{rfq.material}
        </p>
        <p className="text-xs text-slate-500 dark:text-gray-400 mt-0.5">
          Tarea: {rfq.taskWbs} {rfq.taskTitle} · Entrega req.: {fmtDate(rfq.requiredDate)}
          {rfq.taskIsCritical && ' · Ruta crítica — lead time priorizado'}
        </p>
        <div className="flex gap-4 mt-2 text-xs text-slate-500 dark:text-gray-400">
          {[['Precio', wtPrice], ['Lead time', wtLead], ['Historial', 20], ['Condición pago', 15]].map(([label, w]) => (
            <span key={label}>
              {label} <strong className="text-slate-700 dark:text-gray-300">{w}%</strong>
            </span>
          ))}
        </div>
      </div>

      <div className="overflow-x-auto">
        <table className="w-full text-sm">
          <thead>
            <tr className="border-b border-slate-100 dark:border-surface-700">
              {['Rank','Proveedor','Precio unit.','Total','Lead time','Pago','Score IA','Historial',''].map(h => (
                <th key={h} className="text-left text-xs font-semibold text-slate-400 dark:text-gray-500 uppercase tracking-wider pb-3 pr-4">{h}</th>
              ))}
            </tr>
          </thead>
          <tbody className="divide-y divide-slate-50 dark:divide-surface-700/50">
            {evaluated.map(q => {
              const sup      = supMap[q.supplierId];
              const isWinner = q.aiRank === 1;
              return (
                <tr key={q.id} className={`transition-colors ${isWinner ? 'bg-emerald-50/50 dark:bg-emerald-500/5' : 'hover:bg-slate-50 dark:hover:bg-surface-700/30'}`}>
                  <td className="py-3 pr-4">
                    <div className={`w-7 h-7 rounded-full flex items-center justify-center text-xs font-bold ${isWinner ? 'bg-emerald-500 text-white' : 'bg-slate-100 dark:bg-surface-700 text-slate-500 dark:text-gray-400'}`}>
                      {q.aiRank}
                    </div>
                  </td>
                  <td className="py-3 pr-4">
                    <p className="font-medium text-slate-800 dark:text-gray-200">{sup?.name}</p>
                    <p className="text-xs text-slate-400 dark:text-gray-500">{sup?.city}</p>
                    {isWinner && <span className="text-xs text-emerald-600 dark:text-emerald-400 font-semibold">Recomendado</span>}
                  </td>
                  <td className="py-3 pr-4 font-mono tabular-nums text-slate-700 dark:text-gray-300">{fmtCOP(q.unitPrice)}</td>
                  <td className="py-3 pr-4 font-mono tabular-nums font-semibold text-slate-800 dark:text-gray-200">{fmtCOP(q.totalPrice)}</td>
                  <td className="py-3 pr-4">
                    <p className={`text-sm font-semibold ${q.leadOk ? 'text-emerald-600 dark:text-emerald-400' : 'text-red-500'}`}>{q.leadTimeDays}d</p>
                    {q.warning && <p className="text-xs text-red-500">{q.warning}</p>}
                  </td>
                  <td className="py-3 pr-4 text-xs text-slate-600 dark:text-gray-400 max-w-[120px]">{q.paymentTerms}</td>
                  <td className="py-3 pr-4 w-32"><ScoreBar score={q.aiScore}/></td>
                  <td className="py-3 pr-4">
                    <div className="flex">{[...Array(5)].map((_,i) => (
                      <span key={i} className={`text-xs ${i < Math.round(sup?.rating||0) ? 'text-amber-400' : 'text-slate-200 dark:text-gray-700'}`}>★</span>
                    ))}</div>
                    <p className="text-xs text-slate-400 dark:text-gray-500">{sup?.deliveryCompliance}% entregas</p>
                    {(sup?.ncrs||0) > 0 && <p className="text-xs text-red-500">{sup.ncrs} NCR</p>}
                  </td>
                  <td className="py-3">
                    <button className={`text-xs px-3 py-1.5 rounded-lg font-medium transition cursor-pointer whitespace-nowrap ${isWinner ? 'bg-emerald-600 hover:bg-emerald-700 text-white' : 'bg-slate-100 dark:bg-surface-700 text-slate-600 dark:text-gray-300 hover:bg-slate-200 dark:hover:bg-surface-600'}`}>
                      {isWinner ? 'Adjudicar' : 'Seleccionar'}
                    </button>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>

      {winner && (
        <div className="bg-violet-50 dark:bg-violet-500/10 border border-violet-200 dark:border-violet-500/20 rounded-xl p-4">
          <div className="flex items-center gap-2 mb-2">
            <svg className="w-4 h-4 text-violet-600 dark:text-violet-400 flex-shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z"/></svg>
            <p className="text-sm font-bold text-violet-700 dark:text-violet-400">Razonamiento IA</p>
          </div>
          <p className="text-sm text-violet-700 dark:text-violet-300 leading-relaxed">
            <strong>{supMap[winner.supplierId]?.name}</strong> recomendado con score {winner.aiScore}/100.
            {rfq.taskIsCritical
              ? ` Tarea en ruta crítica — lead time de ${winner.leadTimeDays} días priorizado sobre precio. Garantiza inicio puntual de la tarea.`
              : ` Mejor balance precio/historial para tarea con holgura suficiente.`}
            {winner.breakdown.historyScore >= 80 && ' Excelente historial de entregas sin NCRs.'}
            {winner.paymentTerms?.includes('crédito') && ' Condición crédito favorece el flujo de caja.'}
          </p>
        </div>
      )}
    </div>
  );
}

// ── Tab: Órdenes de Compra ────────────────────────────────────────────────────
function TabPOs({ pos, onOpenMeeting }) {
  const supMap    = Object.fromEntries(MOCK_SUPPLIERS.map(s => [s.id, s]));
  const memberMap = Object.fromEntries(MOCK_TEAM.map(m => [m.id, m]));

  return (
    <div className="space-y-4">
      <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
        {[
          { label:'Total POs',           val: pos.length,                              color:'text-slate-800 dark:text-gray-200' },
          { label:'Borradores',          val: pos.filter(p=>p.status==='DRAFT').length, color:'text-amber-600' },
          { label:'Enviadas',            val: pos.filter(p=>p.status==='SENT').length,  color:'text-blue-600' },
          { label:'Valor comprometido',  val: fmtCOP(pos.reduce((s,p)=>s+p.total,0)),  color:'text-emerald-600' },
        ].map(({label,val,color}) => (
          <div key={label} className="bg-slate-50 dark:bg-surface-700 rounded-xl p-4 border border-slate-100 dark:border-surface-600">
            <p className="text-xs text-slate-400 dark:text-gray-500 mb-1">{label}</p>
            <p className={`text-lg font-bold tabular-nums ${color}`}>{val}</p>
          </div>
        ))}
      </div>

      <div className="overflow-x-auto">
        <table className="w-full text-sm">
          <thead>
            <tr className="border-b border-slate-100 dark:border-surface-700">
              {['Código PO','Proveedor','Material','Total','Estado','Entrega esperada','Resp. Compras','Junta ref.','Aprobadores'].map(h => (
                <th key={h} className="text-left text-xs font-semibold text-slate-400 dark:text-gray-500 uppercase tracking-wider pb-3 pr-4 whitespace-nowrap">{h}</th>
              ))}
            </tr>
          </thead>
          <tbody className="divide-y divide-slate-50 dark:divide-surface-700/50">
            {pos.map(po => {
              const sup       = supMap[po.supplierId];
              const approvers = po.approvedBy.map(id => memberMap[id]).filter(Boolean);
              const assignee  = memberMap[po.assignedTo] || DEFAULT_PURCHASER;
              const meeting   = MOCK_MEETINGS.find(m => m.code === po.meetingRef);
              return (
                <tr key={po.id} className="hover:bg-slate-50 dark:hover:bg-surface-700/30 transition-colors">
                  <td className="py-3 pr-4 font-mono text-xs font-bold text-blue-600 dark:text-blue-400">{po.code}</td>
                  <td className="py-3 pr-4">
                    <p className="font-medium text-slate-800 dark:text-gray-200">{sup?.name}</p>
                    <p className="text-xs text-slate-400 dark:text-gray-500">{sup?.city}</p>
                  </td>
                  <td className="py-3 pr-4 max-w-[160px]">
                    <p className="text-slate-700 dark:text-gray-300 truncate">{po.material}</p>
                    <p className="text-xs text-slate-400 dark:text-gray-500">{po.projectCode}</p>
                  </td>
                  <td className="py-3 pr-4 font-mono font-semibold tabular-nums text-slate-800 dark:text-gray-200 whitespace-nowrap">{fmtCOP(po.total)}</td>
                  <td className="py-3 pr-4"><Badge label={STATUS_PO[po.status]} color={STATUS_PO_COLOR[po.status]}/></td>
                  <td className="py-3 pr-4 text-xs text-slate-500 dark:text-gray-400 whitespace-nowrap">{fmtDate(po.expectedDelivery)}</td>
                  <td className="py-3 pr-4">
                    <div className="flex items-center gap-1.5">
                      <Avatar member={assignee}/>
                      <span className="text-xs text-slate-600 dark:text-gray-300">{assignee.firstName}</span>
                    </div>
                  </td>
                  <td className="py-3 pr-4">
                    {po.meetingRef ? (
                      <button
                        onClick={() => meeting && onOpenMeeting(meeting)}
                        title="Ver acta de esta junta"
                        className="font-mono text-xs font-bold text-violet-600 dark:text-violet-400 hover:text-violet-800 dark:hover:text-violet-300 hover:underline cursor-pointer transition-colors">
                        {po.meetingRef}
                      </button>
                    ) : (
                      <span className="text-xs text-slate-300 dark:text-gray-600">—</span>
                    )}
                  </td>
                  <td className="py-3">
                    {approvers.length > 0 ? (
                      <div className="flex gap-1">
                        {approvers.map(a => <Avatar key={a.id} member={a}/>)}
                      </div>
                    ) : (
                      <span className="text-xs text-amber-500 font-medium">Pendiente</span>
                    )}
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}

// ── Tab: Juntas ───────────────────────────────────────────────────────────────
function TabJuntas({ meetings, onOpenMeeting }) {
  const [sel, setSel] = useState(meetings[0]?.id || null);
  const meeting       = meetings.find(m => m.id === sel);
  const memberMap     = Object.fromEntries(MOCK_TEAM.map(m => [m.id, m]));
  const rfqMap        = Object.fromEntries(MOCK_RFQS.map(r => [r.id, r]));

  return (
    <div className="flex gap-4 min-h-[420px]">
      {/* List */}
      <div className="w-52 flex-shrink-0 space-y-1">
        {meetings.map(m => (
          <button key={m.id} onClick={() => setSel(m.id)}
            className={`w-full text-left px-3 py-2.5 rounded-xl transition-colors cursor-pointer ${sel===m.id ? 'bg-blue-50 dark:bg-blue-500/10 border border-blue-200 dark:border-blue-500/30' : 'hover:bg-slate-50 dark:hover:bg-surface-700/50 border border-transparent'}`}>
            <p className={`text-xs font-bold font-mono ${sel===m.id ? 'text-blue-700 dark:text-blue-400' : 'text-slate-600 dark:text-gray-400'}`}>{m.code}</p>
            <p className="text-xs text-slate-500 dark:text-gray-400 mt-0.5">{fmtDate(m.date)}</p>
            <div className="flex items-center gap-1.5 mt-1">
              <span className={`w-1.5 h-1.5 rounded-full ${m.quorum ? 'bg-emerald-400' : 'bg-red-400'}`}/>
              <span className="text-xs text-slate-400 dark:text-gray-500">{m.attendees.length} asistentes</span>
            </div>
          </button>
        ))}
      </div>

      {/* Detail */}
      {meeting && (
        <div className="flex-1 min-w-0 space-y-4">
          <div className="flex items-start justify-between">
            <div>
              <div className="flex items-center gap-2">
                <h3 className="text-base font-bold text-slate-900 dark:text-white">{meeting.code}</h3>
                <Badge label={meeting.quorum ? 'Quórum ✓' : 'Sin quórum'}
                  color={meeting.quorum ? 'bg-emerald-100 text-emerald-700 dark:bg-emerald-500/20 dark:text-emerald-400' : 'bg-red-100 text-red-700 dark:bg-red-500/20 dark:text-red-400'}/>
              </div>
              <p className="text-sm text-slate-500 dark:text-gray-400 mt-0.5">{fmtDT(meeting.date)} · {meeting.channel} · {meeting.duration} min</p>
            </div>
            <button onClick={() => onOpenMeeting(meeting)}
              className="flex items-center gap-1.5 px-3 py-2 text-sm font-medium rounded-xl bg-slate-100 dark:bg-surface-700 hover:bg-slate-200 dark:hover:bg-surface-600 text-slate-700 dark:text-gray-300 transition cursor-pointer">
              <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M17 17h2a2 2 0 002-2v-4a2 2 0 00-2-2H5a2 2 0 00-2 2v4a2 2 0 002 2h2m2 4h6a2 2 0 002-2v-4a2 2 0 00-2-2H9a2 2 0 00-2 2v4a2 2 0 002 2zm8-12V5a2 2 0 00-2-2H9a2 2 0 00-2 2v4h10z"/></svg>
              Ver acta
            </button>
          </div>

          {/* Asistentes */}
          <div>
            <p className="text-xs font-bold text-slate-500 dark:text-gray-400 uppercase tracking-wider mb-2">Asistentes</p>
            <div className="flex gap-2 flex-wrap">
              {meeting.attendees.map(id => {
                const m2 = memberMap[id];
                return m2 ? (
                  <div key={id} className="flex items-center gap-2 bg-slate-50 dark:bg-surface-700 rounded-lg px-3 py-1.5">
                    <Avatar member={m2}/>
                    <div>
                      <p className="text-xs font-medium text-slate-800 dark:text-gray-200">{m2.firstName} {m2.lastName}</p>
                      <p className="text-xs text-slate-400 dark:text-gray-500">{m2.role?.replace(/_/g,' ')}</p>
                    </div>
                  </div>
                ) : null;
              })}
            </div>
          </div>

          {/* Decisiones */}
          {meeting.items.length > 0 && (
            <div>
              <p className="text-xs font-bold text-slate-500 dark:text-gray-400 uppercase tracking-wider mb-2">Decisiones</p>
              <div className="space-y-2">
                {meeting.items.map((item, i) => {
                  const rfq      = rfqMap[item.rfqId];
                  const approved = item.decision === 'APROBADA';
                  return (
                    <div key={i} className={`rounded-xl p-3 border ${approved ? 'bg-emerald-50 dark:bg-emerald-500/10 border-emerald-200 dark:border-emerald-500/20' : 'bg-red-50 dark:bg-red-500/10 border-red-200 dark:border-red-500/20'}`}>
                      <div className="flex items-center justify-between gap-2 mb-1">
                        <div className="flex items-center gap-2">
                          <span className="text-xs font-mono text-slate-500 dark:text-gray-400">{rfq?.code}</span>
                          {item.poCode && <span className="text-xs font-mono font-bold text-blue-600 dark:text-blue-400">→ {item.poCode}</span>}
                        </div>
                        <Badge label={item.decision} color={approved ? 'bg-emerald-100 text-emerald-700 dark:bg-emerald-500/20 dark:text-emerald-400' : 'bg-red-100 text-red-700 dark:bg-red-500/20 dark:text-red-400'}/>
                      </div>
                      <p className="text-xs text-slate-600 dark:text-gray-400 italic">"{item.notes}"</p>
                      <p className="text-xs text-slate-400 dark:text-gray-500 mt-1">
                        {item.votes.favor}✓ {item.votes.contra}✗ {item.votes.abstencion}—
                      </p>
                    </div>
                  );
                })}
              </div>
            </div>
          )}

          {/* Objeciones */}
          {meeting.objections.length > 0 && (
            <div>
              <p className="text-xs font-bold text-slate-500 dark:text-gray-400 uppercase tracking-wider mb-2">Objeciones formales</p>
              {meeting.objections.map((obj, i) => (
                <div key={i} className="bg-amber-50 dark:bg-amber-500/10 border border-amber-200 dark:border-amber-500/20 rounded-lg px-3 py-2 text-xs text-amber-700 dark:text-amber-300">
                  {obj}
                </div>
              ))}
            </div>
          )}

          <div className="bg-slate-50 dark:bg-surface-700 rounded-xl p-3 flex items-center justify-between">
            <div>
              <p className="text-xs text-slate-400 dark:text-gray-500">Próxima junta</p>
              <p className="text-sm font-semibold text-slate-800 dark:text-gray-200">{fmtDT(meeting.nextMeeting)}</p>
            </div>
            <button className="text-xs px-3 py-1.5 rounded-lg bg-blue-600 hover:bg-blue-700 text-white font-medium transition cursor-pointer">
              + Agendar ítem
            </button>
          </div>
        </div>
      )}
    </div>
  );
}

// ── Tab: Proveedores ──────────────────────────────────────────────────────────
// ── CSV Import helpers ────────────────────────────────────────────────────────
const CSV_COLUMNS = ['name','contact','email','phone','category','city'];
const CSV_LABELS  = { name:'Nombre empresa', contact:'Contacto', email:'Email', phone:'Teléfono', category:'Categoría', city:'Ciudad' };

function parseCSV(text) {
  const lines = text.trim().split(/\r?\n/).filter(Boolean);
  if (lines.length < 2) return [];
  const headers = lines[0].split(',').map(h => h.trim().replace(/^"|"$/g,'').toLowerCase());
  const colMap = {};
  CSV_COLUMNS.forEach(col => {
    const idx = headers.findIndex(h => h.includes(col) || h.includes(CSV_LABELS[col].toLowerCase().split(' ')[0]));
    if (idx >= 0) colMap[col] = idx;
  });
  return lines.slice(1).map((line, i) => {
    const vals = line.split(',').map(v => v.trim().replace(/^"|"$/g,''));
    const row = { id: `csv-${Date.now()}-${i}`, rating:4.0, deliveryCompliance:90, ncrs:0 };
    CSV_COLUMNS.forEach(col => { row[col] = colMap[col] !== undefined ? (vals[colMap[col]] || '') : ''; });
    return row;
  }).filter(r => r.name);
}

function CSVImportModal({ onImport, onClose }) {
  const [drag, setDrag]       = useState(false);
  const [preview, setPreview] = useState(null);
  const [error, setError]     = useState('');
  const fileRef               = useRef();

  const handleFile = file => {
    if (!file) return;
    const ext = file.name.split('.').pop().toLowerCase();
    if (!['csv','txt'].includes(ext)) { setError('Solo se aceptan archivos .csv'); return; }
    const reader = new FileReader();
    reader.onload = e => {
      const rows = parseCSV(e.target.result);
      if (!rows.length) { setError('No se encontraron datos válidos. Verifique el formato.'); return; }
      setError('');
      setPreview(rows);
    };
    reader.readAsText(file);
  };

  const onDrop = e => {
    e.preventDefault(); setDrag(false);
    handleFile(e.dataTransfer.files[0]);
  };

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4" onClick={onClose}>
      <div className="bg-white dark:bg-surface-800 rounded-2xl shadow-2xl w-full max-w-2xl border border-slate-200 dark:border-surface-700 max-h-[90vh] flex flex-col" onClick={e=>e.stopPropagation()}>
        {/* Header */}
        <div className="flex items-center justify-between px-6 py-4 border-b border-slate-100 dark:border-surface-700">
          <div>
            <h2 className="text-base font-bold text-slate-900 dark:text-white">Importar proveedores desde CSV</h2>
            <p className="text-xs text-slate-400 dark:text-gray-500 mt-0.5">Columnas esperadas: nombre, contacto, email, teléfono, categoría, ciudad</p>
          </div>
          <button onClick={onClose} className="text-slate-400 hover:text-slate-600 dark:hover:text-white cursor-pointer transition-colors">
            <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12"/></svg>
          </button>
        </div>

        <div className="p-6 overflow-y-auto flex-1 space-y-4">
          {!preview ? (
            <>
              {/* Drop zone */}
              <div
                onDragOver={e=>{e.preventDefault();setDrag(true)}}
                onDragLeave={()=>setDrag(false)}
                onDrop={onDrop}
                onClick={()=>fileRef.current.click()}
                className={`border-2 border-dashed rounded-xl p-10 text-center cursor-pointer transition-colors ${drag ? 'border-blue-500 bg-blue-50 dark:bg-blue-500/10' : 'border-slate-200 dark:border-surface-600 hover:border-blue-400 hover:bg-slate-50 dark:hover:bg-surface-700'}`}>
                <svg className="w-10 h-10 mx-auto mb-3 text-slate-300 dark:text-gray-600" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}><path strokeLinecap="round" strokeLinejoin="round" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-8l-4-4m0 0L8 8m4-4v12"/></svg>
                <p className="text-sm font-semibold text-slate-700 dark:text-gray-300 mb-1">Arrastra tu archivo CSV aquí</p>
                <p className="text-xs text-slate-400 dark:text-gray-500">o haz clic para seleccionar</p>
                <input ref={fileRef} type="file" accept=".csv,.txt" className="hidden" onChange={e=>handleFile(e.target.files[0])}/>
              </div>

              {error && <p className="text-xs text-red-600 dark:text-red-400 bg-red-50 dark:bg-red-500/10 px-3 py-2 rounded-lg">{error}</p>}

              {/* Format help */}
              <div className="bg-slate-50 dark:bg-surface-700 rounded-xl p-4 border border-slate-100 dark:border-surface-600">
                <p className="text-xs font-semibold text-slate-500 dark:text-gray-400 mb-2">Formato esperado (primera fila = encabezados):</p>
                <code className="text-xs text-slate-600 dark:text-gray-300 block overflow-x-auto whitespace-nowrap">
                  name,contact,email,phone,category,city<br/>
                  Aceros S.A.,Juan López,jlopez@aceros.com,+57 310 555 0101,Materiales,Bogotá
                </code>
              </div>
            </>
          ) : (
            <>
              <div className="flex items-center gap-2 bg-emerald-50 dark:bg-emerald-500/10 border border-emerald-100 dark:border-emerald-500/20 rounded-xl px-4 py-2.5">
                <svg className="w-4 h-4 text-emerald-600 dark:text-emerald-400 flex-shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M5 13l4 4L19 7"/></svg>
                <p className="text-xs font-medium text-emerald-700 dark:text-emerald-400">{preview.length} proveedor{preview.length!==1?'es':''} detectado{preview.length!==1?'s':''}. Revisa antes de importar.</p>
              </div>

              <div className="overflow-x-auto rounded-xl border border-slate-100 dark:border-surface-600">
                <table className="w-full text-xs">
                  <thead>
                    <tr className="bg-slate-50 dark:bg-surface-700">
                      {CSV_COLUMNS.map(c => <th key={c} className="px-3 py-2 text-left text-slate-500 dark:text-gray-400 font-semibold uppercase tracking-wide whitespace-nowrap">{CSV_LABELS[c]}</th>)}
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-slate-50 dark:divide-surface-700">
                    {preview.map((row, i) => (
                      <tr key={i} className="hover:bg-slate-50 dark:hover:bg-surface-700/50">
                        {CSV_COLUMNS.map(c => (
                          <td key={c} className={`px-3 py-2 text-slate-600 dark:text-gray-300 ${!row[c] ? 'text-slate-300 dark:text-gray-600 italic' : ''}`}>
                            {row[c] || '—'}
                          </td>
                        ))}
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>

              <button onClick={()=>setPreview(null)} className="text-xs text-slate-400 hover:text-slate-600 dark:hover:text-gray-300 cursor-pointer underline">
                Seleccionar otro archivo
              </button>
            </>
          )}
        </div>

        {/* Footer */}
        <div className="flex justify-end gap-2 px-6 py-4 border-t border-slate-100 dark:border-surface-700">
          <button onClick={onClose} className="px-4 py-2 text-sm text-slate-600 dark:text-gray-300 hover:bg-slate-100 dark:hover:bg-surface-700 rounded-lg transition-colors cursor-pointer">Cancelar</button>
          {preview && (
            <button onClick={()=>{ onImport(preview); onClose(); }}
              className="px-4 py-2 text-sm bg-emerald-600 hover:bg-emerald-700 text-white font-medium rounded-lg transition-colors cursor-pointer flex items-center gap-2">
              <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"/></svg>
              Importar {preview.length} proveedores
            </button>
          )}
        </div>
      </div>
    </div>
  );
}

function TabProveedores() {
  const [search, setSearch]   = useState('');
  const [suppliers, setSuppliers] = useState(MOCK_SUPPLIERS);
  const [showCSV, setShowCSV] = useState(false);

  const filtered = suppliers.filter(s => !search || `${s.name} ${s.city} ${s.category}`.toLowerCase().includes(search.toLowerCase()));

  const handleImport = (rows) => {
    setSuppliers(prev => [...prev, ...rows]);
  };

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between gap-3 flex-wrap">
        <div className="relative flex-1 max-w-xs">
          <svg className="absolute left-3 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-slate-400" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><circle cx="11" cy="11" r="8"/><path strokeLinecap="round" strokeLinejoin="round" d="M21 21l-4.35-4.35"/></svg>
          <input value={search} onChange={e => setSearch(e.target.value)} placeholder="Buscar proveedor..."
            className="w-full pl-8 pr-3 py-2 text-sm rounded-xl border border-slate-200 dark:border-surface-600 bg-white dark:bg-surface-700 text-slate-800 dark:text-gray-200 placeholder-slate-300 focus:outline-none focus:ring-1 focus:ring-blue-500"/>
        </div>
        <div className="flex items-center gap-2">
          <button onClick={()=>setShowCSV(true)}
            className="flex items-center gap-2 px-4 py-2 text-sm font-medium rounded-xl border border-slate-200 dark:border-surface-600 bg-white dark:bg-surface-700 text-slate-700 dark:text-gray-300 hover:border-emerald-400 hover:text-emerald-700 dark:hover:text-emerald-400 transition cursor-pointer">
            <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"/></svg>
            Importar CSV
          </button>
          <button className="flex items-center gap-2 px-4 py-2 text-sm font-medium rounded-xl bg-blue-600 hover:bg-blue-700 text-white transition cursor-pointer">
            <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M12 4v16m8-8H4"/></svg>
            Nuevo proveedor
          </button>
        </div>
      </div>

      {suppliers.length > MOCK_SUPPLIERS.length && (
        <div className="flex items-center gap-2 bg-emerald-50 dark:bg-emerald-500/10 border border-emerald-100 dark:border-emerald-500/20 rounded-xl px-4 py-2">
          <svg className="w-4 h-4 text-emerald-600 dark:text-emerald-400" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M5 13l4 4L19 7"/></svg>
          <p className="text-xs text-emerald-700 dark:text-emerald-400 font-medium">
            {suppliers.length - MOCK_SUPPLIERS.length} proveedor{suppliers.length - MOCK_SUPPLIERS.length !== 1 ? 'es' : ''} importado{suppliers.length - MOCK_SUPPLIERS.length !== 1 ? 's' : ''} desde CSV
          </p>
        </div>
      )}

      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3">
        {filtered.map(sup => {
          const compColor = sup.deliveryCompliance >= 90 ? 'text-emerald-600 dark:text-emerald-400' : sup.deliveryCompliance >= 75 ? 'text-amber-500' : 'text-red-500';
          return (
            <div key={sup.id} className="bg-slate-50 dark:bg-surface-700 rounded-xl p-4 border border-slate-100 dark:border-surface-600 hover:border-blue-200 dark:hover:border-blue-500/30 transition-colors cursor-pointer">
              <div className="flex items-start justify-between gap-2 mb-3">
                <div>
                  <p className="text-sm font-semibold text-slate-900 dark:text-white leading-snug">{sup.name}</p>
                  <p className="text-xs text-slate-400 dark:text-gray-500">{sup.category} · {sup.city}</p>
                </div>
                <div className="text-right">
                  <div className="flex justify-end">{[...Array(5)].map((_,i) => <span key={i} className={`text-xs ${i < Math.round(sup.rating) ? 'text-amber-400' : 'text-slate-200 dark:text-gray-700'}`}>★</span>)}</div>
                  <span className="text-xs font-bold text-amber-500">{sup.rating}</span>
                </div>
              </div>
              <div className="space-y-1.5 text-xs">
                <div className="flex justify-between"><span className="text-slate-400 dark:text-gray-500">Cumplimiento entregas</span><span className={`font-bold ${compColor}`}>{sup.deliveryCompliance}%</span></div>
                <div className="flex justify-between"><span className="text-slate-400 dark:text-gray-500">NCRs registrados</span><span className={`font-bold ${sup.ncrs > 0 ? 'text-red-500' : 'text-emerald-600 dark:text-emerald-400'}`}>{sup.ncrs}</span></div>
                <div className="flex justify-between"><span className="text-slate-400 dark:text-gray-500">Contacto</span><span className="text-slate-600 dark:text-gray-300">{sup.contact}</span></div>
                {sup.email && <div className="flex justify-between"><span className="text-slate-400 dark:text-gray-500">Email</span><span className="text-slate-600 dark:text-gray-300 truncate ml-4">{sup.email}</span></div>}
              </div>
            </div>
          );
        })}
      </div>

      {showCSV && <CSVImportModal onImport={handleImport} onClose={()=>setShowCSV(false)}/>}
    </div>
  );
}

// ── Tab: Tareas de Compras ────────────────────────────────────────────────────
function TabTareasCompras() {
  const memberMap = Object.fromEntries(MOCK_TEAM.map(m => [m.id, m]));
  const SUBTASK_STATUS = ['COMPLETADA','COMPLETADA','EN_PROCESO','PENDIENTE','PENDIENTE'];

  return (
    <div className="space-y-4">
      <div className="flex items-center gap-2 bg-violet-50 dark:bg-violet-500/10 border border-violet-100 dark:border-violet-500/20 rounded-xl px-4 py-2.5">
        <svg className="w-4 h-4 text-violet-500 flex-shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>
        <p className="text-xs text-violet-700 dark:text-violet-300">
          Cada RFQ genera automáticamente una tarea de gestión asignada al <strong>Departamento de Compras</strong>. Estas tareas también aparecen en el Gantt y Kanban del proyecto.
        </p>
      </div>

      <div className="space-y-3">
        {PROCUREMENT_TASKS.map((pt, idx) => {
          const rfq      = MOCK_RFQS.find(r => r.code === pt.rfqCode);
          const assignee = memberMap[pt.assignedTo] || DEFAULT_PURCHASER;
          const done     = pt.subtasks.filter((_,i) => SUBTASK_STATUS[i] === 'COMPLETADA').length;
          const pct      = Math.round((done / pt.subtasks.length) * 100);
          return (
            <div key={idx} className="bg-slate-50 dark:bg-surface-700 rounded-xl p-4 border border-slate-100 dark:border-surface-600">
              <div className="flex items-start justify-between gap-3 mb-3">
                <div className="flex items-center gap-2">
                  <div className="w-8 h-8 rounded-lg bg-violet-100 dark:bg-violet-500/20 flex items-center justify-center flex-shrink-0">
                    <svg className="w-4 h-4 text-violet-600 dark:text-violet-400" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"/></svg>
                  </div>
                  <div>
                    <p className="text-sm font-semibold text-slate-800 dark:text-gray-200">Gestionar {pt.rfqCode}</p>
                    {rfq && <p className="text-xs text-slate-400 dark:text-gray-500">{rfq.material} · {rfq.projectCode}</p>}
                  </div>
                </div>
                <div className="flex items-center gap-2">
                  <Avatar member={assignee}/>
                  <Badge
                    label={pt.status.replace(/_/g,' ')}
                    color={pt.status === 'COMPLETADA' ? 'bg-emerald-100 text-emerald-700 dark:bg-emerald-500/20 dark:text-emerald-400' : 'bg-blue-100 text-blue-700 dark:bg-blue-500/20 dark:text-blue-400'}
                  />
                </div>
              </div>

              {/* Progress */}
              <div className="flex items-center gap-3 mb-3">
                <div className="flex-1 h-1.5 bg-slate-200 dark:bg-surface-600 rounded-full overflow-hidden">
                  <div className="h-full bg-blue-500 rounded-full transition-all" style={{ width:`${pct}%` }}/>
                </div>
                <span className="text-xs text-slate-500 dark:text-gray-400 tabular-nums">{done}/{pt.subtasks.length}</span>
              </div>

              {/* Subtasks */}
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-1.5">
                {pt.subtasks.map((sub, si) => {
                  const st = SUBTASK_STATUS[si] || 'PENDIENTE';
                  return (
                    <div key={si} className="flex items-center gap-2">
                      <div className={`w-4 h-4 rounded-full flex items-center justify-center flex-shrink-0 ${st === 'COMPLETADA' ? 'bg-emerald-500' : st === 'EN_PROCESO' ? 'bg-blue-500' : 'bg-slate-200 dark:bg-surface-600'}`}>
                        {st === 'COMPLETADA' && <svg className="w-2.5 h-2.5 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={3}><path strokeLinecap="round" strokeLinejoin="round" d="M5 13l4 4L19 7"/></svg>}
                        {st === 'EN_PROCESO' && <div className="w-1.5 h-1.5 rounded-full bg-white"/>}
                      </div>
                      <span className={`text-xs ${TASK_STATUS_COLOR[st]}`}>{sub}</span>
                    </div>
                  );
                })}
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

// ── Icons ─────────────────────────────────────────────────────────────────────
const IconRFQ      = () => <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.75}><path strokeLinecap="round" strokeLinejoin="round" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"/></svg>;
const IconAI       = () => <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.75}><path strokeLinecap="round" strokeLinejoin="round" d="M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z"/></svg>;
const IconPO       = () => <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.75}><path strokeLinecap="round" strokeLinejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"/></svg>;
const IconMeeting  = () => <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.75}><path strokeLinecap="round" strokeLinejoin="round" d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0z"/></svg>;
const IconSupplier = () => <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.75}><path strokeLinecap="round" strokeLinejoin="round" d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4"/></svg>;
const IconTasks    = () => <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.75}><path strokeLinecap="round" strokeLinejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2M9 12l2 2 4-4"/></svg>;

const TABS = [
  { id:'rfqs',        label:'RFQs',            Icon: IconRFQ      },
  { id:'evaluacion',  label:'Evaluación IA',   Icon: IconAI       },
  { id:'pos',         label:'Órd. de Compra',  Icon: IconPO       },
  { id:'juntas',      label:'Juntas',          Icon: IconMeeting  },
  { id:'tareas',      label:'Tareas Compras',  Icon: IconTasks    },
  { id:'proveedores', label:'Proveedores',     Icon: IconSupplier },
];

// ── Main Page ─────────────────────────────────────────────────────────────────
export default function ProcurementPage() {
  const { selectedProjectId } = useProject();
  const [tab,          setTab]          = useState('rfqs');
  const [selectedRFQ,  setSelectedRFQ]  = useState(null);
  const [meetingModal, setMeetingModal] = useState(null);

  const rfqs     = useMemo(() => MOCK_RFQS.filter(r => !selectedProjectId || r.projectId === selectedProjectId), [selectedProjectId]);
  const pos      = useMemo(() => MOCK_POS.filter(p => !selectedProjectId || p.projectId === selectedProjectId), [selectedProjectId]);
  const meetings = useMemo(() => MOCK_MEETINGS.filter(m => !selectedProjectId || m.projectId === selectedProjectId), [selectedProjectId]);

  const openRFQCount   = rfqs.filter(r => r.status === 'OPEN').length;
  const draftPOCount   = pos.filter(p => p.status === 'DRAFT').length;
  const totalCommitted = pos.reduce((s, p) => s + p.total, 0);
  const pendingMeeting = meetings.find(m => !m.minutesGenerated);

  const handleSelectRFQ  = (rfq) => { setSelectedRFQ(rfq); setTab('evaluacion'); };
  const handleOpenMeeting = (m)  => setMeetingModal(m);

  return (
    <div className="flex flex-col gap-4">
      {/* Header */}
      <div className="flex items-start justify-between gap-3 flex-wrap">
        <div>
          <h1 className="text-lg font-bold text-slate-900 dark:text-white">Abastecimiento</h1>
          <p className="text-sm text-slate-400 dark:text-gray-500 mt-0.5">RFQs · Evaluación IA · Órdenes de Compra · Juntas · Proveedores</p>
        </div>
        <div className="flex items-center gap-2 flex-wrap">
          <div className="flex items-center gap-2 bg-slate-50 dark:bg-surface-700 border border-slate-200 dark:border-surface-600 rounded-xl px-3 py-2">
            <Avatar member={DEFAULT_PURCHASER}/>
            <div>
              <p className="text-xs font-semibold text-slate-700 dark:text-gray-300">{DEFAULT_PURCHASER.firstName} {DEFAULT_PURCHASER.lastName}</p>
              <p className="text-xs text-slate-400 dark:text-gray-500">Resp. Compras por defecto</p>
            </div>
          </div>
          {pendingMeeting && (
            <div className="flex items-center gap-2 bg-amber-50 dark:bg-amber-500/10 border border-amber-200 dark:border-amber-500/20 rounded-xl px-3 py-2">
              <svg className="w-4 h-4 text-amber-500" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>
              <p className="text-xs text-amber-700 dark:text-amber-300">
                <strong>{pendingMeeting.code}</strong> — acta pendiente
              </p>
            </div>
          )}
        </div>
      </div>

      {/* KPIs */}
      <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
        {[
          { label:'RFQs abiertas',       val: openRFQCount,           color:'text-blue-600 dark:text-blue-400',       bg:'bg-blue-50 dark:bg-blue-500/10' },
          { label:'POs borrador',        val: draftPOCount,           color:'text-amber-600 dark:text-amber-400',     bg:'bg-amber-50 dark:bg-amber-500/10' },
          { label:'Valor comprometido',  val: fmtCOP(totalCommitted), color:'text-emerald-600 dark:text-emerald-400', bg:'bg-emerald-50 dark:bg-emerald-500/10' },
          { label:'Última junta',        val: MOCK_MEETINGS[0]?.code || '—', color:'text-violet-600 dark:text-violet-400', bg:'bg-violet-50 dark:bg-violet-500/10' },
        ].map(({ label, val, color, bg }) => (
          <div key={label} className={`${bg} rounded-xl p-4 border border-slate-100 dark:border-surface-600`}>
            <p className="text-xs text-slate-500 dark:text-gray-400 mb-1">{label}</p>
            <p className={`text-lg font-bold tabular-nums ${color}`}>{val}</p>
          </div>
        ))}
      </div>

      {/* Tabs */}
      <div className="bg-white dark:bg-surface-800 rounded-2xl border border-slate-200 dark:border-surface-700 shadow-sm overflow-hidden">
        <div className="flex border-b border-slate-100 dark:border-surface-700 px-4 gap-0.5 overflow-x-auto">
          {TABS.map(t => (
            <button key={t.id} onClick={() => setTab(t.id)}
              className={`flex items-center gap-1.5 px-4 py-3.5 text-sm font-medium whitespace-nowrap border-b-2 transition-colors cursor-pointer ${
                tab === t.id
                  ? 'border-blue-600 text-blue-700 dark:text-blue-400'
                  : 'border-transparent text-slate-500 dark:text-gray-400 hover:text-slate-700 dark:hover:text-gray-200'
              }`}>
              <t.Icon/>
              {t.label}
              {t.id === 'rfqs'  && openRFQCount > 0 && <span className="ml-1 bg-blue-600 text-white text-xs rounded-full px-1.5 py-0.5 font-bold leading-none">{openRFQCount}</span>}
              {t.id === 'pos'   && draftPOCount > 0 && <span className="ml-1 bg-amber-500 text-white text-xs rounded-full px-1.5 py-0.5 font-bold leading-none">{draftPOCount}</span>}
            </button>
          ))}
        </div>

        <div className="p-6">
          {tab === 'rfqs'        && <TabRFQs         rfqs={rfqs}     onSelectRFQ={handleSelectRFQ}/>}
          {tab === 'evaluacion'  && <TabEvaluacion   rfqs={rfqs}     selectedRFQ={selectedRFQ} onSelectRFQ={setSelectedRFQ}/>}
          {tab === 'pos'         && <TabPOs          pos={pos}       onOpenMeeting={handleOpenMeeting}/>}
          {tab === 'juntas'      && <TabJuntas       meetings={meetings} onOpenMeeting={handleOpenMeeting}/>}
          {tab === 'tareas'      && <TabTareasCompras/>}
          {tab === 'proveedores' && <TabProveedores/>}
        </div>
      </div>

      {/* Meeting minutes modal */}
      {meetingModal && <MeetingMinutesModal meeting={meetingModal} onClose={() => setMeetingModal(null)}/>}
    </div>
  );
}
