import { useState } from 'react';
import { PieChart, Pie, Cell, Tooltip, ResponsiveContainer, BarChart, Bar, XAxis, YAxis, CartesianGrid, Legend, LineChart, Line } from 'recharts';

const MOCK_BIDS = [
  { id:'LIC-2026-001', title:'Construcción sede administrativa Empresa X', client:'Empresa X S.A.',
    type:'LICITACION_PUBLICA', value:1200000000, currency:'COP', submissionDate:'2026-07-30',
    status:'EN_PREPARACION', probability:60, owner:'Paula Soto', team:['Álvaro Romero','Álvaro Romero'],
    category:'CONSTRUCCION', description:'Edificio 6 pisos 3.200m² en zona norte',
    createdAt:'2026-06-01', notes:'' },
  { id:'LIC-2026-002', title:'Sistema de automatización planta láctea', client:'Lácteos del Valle S.A.S.',
    type:'INVITACION_DIRECTA', value:380000000, currency:'COP', submissionDate:'2026-07-15',
    status:'ENVIADA', probability:75, owner:'Ricardo Mora', team:['Paula Soto'],
    category:'INDUSTRIAL', description:'Sistema SCADA y PLCs para línea de producción',
    createdAt:'2026-05-20', notes:'Reunión técnica 2026-07-08 a las 10am' },
  { id:'LIC-2026-003', title:'ERP para empresa distribuidora', client:'Distribuciones Central Ltda.',
    type:'INVITACION_DIRECTA', value:145000000, currency:'COP', submissionDate:'2026-06-20',
    status:'GANADA', probability:100, owner:'Ricardo Mora', team:['Paula Soto'],
    category:'TI', description:'ERP módulos ventas, inventario y contabilidad',
    createdAt:'2026-05-01', notes:'' },
  { id:'LIC-2026-004', title:'Diseño subestación eléctrica industria minera', client:'Minera Andina Corp.',
    type:'LICITACION_PRIVADA', value:650000000, currency:'COP', submissionDate:'2026-08-10',
    status:'EN_PREPARACION', probability:40, owner:'Carmen Vidal', team:['Álvaro Romero'],
    category:'INDUSTRIAL', description:'Subestación 115/13.2kV, 20MVA',
    createdAt:'2026-06-10', notes:'' },
  { id:'LIC-2026-005', title:'Red de datos campus universitario', client:'Universidad del Norte',
    type:'LICITACION_PUBLICA', value:280000000, currency:'COP', submissionDate:'2026-06-10',
    status:'PERDIDA', probability:0, owner:'Jorge Salcedo', team:[],
    category:'TI', description:'Infraestructura de red fibra óptica y WiFi',
    createdAt:'2026-04-15', notes:'Perdida por precio. Competidor ofreció 15% menos.',
    lossReason:'Precio más alto', winnerPrice:238000000, lessonsLearned:'Revisar estructura de costos overhead. Negociar mejores precios con proveedores de equipos.' },
  { id:'LIC-2026-006', title:'Automatización almacén logístico', client:'LogiCarga S.A.S.',
    type:'LICITACION_PRIVADA', value:520000000, currency:'COP', submissionDate:'2026-03-15',
    status:'PERDIDA', probability:0, owner:'Paula Soto', team:['Álvaro Romero'],
    category:'INDUSTRIAL', description:'Sistema WMS y transportadores automáticos',
    createdAt:'2026-02-01', notes:'Propuesta técnica débil en comparación.',
    lossReason:'Propuesta técnica débil', winnerPrice:495000000, lessonsLearned:'Incluir más casos de éxito similares. Reforzar el equipo técnico de la propuesta.' },
  { id:'LIC-2026-007', title:'Plataforma e-learning para municipio', client:'Municipio de Sabaneta',
    type:'LICITACION_PUBLICA', value:95000000, currency:'COP', submissionDate:'2026-01-31',
    status:'PERDIDA', probability:0, owner:'Jorge Salcedo', team:[],
    category:'TI', description:'LMS con contenidos educativos',
    createdAt:'2025-12-10', notes:'Presentación tarde por problemas administrativos.',
    lossReason:'Presentación tarde', winnerPrice:88000000, lessonsLearned:'Establecer proceso de revisión legal con 10 días de anticipación.' },
];

const TEAM_MEMBERS = ['Paula Soto', 'Ricardo Mora', 'Carmen Vidal', 'Jorge Salcedo', 'Álvaro Romero', 'Álvaro Romero', 'Paula Soto'];

const WIN_RATE_TREND = [
  { quarter: 'Q3 2025', winRate: 45, avgValue: 210 },
  { quarter: 'Q4 2025', winRate: 52, avgValue: 285 },
  { quarter: 'Q1 2026', winRate: 38, avgValue: 320 },
  { quarter: 'Q2 2026', winRate: 50, avgValue: 395 },
];

const MONTHLY_WIN_LOSS = [
  { mes: 'Jul', ganadas: 1, perdidas: 0 },
  { mes: 'Ago', ganadas: 0, perdidas: 1 },
  { mes: 'Sep', ganadas: 2, perdidas: 0 },
  { mes: 'Oct', ganadas: 1, perdidas: 1 },
  { mes: 'Nov', ganadas: 0, perdidas: 2 },
  { mes: 'Dic', ganadas: 1, perdidas: 0 },
  { mes: 'Ene', ganadas: 0, perdidas: 1 },
  { mes: 'Feb', ganadas: 2, perdidas: 1 },
  { mes: 'Mar', ganadas: 1, perdidas: 0 },
  { mes: 'Abr', ganadas: 0, perdidas: 1 },
  { mes: 'May', ganadas: 1, perdidas: 0 },
  { mes: 'Jun', ganadas: 1, perdidas: 1 },
];

const LOSS_REASONS = [
  { name: 'Precio más alto', value: 40, fill: '#ef4444' },
  { name: 'Propuesta técnica débil', value: 25, fill: '#f59e0b' },
  { name: 'Experiencia insuficiente', value: 20, fill: '#8b5cf6' },
  { name: 'Presentación tarde', value: 10, fill: '#3b82f6' },
  { name: 'Otro', value: 5, fill: '#94a3b8' },
];

const FUNNEL_DATA = [
  { stage: 'Identificadas', count: 24 },
  { stage: 'Calificadas', count: 16 },
  { stage: 'Propuesta enviada', count: 10 },
  { stage: 'Ganadas', count: 5 },
];

const formatCOP = (v) => new Intl.NumberFormat('es-CO', { style:'currency', currency:'COP', maximumFractionDigits:0 }).format(v);

const daysUntil = (dateStr) => {
  const diff = new Date(dateStr) - new Date('2026-06-26');
  return Math.ceil(diff / (1000 * 60 * 60 * 24));
};

const statusBadge = (s) => {
  const map = {
    EN_PREPARACION: 'bg-slate-100 text-slate-600 dark:bg-slate-700 dark:text-slate-300',
    ENVIADA: 'bg-blue-100 text-blue-700 dark:bg-blue-900/40 dark:text-blue-300',
    GANADA: 'bg-emerald-100 text-emerald-700 dark:bg-emerald-900/40 dark:text-emerald-300',
    PERDIDA: 'bg-red-100 text-red-700 dark:bg-red-900/40 dark:text-red-300',
    DESCARTADA: 'bg-gray-100 text-gray-500 dark:bg-gray-800 dark:text-gray-400',
    CONVERTIDA: 'bg-violet-100 text-violet-700 dark:bg-violet-900/40 dark:text-violet-300',
  };
  const labels = { EN_PREPARACION:'En preparación', ENVIADA:'Enviada', GANADA:'Ganada', PERDIDA:'Perdida', DESCARTADA:'Descartada', CONVERTIDA:'Convertida' };
  return <span className={`px-2 py-0.5 rounded-full text-xs font-medium ${map[s] || 'bg-slate-100 text-slate-600'}`}>{labels[s] || s}</span>;
};

const typeBadge = (t) => {
  const map = {
    LICITACION_PUBLICA: 'bg-purple-100 text-purple-700 dark:bg-purple-900/40 dark:text-purple-300',
    LICITACION_PRIVADA: 'bg-indigo-100 text-indigo-700 dark:bg-indigo-900/40 dark:text-indigo-300',
    INVITACION_DIRECTA: 'bg-teal-100 text-teal-700 dark:bg-teal-900/40 dark:text-teal-300',
  };
  const labels = { LICITACION_PUBLICA:'Lic. pública', LICITACION_PRIVADA:'Lic. privada', INVITACION_DIRECTA:'Inv. directa' };
  return <span className={`px-2 py-0.5 rounded-full text-xs font-medium ${map[t] || 'bg-slate-100 text-slate-600'}`}>{labels[t] || t}</span>;
};

function Modal({ title, onClose, children }) {
  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-sm p-4">
      <div className="bg-white dark:bg-slate-800 rounded-2xl shadow-2xl w-full max-w-2xl max-h-[90vh] overflow-y-auto border border-slate-200 dark:border-slate-700">
        <div className="flex items-center justify-between px-6 py-4 border-b border-slate-200 dark:border-slate-700">
          <h2 className="text-lg font-semibold text-slate-800 dark:text-slate-100">{title}</h2>
          <button onClick={onClose} className="text-slate-400 hover:text-slate-600 dark:hover:text-slate-200 text-2xl leading-none">&times;</button>
        </div>
        <div className="px-6 py-5">{children}</div>
      </div>
    </div>
  );
}

function BidDetailModal({ bid, onClose }) {
  const [form, setForm] = useState({ ...bid });
  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));
  return (
    <Modal title={`${bid.id} — ${bid.title}`} onClose={onClose}>
      <div className="space-y-4 text-sm">
        <div className="grid grid-cols-2 gap-4">
          <div className="col-span-2">
            <label className="block text-slate-500 dark:text-slate-400 mb-1 font-medium">Título</label>
            <input value={form.title} onChange={e => set('title', e.target.value)}
              className="w-full rounded-xl border border-slate-200 dark:border-slate-600 bg-slate-50 dark:bg-slate-700 text-slate-800 dark:text-slate-100 px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-400" />
          </div>
          <div>
            <label className="block text-slate-500 dark:text-slate-400 mb-1 font-medium">Cliente</label>
            <input value={form.client} onChange={e => set('client', e.target.value)}
              className="w-full rounded-xl border border-slate-200 dark:border-slate-600 bg-slate-50 dark:bg-slate-700 text-slate-800 dark:text-slate-100 px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-400" />
          </div>
          <div>
            <label className="block text-slate-500 dark:text-slate-400 mb-1 font-medium">Tipo</label>
            <select value={form.type} onChange={e => set('type', e.target.value)}
              className="w-full rounded-xl border border-slate-200 dark:border-slate-600 bg-slate-50 dark:bg-slate-700 text-slate-800 dark:text-slate-100 px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-400">
              <option value="LICITACION_PUBLICA">Licitación pública</option>
              <option value="LICITACION_PRIVADA">Licitación privada</option>
              <option value="INVITACION_DIRECTA">Invitación directa</option>
            </select>
          </div>
          <div>
            <label className="block text-slate-500 dark:text-slate-400 mb-1 font-medium">Estado</label>
            <select value={form.status} onChange={e => set('status', e.target.value)}
              className="w-full rounded-xl border border-slate-200 dark:border-slate-600 bg-slate-50 dark:bg-slate-700 text-slate-800 dark:text-slate-100 px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-400">
              <option value="EN_PREPARACION">En preparación</option>
              <option value="ENVIADA">Enviada</option>
              <option value="GANADA">Ganada</option>
              <option value="PERDIDA">Perdida</option>
              <option value="DESCARTADA">Descartada</option>
            </select>
          </div>
          <div>
            <label className="block text-slate-500 dark:text-slate-400 mb-1 font-medium">Categoría</label>
            <input value={form.category} onChange={e => set('category', e.target.value)}
              className="w-full rounded-xl border border-slate-200 dark:border-slate-600 bg-slate-50 dark:bg-slate-700 text-slate-800 dark:text-slate-100 px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-400" />
          </div>
          <div>
            <label className="block text-slate-500 dark:text-slate-400 mb-1 font-medium">Valor estimado (COP)</label>
            <input type="number" value={form.value} onChange={e => set('value', Number(e.target.value))}
              className="w-full rounded-xl border border-slate-200 dark:border-slate-600 bg-slate-50 dark:bg-slate-700 text-slate-800 dark:text-slate-100 px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-400" />
          </div>
          <div>
            <label className="block text-slate-500 dark:text-slate-400 mb-1 font-medium">Fecha límite entrega</label>
            <input type="date" value={form.submissionDate} onChange={e => set('submissionDate', e.target.value)}
              className="w-full rounded-xl border border-slate-200 dark:border-slate-600 bg-slate-50 dark:bg-slate-700 text-slate-800 dark:text-slate-100 px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-400" />
          </div>
          <div>
            <label className="block text-slate-500 dark:text-slate-400 mb-1 font-medium">Probabilidad: {form.probability}%</label>
            <input type="range" min={0} max={100} value={form.probability} onChange={e => set('probability', Number(e.target.value))}
              className="w-full accent-blue-600" />
          </div>
          <div>
            <label className="block text-slate-500 dark:text-slate-400 mb-1 font-medium">Responsable</label>
            <input value={form.owner} onChange={e => set('owner', e.target.value)}
              className="w-full rounded-xl border border-slate-200 dark:border-slate-600 bg-slate-50 dark:bg-slate-700 text-slate-800 dark:text-slate-100 px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-400" />
          </div>
          <div className="col-span-2">
            <label className="block text-slate-500 dark:text-slate-400 mb-1 font-medium">Descripción</label>
            <textarea value={form.description} onChange={e => set('description', e.target.value)} rows={3}
              className="w-full rounded-xl border border-slate-200 dark:border-slate-600 bg-slate-50 dark:bg-slate-700 text-slate-800 dark:text-slate-100 px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-400" />
          </div>
          <div className="col-span-2">
            <label className="block text-slate-500 dark:text-slate-400 mb-1 font-medium">Notas internas</label>
            <textarea value={form.notes} onChange={e => set('notes', e.target.value)} rows={2}
              className="w-full rounded-xl border border-slate-200 dark:border-slate-600 bg-slate-50 dark:bg-slate-700 text-slate-800 dark:text-slate-100 px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-400" />
          </div>
        </div>
        <div className="flex justify-end gap-2 pt-2">
          <button onClick={onClose} className="px-4 py-2 rounded-xl border border-slate-200 dark:border-slate-600 text-slate-600 dark:text-slate-300 hover:bg-slate-50 dark:hover:bg-slate-700 text-sm">Cancelar</button>
          <button onClick={onClose} className="px-4 py-2 rounded-xl bg-blue-600 hover:bg-blue-700 text-white text-sm font-medium">Guardar cambios</button>
        </div>
      </div>
    </Modal>
  );
}

function ConvertModal({ bid, onClose, onConverted }) {
  const [form, setForm] = useState({
    name: bid.title,
    client: bid.client,
    value: bid.value,
    type: bid.type,
    startDate: '',
    endDate: '',
    methodology: 'PMI',
    gerente: bid.owner || '',
  });
  const [success, setSuccess] = useState(false);
  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));

  const handleCreate = () => {
    if (!form.startDate || !form.endDate || !form.gerente) return;
    setSuccess(true);
    setTimeout(() => {
      onConverted(bid.id);
      onClose();
    }, 2000);
  };

  if (success) {
    return (
      <Modal title="Proyecto creado" onClose={onClose}>
        <div className="flex flex-col items-center py-8 gap-4">
          <div className="w-16 h-16 bg-emerald-100 dark:bg-emerald-900/40 rounded-full flex items-center justify-center">
            <svg className="w-8 h-8 text-emerald-600 dark:text-emerald-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
            </svg>
          </div>
          <p className="text-lg font-semibold text-slate-800 dark:text-slate-100">Proyecto PRY-2026-005 creado exitosamente</p>
          <p className="text-sm text-slate-500 dark:text-slate-400">Redirigiendo al pipeline...</p>
        </div>
      </Modal>
    );
  }

  return (
    <Modal title={`Convertir en Proyecto — ${bid.id}`} onClose={onClose}>
      <div className="space-y-4 text-sm">
        <div className="bg-emerald-50 dark:bg-emerald-900/20 border border-emerald-200 dark:border-emerald-800 rounded-xl p-4 mb-2">
          <p className="text-xs font-semibold text-emerald-700 dark:text-emerald-400 uppercase mb-1">Datos de la licitación</p>
          <p className="text-slate-700 dark:text-slate-200 font-medium">{bid.title}</p>
          <p className="text-slate-500 dark:text-slate-400 text-xs mt-0.5">{bid.client} · {formatCOP(bid.value)}</p>
        </div>
        <div className="grid grid-cols-2 gap-4">
          <div className="col-span-2">
            <label className="block text-slate-500 dark:text-slate-400 mb-1 font-medium">Nombre del proyecto</label>
            <input value={form.name} onChange={e => set('name', e.target.value)}
              className="w-full rounded-xl border border-slate-200 dark:border-slate-600 bg-slate-50 dark:bg-slate-700 text-slate-800 dark:text-slate-100 px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-400" />
          </div>
          <div>
            <label className="block text-slate-500 dark:text-slate-400 mb-1 font-medium">Fecha de inicio *</label>
            <input type="date" value={form.startDate} onChange={e => set('startDate', e.target.value)}
              className="w-full rounded-xl border border-slate-200 dark:border-slate-600 bg-slate-50 dark:bg-slate-700 text-slate-800 dark:text-slate-100 px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-400" />
          </div>
          <div>
            <label className="block text-slate-500 dark:text-slate-400 mb-1 font-medium">Fecha de finalización *</label>
            <input type="date" value={form.endDate} onChange={e => set('endDate', e.target.value)}
              className="w-full rounded-xl border border-slate-200 dark:border-slate-600 bg-slate-50 dark:bg-slate-700 text-slate-800 dark:text-slate-100 px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-400" />
          </div>
          <div>
            <label className="block text-slate-500 dark:text-slate-400 mb-1 font-medium">Metodología</label>
            <select value={form.methodology} onChange={e => set('methodology', e.target.value)}
              className="w-full rounded-xl border border-slate-200 dark:border-slate-600 bg-slate-50 dark:bg-slate-700 text-slate-800 dark:text-slate-100 px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-400">
              <option value="PMI">PMI</option>
              <option value="Scrum">Scrum</option>
              <option value="Agile">Agile</option>
            </select>
          </div>
          <div>
            <label className="block text-slate-500 dark:text-slate-400 mb-1 font-medium">Gerente de proyecto *</label>
            <select value={form.gerente} onChange={e => set('gerente', e.target.value)}
              className="w-full rounded-xl border border-slate-200 dark:border-slate-600 bg-slate-50 dark:bg-slate-700 text-slate-800 dark:text-slate-100 px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-400">
              <option value="">Seleccionar...</option>
              {TEAM_MEMBERS.map(m => <option key={m} value={m}>{m}</option>)}
            </select>
          </div>
          <div>
            <label className="block text-slate-500 dark:text-slate-400 mb-1 font-medium">Valor del contrato</label>
            <input value={formatCOP(form.value)} readOnly
              className="w-full rounded-xl border border-slate-100 dark:border-slate-700 bg-slate-100 dark:bg-slate-800 text-slate-600 dark:text-slate-400 px-3 py-2 cursor-not-allowed" />
          </div>
        </div>
        <div className="flex justify-end gap-2 pt-2">
          <button onClick={onClose} className="px-4 py-2 rounded-xl border border-slate-200 dark:border-slate-600 text-slate-600 dark:text-slate-300 hover:bg-slate-50 dark:hover:bg-slate-700 text-sm">Cancelar</button>
          <button onClick={handleCreate}
            disabled={!form.startDate || !form.endDate || !form.gerente}
            className="px-5 py-2 rounded-xl bg-emerald-600 hover:bg-emerald-700 disabled:opacity-40 disabled:cursor-not-allowed text-white text-sm font-medium">
            Crear Proyecto
          </button>
        </div>
      </div>
    </Modal>
  );
}

const TABS = ['Pipeline', 'Nueva propuesta', 'Análisis', 'Análisis de Pérdidas'];

const STATUS_COLORS = {
  EN_PREPARACION: '#94a3b8',
  ENVIADA: '#3b82f6',
  GANADA: '#10b981',
  PERDIDA: '#ef4444',
  DESCARTADA: '#6b7280',
  CONVERTIDA: '#8b5cf6',
};

const CATEGORY_COLORS = ['#3b82f6', '#10b981', '#f59e0b', '#8b5cf6', '#ef4444'];

export default function BidsPage() {
  const [activeTab, setActiveTab] = useState(0);
  const [selectedBid, setSelectedBid] = useState(null);
  const [convertBid, setConvertBid] = useState(null);
  const [bids, setBids] = useState(MOCK_BIDS);
  const [newForm, setNewForm] = useState({
    title: '', client: '', type: 'LICITACION_PUBLICA', category: 'CONSTRUCCION',
    value: '', currency: 'COP', submissionDate: '', probability: 50,
    owner: '', description: '', notes: '',
  });
  const setF = (k, v) => setNewForm(f => ({ ...f, [k]: v }));

  const enPreparacion = bids.filter(b => b.status === 'EN_PREPARACION').length;
  const enviadas = bids.filter(b => b.status === 'ENVIADA').length;
  const ganadas = bids.filter(b => b.status === 'GANADA').length;
  const valorPipeline = bids.filter(b => !['PERDIDA','DESCARTADA'].includes(b.status)).reduce((a, b) => a + b.value, 0);
  const closedBids = bids.filter(b => ['GANADA','PERDIDA','CONVERTIDA'].includes(b.status));
  const wonBids = bids.filter(b => ['GANADA','CONVERTIDA'].includes(b.status));
  const tasaExito = closedBids.length > 0
    ? Math.round((wonBids.length / closedBids.length) * 100)
    : 0;

  const pieData = Object.entries(
    bids.reduce((acc, b) => { acc[b.status] = (acc[b.status] || 0) + 1; return acc; }, {})
  ).map(([name, value]) => ({ name, value }));

  const barData = Object.entries(
    bids.reduce((acc, b) => { acc[b.category] = (acc[b.category] || 0) + b.value; return acc; }, {})
  ).map(([name, value]) => ({ name, value }));

  const valorGanado = wonBids.reduce((a, b) => a + b.value, 0);
  const lostBids = bids.filter(b => b.status === 'PERDIDA');
  const valorPerdido = lostBids.reduce((a, b) => a + b.value, 0);

  const handleCreate = () => {
    if (!newForm.title || !newForm.client) return;
    const id = `LIC-2026-00${bids.length + 1}`;
    setBids(prev => [...prev, { ...newForm, id, status: 'EN_PREPARACION', team: [], createdAt: '2026-06-26', value: Number(newForm.value) || 0 }]);
    setNewForm({ title:'', client:'', type:'LICITACION_PUBLICA', category:'CONSTRUCCION', value:'', currency:'COP', submissionDate:'', probability:50, owner:'', description:'', notes:'' });
    setActiveTab(0);
  };

  const handleConverted = (bidId) => {
    setBids(prev => prev.map(b => b.id === bidId ? { ...b, status: 'CONVERTIDA' } : b));
  };

  // Loss analysis KPIs
  const principalCausa = lostBids.length > 0
    ? lostBids.reduce((acc, b) => {
        if (b.lossReason) acc[b.lossReason] = (acc[b.lossReason] || 0) + 1;
        return acc;
      }, {})
    : {};
  const topCausa = Object.entries(principalCausa).sort((a,b) => b[1]-a[1])[0]?.[0] || 'N/A';

  return (
    <div className="min-h-screen bg-slate-50 dark:bg-slate-900 p-6">
      <div className="max-w-7xl mx-auto">
        {/* Header */}
        <div className="mb-6">
          <h1 className="text-2xl font-bold text-slate-800 dark:text-slate-100">Licitaciones y Propuestas</h1>
          <p className="text-slate-500 dark:text-slate-400 text-sm mt-1">Gestión del pipeline de oportunidades comerciales</p>
        </div>

        {/* Tabs */}
        <div className="flex gap-1 mb-6 bg-slate-100 dark:bg-slate-800 p-1 rounded-2xl w-fit flex-wrap">
          {TABS.map((tab, i) => (
            <button key={i} onClick={() => setActiveTab(i)}
              className={`px-4 py-2 rounded-xl text-sm font-medium transition-all ${activeTab === i ? 'bg-white dark:bg-slate-700 text-slate-800 dark:text-slate-100 shadow-sm' : 'text-slate-500 dark:text-slate-400 hover:text-slate-700 dark:hover:text-slate-200'}`}>
              {tab}
            </button>
          ))}
        </div>

        {/* Tab 0: Pipeline */}
        {activeTab === 0 && (
          <div className="space-y-5">
            {/* KPIs */}
            <div className="grid grid-cols-2 md:grid-cols-5 gap-4">
              {[
                { label:'En preparación', value: enPreparacion, color:'text-slate-600 dark:text-slate-300' },
                { label:'Enviadas', value: enviadas, color:'text-blue-600 dark:text-blue-400' },
                { label:'Ganadas', value: ganadas, color:'text-emerald-600 dark:text-emerald-400' },
                { label:'Valor pipeline', value: formatCOP(valorPipeline), color:'text-slate-700 dark:text-slate-100', small:true },
                { label:'Tasa de éxito', value: `${tasaExito}%`, color:'text-emerald-600 dark:text-emerald-400' },
              ].map((k, i) => (
                <div key={i} className="bg-white dark:bg-slate-800 rounded-2xl border border-slate-200 dark:border-slate-700 p-4">
                  <p className="text-xs text-slate-500 dark:text-slate-400 mb-1">{k.label}</p>
                  <p className={`font-bold ${k.color} ${k.small ? 'text-lg' : 'text-3xl'}`}>{k.value}</p>
                </div>
              ))}
            </div>

            {/* Win Rate Trend */}
            <div className="grid grid-cols-1 md:grid-cols-2 gap-5">
              <div className="bg-white dark:bg-slate-800 rounded-2xl border border-slate-200 dark:border-slate-700 p-5">
                <h3 className="font-semibold text-slate-800 dark:text-slate-100 mb-1">Tasa de éxito por trimestre</h3>
                <p className="text-xs text-slate-500 dark:text-slate-400 mb-4">Últimos 4 trimestres</p>
                <ResponsiveContainer width="100%" height={200}>
                  <LineChart data={WIN_RATE_TREND} margin={{ top: 5, right: 10, left: 0, bottom: 5 }}>
                    <CartesianGrid strokeDasharray="3 3" stroke="#e2e8f0" />
                    <XAxis dataKey="quarter" tick={{ fontSize: 11, fill: '#94a3b8' }} />
                    <YAxis tick={{ fontSize: 10, fill: '#94a3b8' }} tickFormatter={v => `${v}%`} domain={[0, 100]} />
                    <Tooltip formatter={(v, name) => [name === 'winRate' ? `${v}%` : `${v}M COP`, name === 'winRate' ? 'Win rate' : 'Valor promedio']} />
                    <Legend formatter={v => v === 'winRate' ? 'Win rate %' : 'Valor prom. (M)'} />
                    <Line type="monotone" dataKey="winRate" stroke="#10b981" strokeWidth={2} dot={{ fill: '#10b981', r: 4 }} />
                    <Line type="monotone" dataKey="avgValue" stroke="#3b82f6" strokeWidth={2} dot={{ fill: '#3b82f6', r: 4 }} strokeDasharray="5 5" />
                  </LineChart>
                </ResponsiveContainer>
              </div>

              {/* Conversion Funnel */}
              <div className="bg-white dark:bg-slate-800 rounded-2xl border border-slate-200 dark:border-slate-700 p-5">
                <h3 className="font-semibold text-slate-800 dark:text-slate-100 mb-1">Embudo de conversión</h3>
                <p className="text-xs text-slate-500 dark:text-slate-400 mb-4">Últimos 12 meses</p>
                <div className="space-y-3 mt-2">
                  {FUNNEL_DATA.map((stage, i) => {
                    const pct = Math.round((stage.count / FUNNEL_DATA[0].count) * 100);
                    const colors = ['bg-blue-500', 'bg-blue-400', 'bg-emerald-500', 'bg-emerald-600'];
                    return (
                      <div key={i}>
                        <div className="flex justify-between text-xs text-slate-600 dark:text-slate-300 mb-1">
                          <span className="font-medium">{stage.stage}</span>
                          <span>{stage.count} ({pct}%)</span>
                        </div>
                        <div className="w-full h-2.5 bg-slate-100 dark:bg-slate-700 rounded-full">
                          <div className={`h-2.5 ${colors[i]} rounded-full transition-all`} style={{ width: `${pct}%` }} />
                        </div>
                      </div>
                    );
                  })}
                </div>
                <p className="text-xs text-slate-400 dark:text-slate-500 mt-4">Conversión final: {Math.round((FUNNEL_DATA[3].count / FUNNEL_DATA[0].count) * 100)}% de identificadas a ganadas</p>
              </div>
            </div>

            {/* Table */}
            <div className="bg-white dark:bg-slate-800 rounded-2xl border border-slate-200 dark:border-slate-700 overflow-hidden">
              <div className="px-5 py-4 border-b border-slate-200 dark:border-slate-700">
                <h2 className="font-semibold text-slate-800 dark:text-slate-100">Todas las licitaciones</h2>
              </div>
              <div className="overflow-x-auto">
                <table className="w-full text-sm">
                  <thead>
                    <tr className="text-left text-slate-500 dark:text-slate-400 text-xs border-b border-slate-100 dark:border-slate-700">
                      <th className="px-5 py-3">ID</th>
                      <th className="px-5 py-3">Título</th>
                      <th className="px-5 py-3">Cliente</th>
                      <th className="px-5 py-3">Tipo</th>
                      <th className="px-5 py-3">Valor</th>
                      <th className="px-5 py-3">Probabilidad</th>
                      <th className="px-5 py-3">Vencimiento</th>
                      <th className="px-5 py-3">Estado</th>
                      <th className="px-5 py-3">Acciones</th>
                    </tr>
                  </thead>
                  <tbody>
                    {bids.map(bid => {
                      const days = daysUntil(bid.submissionDate);
                      return (
                        <tr key={bid.id} className="border-b border-slate-50 dark:border-slate-700/50 hover:bg-slate-50 dark:hover:bg-slate-700/30 transition-colors">
                          <td className="px-5 py-3 font-mono text-xs text-slate-500 dark:text-slate-400">{bid.id}</td>
                          <td className="px-5 py-3 text-slate-700 dark:text-slate-200 max-w-xs">
                            <div className="font-medium truncate max-w-[200px]">{bid.title}</div>
                            <div className="text-xs text-slate-400">{bid.category}</div>
                          </td>
                          <td className="px-5 py-3 text-slate-600 dark:text-slate-300 max-w-[140px] truncate">{bid.client}</td>
                          <td className="px-5 py-3">{typeBadge(bid.type)}</td>
                          <td className="px-5 py-3 text-slate-700 dark:text-slate-200 text-xs font-medium whitespace-nowrap">{formatCOP(bid.value)}</td>
                          <td className="px-5 py-3">
                            <div className="flex items-center gap-2">
                              <div className="w-16 h-1.5 bg-slate-100 dark:bg-slate-700 rounded-full">
                                <div className="h-1.5 bg-blue-500 rounded-full" style={{ width: `${bid.probability}%` }} />
                              </div>
                              <span className="text-xs text-slate-500 dark:text-slate-400">{bid.probability}%</span>
                            </div>
                          </td>
                          <td className="px-5 py-3">
                            <span className={`text-xs font-medium ${days < 10 && days > 0 ? 'text-red-600 dark:text-red-400' : days <= 0 ? 'text-slate-400' : 'text-slate-500 dark:text-slate-400'}`}>
                              {days > 0 ? `${days}d` : days === 0 ? 'Hoy' : 'Vencida'}
                            </span>
                          </td>
                          <td className="px-5 py-3">{statusBadge(bid.status)}</td>
                          <td className="px-5 py-3">
                            <div className="flex items-center gap-2 flex-wrap">
                              <button onClick={() => setSelectedBid(bid)} className="text-blue-600 dark:text-blue-400 hover:underline text-xs font-medium">Ver/Editar</button>
                              {bid.status === 'GANADA' && (
                                <button
                                  onClick={() => setConvertBid(bid)}
                                  className="bg-emerald-600 hover:bg-emerald-700 text-white rounded-lg px-2.5 py-1 text-xs font-medium whitespace-nowrap">
                                  Convertir en Proyecto
                                </button>
                              )}
                              {bid.status === 'CONVERTIDA' && (
                                <span className="text-violet-600 dark:text-violet-400 text-xs font-medium flex items-center gap-1">
                                  Ver Proyecto <span aria-hidden>→</span>
                                </span>
                              )}
                            </div>
                          </td>
                        </tr>
                      );
                    })}
                  </tbody>
                </table>
              </div>
            </div>
          </div>
        )}

        {/* Tab 1: Nueva propuesta */}
        {activeTab === 1 && (
          <div className="bg-white dark:bg-slate-800 rounded-2xl border border-slate-200 dark:border-slate-700 p-6 max-w-3xl">
            <h2 className="font-semibold text-slate-800 dark:text-slate-100 mb-5">Nueva licitación / propuesta</h2>
            <div className="grid grid-cols-2 gap-4 text-sm">
              <div className="col-span-2">
                <label className="block text-slate-500 dark:text-slate-400 mb-1 font-medium">Título *</label>
                <input value={newForm.title} onChange={e => setF('title', e.target.value)}
                  className="w-full rounded-xl border border-slate-200 dark:border-slate-600 bg-slate-50 dark:bg-slate-700 text-slate-800 dark:text-slate-100 px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-400" placeholder="Nombre de la licitación" />
              </div>
              <div>
                <label className="block text-slate-500 dark:text-slate-400 mb-1 font-medium">Cliente *</label>
                <input value={newForm.client} onChange={e => setF('client', e.target.value)}
                  className="w-full rounded-xl border border-slate-200 dark:border-slate-600 bg-slate-50 dark:bg-slate-700 text-slate-800 dark:text-slate-100 px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-400" placeholder="Nombre del cliente" />
              </div>
              <div>
                <label className="block text-slate-500 dark:text-slate-400 mb-1 font-medium">Tipo</label>
                <select value={newForm.type} onChange={e => setF('type', e.target.value)}
                  className="w-full rounded-xl border border-slate-200 dark:border-slate-600 bg-slate-50 dark:bg-slate-700 text-slate-800 dark:text-slate-100 px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-400">
                  <option value="LICITACION_PUBLICA">Licitación pública</option>
                  <option value="LICITACION_PRIVADA">Licitación privada</option>
                  <option value="INVITACION_DIRECTA">Invitación directa</option>
                </select>
              </div>
              <div>
                <label className="block text-slate-500 dark:text-slate-400 mb-1 font-medium">Categoría</label>
                <select value={newForm.category} onChange={e => setF('category', e.target.value)}
                  className="w-full rounded-xl border border-slate-200 dark:border-slate-600 bg-slate-50 dark:bg-slate-700 text-slate-800 dark:text-slate-100 px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-400">
                  <option value="CONSTRUCCION">Construcción</option>
                  <option value="INDUSTRIAL">Industrial</option>
                  <option value="TI">TI</option>
                  <option value="ENERGIA">Energía</option>
                </select>
              </div>
              <div>
                <label className="block text-slate-500 dark:text-slate-400 mb-1 font-medium">Valor estimado</label>
                <input type="number" value={newForm.value} onChange={e => setF('value', e.target.value)}
                  className="w-full rounded-xl border border-slate-200 dark:border-slate-600 bg-slate-50 dark:bg-slate-700 text-slate-800 dark:text-slate-100 px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-400" placeholder="0" />
              </div>
              <div>
                <label className="block text-slate-500 dark:text-slate-400 mb-1 font-medium">Moneda</label>
                <select value={newForm.currency} onChange={e => setF('currency', e.target.value)}
                  className="w-full rounded-xl border border-slate-200 dark:border-slate-600 bg-slate-50 dark:bg-slate-700 text-slate-800 dark:text-slate-100 px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-400">
                  <option value="COP">COP</option>
                  <option value="USD">USD</option>
                  <option value="EUR">EUR</option>
                </select>
              </div>
              <div>
                <label className="block text-slate-500 dark:text-slate-400 mb-1 font-medium">Fecha límite entrega</label>
                <input type="date" value={newForm.submissionDate} onChange={e => setF('submissionDate', e.target.value)}
                  className="w-full rounded-xl border border-slate-200 dark:border-slate-600 bg-slate-50 dark:bg-slate-700 text-slate-800 dark:text-slate-100 px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-400" />
              </div>
              <div>
                <label className="block text-slate-500 dark:text-slate-400 mb-1 font-medium">Probabilidad: {newForm.probability}%</label>
                <input type="range" min={0} max={100} value={newForm.probability} onChange={e => setF('probability', Number(e.target.value))}
                  className="w-full accent-blue-600 mt-2" />
              </div>
              <div>
                <label className="block text-slate-500 dark:text-slate-400 mb-1 font-medium">Responsable</label>
                <select value={newForm.owner} onChange={e => setF('owner', e.target.value)}
                  className="w-full rounded-xl border border-slate-200 dark:border-slate-600 bg-slate-50 dark:bg-slate-700 text-slate-800 dark:text-slate-100 px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-400">
                  <option value="">Seleccionar...</option>
                  {TEAM_MEMBERS.map(m => <option key={m} value={m}>{m}</option>)}
                </select>
              </div>
              <div className="col-span-2">
                <label className="block text-slate-500 dark:text-slate-400 mb-1 font-medium">Descripción</label>
                <textarea value={newForm.description} onChange={e => setF('description', e.target.value)} rows={3}
                  className="w-full rounded-xl border border-slate-200 dark:border-slate-600 bg-slate-50 dark:bg-slate-700 text-slate-800 dark:text-slate-100 px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-400" placeholder="Descripción del alcance..." />
              </div>
              <div className="col-span-2">
                <label className="block text-slate-500 dark:text-slate-400 mb-1 font-medium">Notas internas</label>
                <textarea value={newForm.notes} onChange={e => setF('notes', e.target.value)} rows={2}
                  className="w-full rounded-xl border border-slate-200 dark:border-slate-600 bg-slate-50 dark:bg-slate-700 text-slate-800 dark:text-slate-100 px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-400" placeholder="Notas confidenciales..." />
              </div>
            </div>
            <div className="flex justify-end gap-3 mt-6">
              <button onClick={() => setActiveTab(0)} className="px-4 py-2 rounded-xl border border-slate-200 dark:border-slate-600 text-slate-600 dark:text-slate-300 hover:bg-slate-50 dark:hover:bg-slate-700 text-sm">Cancelar</button>
              <button onClick={handleCreate} className="px-5 py-2 rounded-xl bg-blue-600 hover:bg-blue-700 text-white text-sm font-medium">Crear licitación</button>
            </div>
          </div>
        )}

        {/* Tab 2: Análisis */}
        {activeTab === 2 && (
          <div className="space-y-5">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-5">
              {/* PieChart */}
              <div className="bg-white dark:bg-slate-800 rounded-2xl border border-slate-200 dark:border-slate-700 p-5">
                <h3 className="font-semibold text-slate-800 dark:text-slate-100 mb-4">Distribución por estado</h3>
                <ResponsiveContainer width="100%" height={260}>
                  <PieChart>
                    <Pie data={pieData} dataKey="value" nameKey="name" cx="50%" cy="50%" outerRadius={90} label={({ name, percent }) => `${name} ${(percent*100).toFixed(0)}%`} labelLine={false}>
                      {pieData.map((entry, i) => (
                        <Cell key={i} fill={STATUS_COLORS[entry.name] || '#94a3b8'} />
                      ))}
                    </Pie>
                    <Tooltip formatter={(v) => [v, 'Cantidad']} />
                  </PieChart>
                </ResponsiveContainer>
              </div>

              {/* BarChart */}
              <div className="bg-white dark:bg-slate-800 rounded-2xl border border-slate-200 dark:border-slate-700 p-5">
                <h3 className="font-semibold text-slate-800 dark:text-slate-100 mb-4">Valor por categoría (COP)</h3>
                <ResponsiveContainer width="100%" height={260}>
                  <BarChart data={barData} margin={{ top: 5, right: 5, left: 0, bottom: 5 }}>
                    <CartesianGrid strokeDasharray="3 3" stroke="#e2e8f0" />
                    <XAxis dataKey="name" tick={{ fontSize: 11, fill: '#94a3b8' }} />
                    <YAxis tick={{ fontSize: 10, fill: '#94a3b8' }} tickFormatter={v => `$${(v/1e6).toFixed(0)}M`} />
                    <Tooltip formatter={(v) => [formatCOP(v), 'Valor']} />
                    <Bar dataKey="value" radius={[6,6,0,0]}>
                      {barData.map((_, i) => <Cell key={i} fill={CATEGORY_COLORS[i % CATEGORY_COLORS.length]} />)}
                    </Bar>
                  </BarChart>
                </ResponsiveContainer>
              </div>
            </div>

            {/* Summary */}
            <div className="bg-white dark:bg-slate-800 rounded-2xl border border-slate-200 dark:border-slate-700 p-5">
              <h3 className="font-semibold text-slate-800 dark:text-slate-100 mb-4">Resumen — últimos 12 meses</h3>
              <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                <div className="bg-slate-50 dark:bg-slate-700/50 rounded-xl p-4">
                  <p className="text-xs text-slate-500 dark:text-slate-400 mb-1">Tasa de éxito</p>
                  <p className="text-2xl font-bold text-emerald-600 dark:text-emerald-400">{tasaExito}%</p>
                </div>
                <div className="bg-slate-50 dark:bg-slate-700/50 rounded-xl p-4">
                  <p className="text-xs text-slate-500 dark:text-slate-400 mb-1">Valor ganado</p>
                  <p className="text-lg font-bold text-emerald-600 dark:text-emerald-400">{formatCOP(valorGanado)}</p>
                </div>
                <div className="bg-slate-50 dark:bg-slate-700/50 rounded-xl p-4">
                  <p className="text-xs text-slate-500 dark:text-slate-400 mb-1">Valor perdido</p>
                  <p className="text-lg font-bold text-red-500 dark:text-red-400">{formatCOP(valorPerdido)}</p>
                </div>
                <div className="bg-slate-50 dark:bg-slate-700/50 rounded-xl p-4">
                  <p className="text-xs text-slate-500 dark:text-slate-400 mb-1">Pipeline activo</p>
                  <p className="text-lg font-bold text-blue-600 dark:text-blue-400">{formatCOP(valorPipeline)}</p>
                </div>
              </div>
            </div>
          </div>
        )}

        {/* Tab 3: Análisis de Pérdidas */}
        {activeTab === 3 && (
          <div className="space-y-5">
            {/* KPIs */}
            <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
              <div className="bg-white dark:bg-slate-800 rounded-2xl border border-slate-200 dark:border-slate-700 p-4">
                <p className="text-xs text-slate-500 dark:text-slate-400 mb-1">Total licitaciones perdidas</p>
                <p className="text-3xl font-bold text-red-500 dark:text-red-400">{lostBids.length}</p>
              </div>
              <div className="bg-white dark:bg-slate-800 rounded-2xl border border-slate-200 dark:border-slate-700 p-4">
                <p className="text-xs text-slate-500 dark:text-slate-400 mb-1">Tasa de éxito</p>
                <p className="text-3xl font-bold text-emerald-600 dark:text-emerald-400">{tasaExito}%</p>
              </div>
              <div className="bg-white dark:bg-slate-800 rounded-2xl border border-slate-200 dark:border-slate-700 p-4">
                <p className="text-xs text-slate-500 dark:text-slate-400 mb-1">Valor perdido total</p>
                <p className="text-lg font-bold text-red-500 dark:text-red-400">{formatCOP(valorPerdido)}</p>
              </div>
              <div className="bg-white dark:bg-slate-800 rounded-2xl border border-slate-200 dark:border-slate-700 p-4">
                <p className="text-xs text-slate-500 dark:text-slate-400 mb-1">Principal causa de pérdida</p>
                <p className="text-sm font-bold text-slate-700 dark:text-slate-200 leading-snug mt-1">{topCausa}</p>
              </div>
            </div>

            {/* Charts */}
            <div className="grid grid-cols-1 md:grid-cols-2 gap-5">
              {/* Win vs Loss per month */}
              <div className="bg-white dark:bg-slate-800 rounded-2xl border border-slate-200 dark:border-slate-700 p-5">
                <h3 className="font-semibold text-slate-800 dark:text-slate-100 mb-1">Ganadas vs. Perdidas por mes</h3>
                <p className="text-xs text-slate-500 dark:text-slate-400 mb-4">Últimos 12 meses</p>
                <ResponsiveContainer width="100%" height={240}>
                  <BarChart data={MONTHLY_WIN_LOSS} margin={{ top: 5, right: 5, left: 0, bottom: 5 }}>
                    <CartesianGrid strokeDasharray="3 3" stroke="#e2e8f0" />
                    <XAxis dataKey="mes" tick={{ fontSize: 11, fill: '#94a3b8' }} />
                    <YAxis tick={{ fontSize: 10, fill: '#94a3b8' }} allowDecimals={false} />
                    <Tooltip />
                    <Legend />
                    <Bar dataKey="ganadas" name="Ganadas" fill="#10b981" radius={[4,4,0,0]} />
                    <Bar dataKey="perdidas" name="Perdidas" fill="#ef4444" radius={[4,4,0,0]} />
                  </BarChart>
                </ResponsiveContainer>
              </div>

              {/* Loss reasons PieChart */}
              <div className="bg-white dark:bg-slate-800 rounded-2xl border border-slate-200 dark:border-slate-700 p-5">
                <h3 className="font-semibold text-slate-800 dark:text-slate-100 mb-1">Causas de pérdida</h3>
                <p className="text-xs text-slate-500 dark:text-slate-400 mb-4">Distribución porcentual</p>
                <ResponsiveContainer width="100%" height={240}>
                  <PieChart>
                    <Pie data={LOSS_REASONS} dataKey="value" nameKey="name" cx="50%" cy="50%" outerRadius={85} label={({ name, value }) => `${value}%`} labelLine={false}>
                      {LOSS_REASONS.map((entry, i) => (
                        <Cell key={i} fill={entry.fill} />
                      ))}
                    </Pie>
                    <Tooltip formatter={(v, name) => [`${v}%`, name]} />
                    <Legend />
                  </PieChart>
                </ResponsiveContainer>
              </div>
            </div>

            {/* AI Insight */}
            <div className="bg-indigo-50 dark:bg-indigo-900/20 border border-indigo-200 dark:border-indigo-800 rounded-2xl p-5">
              <div className="flex items-start gap-3">
                <span className="text-2xl mt-0.5">&#x1F4CA;</span>
                <div>
                  <p className="text-sm font-semibold text-indigo-800 dark:text-indigo-300 mb-1">Análisis con IA</p>
                  <p className="text-sm text-indigo-700 dark:text-indigo-400 leading-relaxed">
                    Las licitaciones perdidas por precio tienen un gap promedio del 8.3%. Reducir overhead en un 5% mejoraría la competitividad en 3 de las últimas 5 pérdidas. Se recomienda revisar la estructura de costos indirectos y evaluar acuerdos marco con proveedores estratégicos para mejorar el margen sin comprometer la calidad técnica.
                  </p>
                </div>
              </div>
            </div>

            {/* Lost bids table */}
            <div className="bg-white dark:bg-slate-800 rounded-2xl border border-slate-200 dark:border-slate-700 overflow-hidden">
              <div className="px-5 py-4 border-b border-slate-200 dark:border-slate-700">
                <h3 className="font-semibold text-slate-800 dark:text-slate-100">Detalle de licitaciones perdidas</h3>
              </div>
              <div className="overflow-x-auto">
                <table className="w-full text-sm">
                  <thead>
                    <tr className="text-left text-slate-500 dark:text-slate-400 text-xs border-b border-slate-100 dark:border-slate-700">
                      <th className="px-4 py-3 font-semibold uppercase">Licitación</th>
                      <th className="px-4 py-3 font-semibold uppercase">Cliente</th>
                      <th className="px-4 py-3 font-semibold uppercase">Nuestro precio</th>
                      <th className="px-4 py-3 font-semibold uppercase">Precio ganador</th>
                      <th className="px-4 py-3 font-semibold uppercase">Gap %</th>
                      <th className="px-4 py-3 font-semibold uppercase">Causa</th>
                      <th className="px-4 py-3 font-semibold uppercase">Lecciones aprendidas</th>
                    </tr>
                  </thead>
                  <tbody>
                    {lostBids.map(bid => {
                      const gap = bid.winnerPrice ? Math.round(((bid.value - bid.winnerPrice) / bid.winnerPrice) * 100) : null;
                      return (
                        <tr key={bid.id} className="border-b border-slate-50 dark:border-slate-700/50 hover:bg-slate-50 dark:hover:bg-slate-800/40 transition-colors">
                          <td className="px-4 py-3">
                            <div className="font-medium text-slate-700 dark:text-slate-200 text-xs max-w-[180px] truncate">{bid.title}</div>
                            <div className="text-xs text-slate-400 font-mono">{bid.id}</div>
                          </td>
                          <td className="px-4 py-3 text-slate-600 dark:text-slate-300 text-xs max-w-[120px] truncate">{bid.client}</td>
                          <td className="px-4 py-3 text-xs font-medium text-slate-700 dark:text-slate-200 whitespace-nowrap">{formatCOP(bid.value)}</td>
                          <td className="px-4 py-3 text-xs font-medium text-emerald-600 dark:text-emerald-400 whitespace-nowrap">
                            {bid.winnerPrice ? formatCOP(bid.winnerPrice) : '—'}
                          </td>
                          <td className="px-4 py-3">
                            {gap !== null ? (
                              <span className={`text-xs font-semibold ${gap > 0 ? 'text-red-600 dark:text-red-400' : 'text-emerald-600 dark:text-emerald-400'}`}>
                                +{gap}%
                              </span>
                            ) : '—'}
                          </td>
                          <td className="px-4 py-3">
                            {bid.lossReason ? (
                              <span className="px-2 py-0.5 rounded-full text-xs font-medium bg-red-100 text-red-700 dark:bg-red-900/40 dark:text-red-300 whitespace-nowrap">
                                {bid.lossReason}
                              </span>
                            ) : '—'}
                          </td>
                          <td className="px-4 py-3 text-xs text-slate-500 dark:text-slate-400 max-w-[240px]">
                            {bid.lessonsLearned || '—'}
                          </td>
                        </tr>
                      );
                    })}
                    {lostBids.length === 0 && (
                      <tr>
                        <td colSpan={7} className="px-4 py-8 text-center text-slate-400 text-sm">No hay licitaciones perdidas registradas.</td>
                      </tr>
                    )}
                  </tbody>
                </table>
              </div>
            </div>
          </div>
        )}
      </div>

      {/* Modals */}
      {selectedBid && <BidDetailModal bid={selectedBid} onClose={() => setSelectedBid(null)} />}
      {convertBid && (
        <ConvertModal
          bid={convertBid}
          onClose={() => setConvertBid(null)}
          onConverted={handleConverted}
        />
      )}
    </div>
  );
}
