import { useState } from 'react';
import {
  RadarChart, Radar, PolarGrid, PolarAngleAxis, PolarRadiusAxis,
  LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, Legend,
  ResponsiveContainer,
} from 'recharts';

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

const MOCK_INSPECTIONS = [
  {
    id: 'ins1', code: 'INS-2026-001', type: 'INTERNA', area: 'Estructura — Piso 1',
    project: 'AR-ProjectManagement', inspector: 'Álvaro Romero', date: '2026-06-10',
    status: 'APROBADA',
    checklist: [
      { item: 'Vertido de concreto según especificación', ok: true, obs: '' },
      { item: "Resistencia f'c = 28 MPa verificada", ok: true, obs: '' },
      { item: 'Recubrimiento mínimo 3cm', ok: true, obs: '' },
      { item: 'Armado según plano PLN-002 Rev.2', ok: true, obs: '' },
    ],
    ncrs: [],
  },
  {
    id: 'ins2', code: 'INS-2026-002', type: 'INTERNA', area: 'Instalaciones eléctricas — Piso 2',
    project: 'AR-ProjectManagement', inspector: 'Álvaro Romero', date: '2026-06-18',
    status: 'CON_OBSERVACIONES',
    checklist: [
      { item: 'Calibre de conductores según ESP-001', ok: true, obs: '' },
      { item: 'Identificación de circuitos', ok: false, obs: 'Falta rotulación en tablero secundario TB-2' },
      { item: 'Conectores aprobados', ok: true, obs: '' },
      { item: 'Prueba de aislamiento realizada', ok: false, obs: 'Pendiente resultado laboratorio' },
    ],
    ncrs: ['NCR-2026-001'],
  },
  {
    id: 'ins3', code: 'INS-2026-003', type: 'CLIENTE', area: 'Estructura — Pisos 1-3',
    project: 'AR-ProjectManagement', inspector: 'Ing. Álvaro Romero (Cliente)', date: '2026-06-22',
    status: 'PENDIENTE', checklist: [], ncrs: [],
  },
  {
    id: 'ins4', code: 'INS-2026-004', type: 'INTERNA', area: 'Módulo financiero — pruebas UAT',
    project: 'AR-ProjectManagement', inspector: 'Paula Soto', date: '2026-06-15',
    status: 'APROBADA',
    checklist: [
      { item: 'Cálculo de IVA correcto', ok: true, obs: '' },
      { item: 'Generación de reportes PDF', ok: true, obs: '' },
      { item: 'Integración con módulo inventario', ok: true, obs: '' },
    ],
    ncrs: [],
  },
];

const INITIAL_NCRS = [
  {
    id: 'NCR-2026-001', title: 'Falta rotulación tablero secundario TB-2',
    project: 'AR-ProjectManagement', area: 'Instalaciones eléctricas piso 2',
    detectedBy: 'Álvaro Romero', detectedDate: '2026-06-18',
    severity: 'MENOR', status: 'ABIERTA', assignedTo: 'Álvaro Romero',
    dueDate: '2026-06-30', closedDate: null, rootCause: '', correctiveAction: '',
    inspectionRef: 'INS-2026-002',
  },
  {
    id: 'NCR-2026-002', title: 'Prueba de aislamiento pendiente piso 2',
    project: 'AR-ProjectManagement', area: 'Instalaciones eléctricas piso 2',
    detectedBy: 'Álvaro Romero', detectedDate: '2026-06-18',
    severity: 'MAYOR', status: 'EN_PROCESO', assignedTo: 'Paula Soto',
    dueDate: '2026-07-05', closedDate: null,
    rootCause: 'Laboratorio externo con demora',
    correctiveAction: 'Reprogramar ensayo con Laboratorio Contek para 2026-07-03',
    inspectionRef: 'INS-2026-002',
  },
  {
    id: 'NCR-2026-003', title: 'Diferencia de nivel en losa piso 1 (±8mm)',
    project: 'AR-ProjectManagement', area: 'Estructura piso 1',
    detectedBy: 'Álvaro Romero', detectedDate: '2026-06-05',
    severity: 'CRITICA', status: 'CERRADA', assignedTo: 'Álvaro Romero',
    dueDate: '2026-06-15', closedDate: '2026-06-14',
    rootCause: 'Error en nivelación previo al vaciado',
    correctiveAction: 'Aplicación de mortero nivelador aprobado por diseñador estructural',
    inspectionRef: 'INS-2026-001',
  },
];

const INITIAL_PUNCH = [
  { id: 'PL-001', description: 'Pintura faltante en columna eje C4', area: 'Piso 1', project: 'AR-ProjectManagement', assignedTo: 'Contratista Pintura', dueDate: '2026-07-10', status: 'PENDIENTE', priority: 'BAJA' },
  { id: 'PL-002', description: 'Silicón en juntas ventanas fachada norte', area: 'Pisos 1-3', project: 'AR-ProjectManagement', assignedTo: 'Contratista Vidrios', dueDate: '2026-07-08', status: 'EN_PROCESO', priority: 'MEDIA' },
  { id: 'PL-003', description: 'Ajuste bisagras puerta eléctrica cuarto piso 1', area: 'Cuarto eléctrico', project: 'AR-ProjectManagement', assignedTo: 'Eléctricos Modernos', dueDate: '2026-07-05', status: 'COMPLETADO', priority: 'BAJA' },
  { id: 'PL-004', description: 'Error en traducción menú configuración sistema', area: 'UI módulo RRHH', project: 'AR-ProjectManagement', assignedTo: 'Paula Soto', dueDate: '2026-07-03', status: 'PENDIENTE', priority: 'ALTA' },
];

// ─── Helpers ──────────────────────────────────────────────────────────────────

const TODAY = '2026-06-26';

function isOverdue(dueDate, status) {
  return status !== 'CERRADA' && status !== 'COMPLETADO' && dueDate < TODAY;
}

function daysSince(dateStr) {
  const ms = new Date(TODAY) - new Date(dateStr);
  return Math.floor(ms / 86400000);
}

function nextNcrId(ncrs) {
  const nums = ncrs.map(n => parseInt(n.id.replace('NCR-2026-', ''), 10));
  const max = nums.length ? Math.max(...nums) : 0;
  return `NCR-2026-${String(max + 1).padStart(3, '0')}`;
}

function nextPunchId(list) {
  const nums = list.map(p => parseInt(p.id.replace('PL-', ''), 10));
  const max = nums.length ? Math.max(...nums) : 0;
  return `PL-${String(max + 1).padStart(3, '0')}`;
}

// ─── Badge components ─────────────────────────────────────────────────────────

function InspectionTypeBadge({ type }) {
  const cls = type === 'CLIENTE'
    ? 'bg-blue-100 text-blue-700 dark:bg-blue-900/40 dark:text-blue-300'
    : 'bg-slate-100 text-slate-600 dark:bg-slate-700 dark:text-slate-300';
  return <span className={`px-2 py-0.5 rounded-full text-xs font-medium ${cls}`}>{type}</span>;
}

function InspectionStatusBadge({ status }) {
  const map = {
    APROBADA: 'bg-emerald-100 text-emerald-700 dark:bg-emerald-900/40 dark:text-emerald-300',
    CON_OBSERVACIONES: 'bg-amber-100 text-amber-700 dark:bg-amber-900/40 dark:text-amber-300',
    PENDIENTE: 'bg-slate-100 text-slate-500 dark:bg-slate-700 dark:text-slate-400',
    RECHAZADA: 'bg-red-100 text-red-700 dark:bg-red-900/40 dark:text-red-300',
  };
  const labels = {
    APROBADA: 'Aprobada', CON_OBSERVACIONES: 'Con observaciones',
    PENDIENTE: 'Pendiente', RECHAZADA: 'Rechazada',
  };
  return (
    <span className={`px-2 py-0.5 rounded-full text-xs font-medium ${map[status] || map.PENDIENTE}`}>
      {labels[status] || status}
    </span>
  );
}

function SeverityBadge({ severity }) {
  const map = {
    MENOR: 'bg-blue-100 text-blue-700 dark:bg-blue-900/40 dark:text-blue-300',
    MAYOR: 'bg-amber-100 text-amber-700 dark:bg-amber-900/40 dark:text-amber-300',
    CRITICA: 'bg-red-100 text-red-700 dark:bg-red-900/40 dark:text-red-300 animate-pulse',
  };
  return <span className={`px-2 py-0.5 rounded-full text-xs font-medium ${map[severity] || ''}`}>{severity}</span>;
}

function NcrStatusBadge({ status }) {
  const map = {
    ABIERTA: 'bg-red-100 text-red-700 dark:bg-red-900/40 dark:text-red-300',
    EN_PROCESO: 'bg-amber-100 text-amber-700 dark:bg-amber-900/40 dark:text-amber-300',
    CERRADA: 'bg-emerald-100 text-emerald-700 dark:bg-emerald-900/40 dark:text-emerald-300',
  };
  return <span className={`px-2 py-0.5 rounded-full text-xs font-medium ${map[status] || ''}`}>{status.replace('_', ' ')}</span>;
}

function PunchStatusBadge({ status }) {
  const map = {
    PENDIENTE: 'bg-slate-100 text-slate-500 dark:bg-slate-700 dark:text-slate-400',
    EN_PROCESO: 'bg-amber-100 text-amber-700 dark:bg-amber-900/40 dark:text-amber-300',
    COMPLETADO: 'bg-emerald-100 text-emerald-700 dark:bg-emerald-900/40 dark:text-emerald-300',
  };
  return <span className={`px-2 py-0.5 rounded-full text-xs font-medium ${map[status] || ''}`}>{status.replace('_', ' ')}</span>;
}

function PriorityBadge({ priority }) {
  const map = {
    ALTA: 'bg-red-100 text-red-700 dark:bg-red-900/40 dark:text-red-300',
    MEDIA: 'bg-amber-100 text-amber-700 dark:bg-amber-900/40 dark:text-amber-300',
    BAJA: 'bg-slate-100 text-slate-500 dark:bg-slate-700 dark:text-slate-400',
  };
  return <span className={`px-2 py-0.5 rounded-full text-xs font-medium ${map[priority] || ''}`}>{priority}</span>;
}

// ─── KPI Card ─────────────────────────────────────────────────────────────────

function KpiCard({ label, value, color = 'text-slate-800 dark:text-slate-100', sub }) {
  return (
    <div className="rounded-2xl border border-slate-200 dark:border-surface-700 bg-white dark:bg-slate-800 p-4 flex flex-col gap-1">
      <span className="text-xs text-slate-500 dark:text-slate-400 font-medium uppercase tracking-wide">{label}</span>
      <span className={`text-3xl font-bold ${color}`}>{value}</span>
      {sub && <span className="text-xs text-slate-400 dark:text-slate-500">{sub}</span>}
    </div>
  );
}

// ─── Modal wrapper ────────────────────────────────────────────────────────────

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

// ─── Field input ──────────────────────────────────────────────────────────────

function Field({ label, children }) {
  return (
    <div className="flex flex-col gap-1">
      <label className="text-xs font-medium text-slate-500 dark:text-slate-400 uppercase tracking-wide">{label}</label>
      {children}
    </div>
  );
}

const inputCls = 'rounded-lg border border-slate-200 dark:border-surface-700 bg-slate-50 dark:bg-slate-800 text-slate-800 dark:text-slate-100 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 transition';

// ─── TAB 0 — Inspecciones ─────────────────────────────────────────────────────

function InspectionDetailModal({ inspection, onClose, onNewNcr }) {
  return (
    <Modal title={`${inspection.code} — ${inspection.area}`} onClose={onClose} wide>
      <div className="space-y-4">
        <div className="grid grid-cols-2 gap-3 text-sm">
          <div><span className="text-slate-500 dark:text-slate-400">Proyecto: </span><span className="text-slate-800 dark:text-slate-100 font-medium">{inspection.project}</span></div>
          <div><span className="text-slate-500 dark:text-slate-400">Inspector: </span><span className="text-slate-800 dark:text-slate-100 font-medium">{inspection.inspector}</span></div>
          <div><span className="text-slate-500 dark:text-slate-400">Fecha: </span><span className="text-slate-800 dark:text-slate-100 font-medium">{inspection.date}</span></div>
          <div className="flex items-center gap-2"><span className="text-slate-500 dark:text-slate-400">Estado: </span><InspectionStatusBadge status={inspection.status} /></div>
        </div>

        {inspection.checklist.length > 0 && (
          <div>
            <h4 className="font-semibold text-slate-700 dark:text-slate-200 mb-2">Checklist</h4>
            <div className="space-y-2">
              {inspection.checklist.map((c, i) => (
                <div key={i} className={`rounded-xl p-3 border text-sm ${c.ok ? 'border-emerald-200 bg-emerald-50 dark:border-emerald-800/50 dark:bg-emerald-900/20' : 'border-red-200 bg-red-50 dark:border-red-800/50 dark:bg-red-900/20'}`}>
                  <div className="flex items-start gap-2">
                    <span className={`mt-0.5 flex-shrink-0 ${c.ok ? 'text-emerald-600' : 'text-red-500'}`}>{c.ok ? '✓' : '✗'}</span>
                    <div>
                      <p className="text-slate-800 dark:text-slate-100">{c.item}</p>
                      {c.obs && <p className="text-slate-500 dark:text-slate-400 mt-0.5 text-xs">{c.obs}</p>}
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        )}

        {inspection.ncrs.length > 0 && (
          <div>
            <h4 className="font-semibold text-slate-700 dark:text-slate-200 mb-2">NCRs vinculadas</h4>
            <div className="flex flex-wrap gap-2">
              {inspection.ncrs.map(id => (
                <span key={id} className="px-3 py-1 rounded-full bg-amber-100 dark:bg-amber-900/30 text-amber-700 dark:text-amber-300 text-sm font-medium">{id}</span>
              ))}
            </div>
          </div>
        )}

        <div className="pt-2 flex justify-end gap-2">
          <button onClick={() => { onNewNcr(inspection); onClose(); }}
            className="px-4 py-2 rounded-xl bg-amber-500 hover:bg-amber-600 text-white text-sm font-medium transition-colors">
            + Nueva NCR desde esta inspección
          </button>
          <button onClick={onClose} className="px-4 py-2 rounded-xl bg-slate-100 dark:bg-slate-700 text-slate-700 dark:text-slate-200 text-sm font-medium hover:bg-slate-200 dark:hover:bg-slate-600 transition-colors">Cerrar</button>
        </div>
      </div>
    </Modal>
  );
}

function NewInspectionModal({ onClose, onSave }) {
  const [form, setForm] = useState({
    type: 'INTERNA', area: '', project: '', inspector: '', date: TODAY, status: 'PENDIENTE',
  });
  const [checklist, setChecklist] = useState([{ item: '', ok: false, obs: '' }]);

  function addItem() { setChecklist(p => [...p, { item: '', ok: false, obs: '' }]); }
  function removeItem(i) { setChecklist(p => p.filter((_, idx) => idx !== i)); }
  function updateItem(i, field, val) {
    setChecklist(p => p.map((c, idx) => idx === i ? { ...c, [field]: val } : c));
  }

  function handleSave() {
    if (!form.area || !form.project || !form.inspector) return;
    const inspections = JSON.parse(sessionStorage.getItem('inspections') || 'null') || MOCK_INSPECTIONS;
    const num = inspections.length + 1;
    const code = `INS-2026-${String(num + 4).padStart(3, '0')}`;
    onSave({ ...form, id: `ins${Date.now()}`, code, checklist: checklist.filter(c => c.item), ncrs: [] });
    onClose();
  }

  return (
    <Modal title="Nueva Inspección" onClose={onClose} wide>
      <div className="space-y-4">
        <div className="grid grid-cols-2 gap-3">
          <Field label="Tipo">
            <select value={form.type} onChange={e => setForm(p => ({ ...p, type: e.target.value }))} className={inputCls}>
              <option value="INTERNA">INTERNA</option>
              <option value="CLIENTE">CLIENTE</option>
            </select>
          </Field>
          <Field label="Estado inicial">
            <select value={form.status} onChange={e => setForm(p => ({ ...p, status: e.target.value }))} className={inputCls}>
              <option value="PENDIENTE">Pendiente</option>
              <option value="APROBADA">Aprobada</option>
              <option value="CON_OBSERVACIONES">Con observaciones</option>
              <option value="RECHAZADA">Rechazada</option>
            </select>
          </Field>
          <Field label="Área">
            <input value={form.area} onChange={e => setForm(p => ({ ...p, area: e.target.value }))} className={inputCls} placeholder="Ej. Estructura — Piso 3" />
          </Field>
          <Field label="Proyecto">
            <input value={form.project} onChange={e => setForm(p => ({ ...p, project: e.target.value }))} className={inputCls} placeholder="Ej. AR-ProjectManagement" />
          </Field>
          <Field label="Inspector">
            <input value={form.inspector} onChange={e => setForm(p => ({ ...p, inspector: e.target.value }))} className={inputCls} placeholder="Nombre del inspector" />
          </Field>
          <Field label="Fecha">
            <input type="date" value={form.date} onChange={e => setForm(p => ({ ...p, date: e.target.value }))} className={inputCls} />
          </Field>
        </div>

        <div>
          <div className="flex items-center justify-between mb-2">
            <h4 className="font-semibold text-slate-700 dark:text-slate-200 text-sm">Checklist</h4>
            <button onClick={addItem} className="text-xs text-blue-600 dark:text-blue-400 hover:underline">+ Agregar ítem</button>
          </div>
          <div className="space-y-2 max-h-52 overflow-y-auto pr-1">
            {checklist.map((c, i) => (
              <div key={i} className="flex gap-2 items-start">
                <input type="checkbox" checked={c.ok} onChange={e => updateItem(i, 'ok', e.target.checked)}
                  className="mt-2.5 accent-emerald-500 flex-shrink-0" />
                <input value={c.item} onChange={e => updateItem(i, 'item', e.target.value)}
                  className={`${inputCls} flex-1`} placeholder="Ítem de verificación" />
                <input value={c.obs} onChange={e => updateItem(i, 'obs', e.target.value)}
                  className={`${inputCls} w-36`} placeholder="Observación" />
                <button onClick={() => removeItem(i)} className="mt-2 text-red-400 hover:text-red-600 text-lg leading-none transition-colors">&times;</button>
              </div>
            ))}
          </div>
        </div>

        <div className="flex justify-end gap-2 pt-2">
          <button onClick={onClose} className="px-4 py-2 rounded-xl bg-slate-100 dark:bg-slate-700 text-slate-700 dark:text-slate-200 text-sm font-medium hover:bg-slate-200 dark:hover:bg-slate-600 transition-colors">Cancelar</button>
          <button onClick={handleSave} className="px-4 py-2 rounded-xl bg-blue-600 hover:bg-blue-700 text-white text-sm font-medium transition-colors">Guardar inspección</button>
        </div>
      </div>
    </Modal>
  );
}

function InspectionsTab({ inspections, setInspections, onNewNcr }) {
  const [viewInspection, setViewInspection] = useState(null);
  const [showNew, setShowNew] = useState(false);

  const total = inspections.length;
  const aprobadas = inspections.filter(i => i.status === 'APROBADA').length;
  const conObs = inspections.filter(i => i.status === 'CON_OBSERVACIONES').length;
  const pendientes = inspections.filter(i => i.status === 'PENDIENTE').length;

  return (
    <div className="space-y-5">
      <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
        <KpiCard label="Total inspecciones" value={total} />
        <KpiCard label="Aprobadas" value={aprobadas} color="text-emerald-600 dark:text-emerald-400" />
        <KpiCard label="Con observaciones" value={conObs} color="text-amber-600 dark:text-amber-400" />
        <KpiCard label="Pendientes" value={pendientes} color="text-slate-500 dark:text-slate-400" />
      </div>

      <div className="rounded-2xl border border-slate-200 dark:border-surface-700 bg-white dark:bg-slate-900 overflow-hidden">
        <div className="flex items-center justify-between px-5 py-4 border-b border-slate-100 dark:border-surface-700">
          <h3 className="font-semibold text-slate-800 dark:text-slate-100">Inspecciones</h3>
          <button onClick={() => setShowNew(true)}
            className="px-4 py-2 rounded-xl bg-blue-600 hover:bg-blue-700 text-white text-sm font-medium transition-colors">
            + Nueva inspección
          </button>
        </div>
        <div className="overflow-x-auto">
          <table className="w-full text-sm">
            <thead>
              <tr className="bg-slate-50 dark:bg-slate-800 text-slate-500 dark:text-slate-400 text-left">
                {['Código', 'Área', 'Proyecto', 'Inspector', 'Fecha', 'Tipo', 'Estado', 'Acciones'].map(h => (
                  <th key={h} className="px-4 py-3 font-medium whitespace-nowrap">{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {inspections.map((ins, idx) => (
                <tr key={ins.id} className={`border-t border-slate-100 dark:border-surface-700 hover:bg-slate-50 dark:hover:bg-slate-800/50 transition-colors ${idx % 2 === 0 ? '' : 'bg-slate-50/30 dark:bg-slate-800/20'}`}>
                  <td className="px-4 py-3 font-mono text-xs text-slate-600 dark:text-slate-300 whitespace-nowrap">{ins.code}</td>
                  <td className="px-4 py-3 text-slate-700 dark:text-slate-200 max-w-[180px] truncate">{ins.area}</td>
                  <td className="px-4 py-3 text-slate-600 dark:text-slate-300 whitespace-nowrap">{ins.project}</td>
                  <td className="px-4 py-3 text-slate-600 dark:text-slate-300 whitespace-nowrap">{ins.inspector}</td>
                  <td className="px-4 py-3 text-slate-500 dark:text-slate-400 whitespace-nowrap">{ins.date}</td>
                  <td className="px-4 py-3"><InspectionTypeBadge type={ins.type} /></td>
                  <td className="px-4 py-3"><InspectionStatusBadge status={ins.status} /></td>
                  <td className="px-4 py-3 whitespace-nowrap">
                    <button onClick={() => setViewInspection(ins)}
                      className="px-3 py-1 rounded-lg bg-slate-100 dark:bg-slate-700 text-slate-600 dark:text-slate-300 text-xs hover:bg-slate-200 dark:hover:bg-slate-600 transition-colors mr-2">
                      Ver
                    </button>
                    <button onClick={() => onNewNcr(ins)}
                      className="px-3 py-1 rounded-lg bg-amber-50 dark:bg-amber-900/30 text-amber-700 dark:text-amber-300 text-xs hover:bg-amber-100 dark:hover:bg-amber-900/50 transition-colors">
                      + NCR
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      {viewInspection && (
        <InspectionDetailModal
          inspection={viewInspection}
          onClose={() => setViewInspection(null)}
          onNewNcr={(ins) => { onNewNcr(ins); setViewInspection(null); }}
        />
      )}

      {showNew && (
        <NewInspectionModal
          onClose={() => setShowNew(false)}
          onSave={(ins) => setInspections(p => [...p, ins])}
        />
      )}
    </div>
  );
}

// ─── TAB 1 — No Conformidades ─────────────────────────────────────────────────

function NcrDetailModal({ ncr, onClose, onUpdate }) {
  const [rootCause, setRootCause] = useState(ncr.rootCause);
  const [correctiveAction, setCorrectiveAction] = useState(ncr.correctiveAction);
  const canClose = rootCause.trim() && correctiveAction.trim() && ncr.status !== 'CERRADA';

  function handleSave() {
    onUpdate({ ...ncr, rootCause, correctiveAction });
    onClose();
  }

  function handleCloseNcr() {
    if (!canClose) return;
    onUpdate({ ...ncr, rootCause, correctiveAction, status: 'CERRADA', closedDate: TODAY });
    onClose();
  }

  return (
    <Modal title={`${ncr.id} — ${ncr.title}`} onClose={onClose} wide>
      <div className="space-y-4 text-sm">
        <div className="grid grid-cols-2 gap-3">
          <div><span className="text-slate-500 dark:text-slate-400">Proyecto: </span><span className="font-medium text-slate-800 dark:text-slate-100">{ncr.project}</span></div>
          <div><span className="text-slate-500 dark:text-slate-400">Área: </span><span className="font-medium text-slate-800 dark:text-slate-100">{ncr.area}</span></div>
          <div><span className="text-slate-500 dark:text-slate-400">Detectado por: </span><span className="font-medium text-slate-800 dark:text-slate-100">{ncr.detectedBy}</span></div>
          <div><span className="text-slate-500 dark:text-slate-400">Fecha detección: </span><span className="font-medium text-slate-800 dark:text-slate-100">{ncr.detectedDate}</span></div>
          <div className="flex items-center gap-2"><span className="text-slate-500 dark:text-slate-400">Severidad: </span><SeverityBadge severity={ncr.severity} /></div>
          <div className="flex items-center gap-2"><span className="text-slate-500 dark:text-slate-400">Estado: </span><NcrStatusBadge status={ncr.status} /></div>
          <div><span className="text-slate-500 dark:text-slate-400">Asignado a: </span><span className="font-medium text-slate-800 dark:text-slate-100">{ncr.assignedTo}</span></div>
          <div><span className="text-slate-500 dark:text-slate-400">Vence: </span><span className={`font-medium ${isOverdue(ncr.dueDate, ncr.status) ? 'text-red-600 dark:text-red-400' : 'text-slate-800 dark:text-slate-100'}`}>{ncr.dueDate}</span></div>
          {ncr.closedDate && <div><span className="text-slate-500 dark:text-slate-400">Cerrada: </span><span className="font-medium text-emerald-600 dark:text-emerald-400">{ncr.closedDate}</span></div>}
          <div><span className="text-slate-500 dark:text-slate-400">Inspección ref.: </span><span className="font-mono text-xs text-blue-600 dark:text-blue-400">{ncr.inspectionRef}</span></div>
        </div>

        <Field label="Causa raíz">
          <textarea value={rootCause} onChange={e => setRootCause(e.target.value)} rows={3}
            disabled={ncr.status === 'CERRADA'}
            className={`${inputCls} resize-none disabled:opacity-60`}
            placeholder="Describir la causa raíz identificada..." />
        </Field>
        <Field label="Acción correctiva">
          <textarea value={correctiveAction} onChange={e => setCorrectiveAction(e.target.value)} rows={3}
            disabled={ncr.status === 'CERRADA'}
            className={`${inputCls} resize-none disabled:opacity-60`}
            placeholder="Describir la acción correctiva a implementar..." />
        </Field>

        <div className="flex flex-wrap justify-end gap-2 pt-2">
          {ncr.status !== 'CERRADA' && (
            <button onClick={handleSave} className="px-4 py-2 rounded-xl bg-slate-100 dark:bg-slate-700 text-slate-700 dark:text-slate-200 text-sm font-medium hover:bg-slate-200 dark:hover:bg-slate-600 transition-colors">
              Guardar cambios
            </button>
          )}
          <button
            onClick={handleCloseNcr}
            disabled={!canClose}
            className="px-4 py-2 rounded-xl bg-emerald-600 hover:bg-emerald-700 disabled:opacity-40 disabled:cursor-not-allowed text-white text-sm font-medium transition-colors">
            Cerrar NCR
          </button>
          <button onClick={onClose} className="px-4 py-2 rounded-xl border border-slate-200 dark:border-surface-700 text-slate-600 dark:text-slate-300 text-sm font-medium hover:bg-slate-50 dark:hover:bg-slate-800 transition-colors">
            Cancelar
          </button>
        </div>
      </div>
    </Modal>
  );
}

function NewNcrModal({ onClose, onSave, prefill }) {
  const [form, setForm] = useState({
    title: '', project: prefill?.project || '', area: prefill?.area || '',
    detectedBy: '', detectedDate: TODAY, severity: 'MENOR',
    status: 'ABIERTA', assignedTo: '', dueDate: '',
    rootCause: '', correctiveAction: '',
    inspectionRef: prefill?.code || '',
  });

  function handleSave() {
    if (!form.title || !form.project || !form.assignedTo) return;
    onSave(form);
    onClose();
  }

  return (
    <Modal title="Nueva No Conformidad (NCR)" onClose={onClose} wide>
      <div className="space-y-4">
        <div className="grid grid-cols-1 gap-3">
          <Field label="Título">
            <input value={form.title} onChange={e => setForm(p => ({ ...p, title: e.target.value }))} className={inputCls} placeholder="Descripción breve de la no conformidad" />
          </Field>
        </div>
        <div className="grid grid-cols-2 gap-3">
          <Field label="Proyecto">
            <input value={form.project} onChange={e => setForm(p => ({ ...p, project: e.target.value }))} className={inputCls} />
          </Field>
          <Field label="Área">
            <input value={form.area} onChange={e => setForm(p => ({ ...p, area: e.target.value }))} className={inputCls} />
          </Field>
          <Field label="Detectado por">
            <input value={form.detectedBy} onChange={e => setForm(p => ({ ...p, detectedBy: e.target.value }))} className={inputCls} />
          </Field>
          <Field label="Fecha detección">
            <input type="date" value={form.detectedDate} onChange={e => setForm(p => ({ ...p, detectedDate: e.target.value }))} className={inputCls} />
          </Field>
          <Field label="Severidad">
            <select value={form.severity} onChange={e => setForm(p => ({ ...p, severity: e.target.value }))} className={inputCls}>
              <option value="MENOR">MENOR</option>
              <option value="MAYOR">MAYOR</option>
              <option value="CRITICA">CRITICA</option>
            </select>
          </Field>
          <Field label="Estado">
            <select value={form.status} onChange={e => setForm(p => ({ ...p, status: e.target.value }))} className={inputCls}>
              <option value="ABIERTA">ABIERTA</option>
              <option value="EN_PROCESO">EN_PROCESO</option>
              <option value="CERRADA">CERRADA</option>
            </select>
          </Field>
          <Field label="Asignado a">
            <input value={form.assignedTo} onChange={e => setForm(p => ({ ...p, assignedTo: e.target.value }))} className={inputCls} />
          </Field>
          <Field label="Fecha límite">
            <input type="date" value={form.dueDate} onChange={e => setForm(p => ({ ...p, dueDate: e.target.value }))} className={inputCls} />
          </Field>
          <Field label="Inspección de referencia">
            <input value={form.inspectionRef} onChange={e => setForm(p => ({ ...p, inspectionRef: e.target.value }))} className={inputCls} placeholder="Ej. INS-2026-002" />
          </Field>
        </div>
        <Field label="Causa raíz (opcional)">
          <textarea value={form.rootCause} onChange={e => setForm(p => ({ ...p, rootCause: e.target.value }))} rows={2} className={`${inputCls} resize-none`} />
        </Field>
        <Field label="Acción correctiva (opcional)">
          <textarea value={form.correctiveAction} onChange={e => setForm(p => ({ ...p, correctiveAction: e.target.value }))} rows={2} className={`${inputCls} resize-none`} />
        </Field>
        <div className="flex justify-end gap-2 pt-2">
          <button onClick={onClose} className="px-4 py-2 rounded-xl bg-slate-100 dark:bg-slate-700 text-slate-700 dark:text-slate-200 text-sm font-medium hover:bg-slate-200 dark:hover:bg-slate-600 transition-colors">Cancelar</button>
          <button onClick={handleSave} className="px-4 py-2 rounded-xl bg-blue-600 hover:bg-blue-700 text-white text-sm font-medium transition-colors">Guardar NCR</button>
        </div>
      </div>
    </Modal>
  );
}

function NcrTab({ ncrs, setNcrs, newNcrPrefill, setNewNcrPrefill }) {
  const [viewNcr, setViewNcr] = useState(null);
  const [showNew, setShowNew] = useState(!!newNcrPrefill);

  const total = ncrs.length;
  const abiertas = ncrs.filter(n => n.status === 'ABIERTA').length;
  const enProceso = ncrs.filter(n => n.status === 'EN_PROCESO').length;
  const cerradas = ncrs.filter(n => n.status === 'CERRADA').length;
  const vencidas = ncrs.filter(n => isOverdue(n.dueDate, n.status)).length;

  function handleUpdate(updated) {
    setNcrs(p => p.map(n => n.id === updated.id ? updated : n));
  }

  function handleSaveNew(form) {
    const id = nextNcrId(ncrs);
    setNcrs(p => [...p, { ...form, id, closedDate: null }]);
    setNewNcrPrefill(null);
  }

  return (
    <div className="space-y-5">
      <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
        <KpiCard label="Total NCRs" value={total} />
        <KpiCard label="Abiertas" value={abiertas} color="text-red-600 dark:text-red-400"
          sub={vencidas > 0 ? `⚠ ${vencidas} vencida${vencidas > 1 ? 's' : ''}` : undefined} />
        <KpiCard label="En proceso" value={enProceso} color="text-amber-600 dark:text-amber-400" />
        <KpiCard label="Cerradas" value={cerradas} color="text-emerald-600 dark:text-emerald-400" />
      </div>

      {vencidas > 0 && (
        <div className="rounded-2xl border border-red-200 dark:border-red-800/50 bg-red-50 dark:bg-red-900/20 px-4 py-3 flex items-center gap-3">
          <span className="text-red-500 text-lg">⚠</span>
          <p className="text-sm text-red-700 dark:text-red-300 font-medium">
            {vencidas} NCR{vencidas > 1 ? 's' : ''} vencida{vencidas > 1 ? 's' : ''} — requiere atención inmediata.
          </p>
        </div>
      )}

      <div className="rounded-2xl border border-slate-200 dark:border-surface-700 bg-white dark:bg-slate-900 overflow-hidden">
        <div className="flex items-center justify-between px-5 py-4 border-b border-slate-100 dark:border-surface-700">
          <h3 className="font-semibold text-slate-800 dark:text-slate-100">No Conformidades</h3>
          <button onClick={() => setShowNew(true)}
            className="px-4 py-2 rounded-xl bg-amber-500 hover:bg-amber-600 text-white text-sm font-medium transition-colors">
            + Nueva NCR
          </button>
        </div>
        <div className="overflow-x-auto">
          <table className="w-full text-sm">
            <thead>
              <tr className="bg-slate-50 dark:bg-slate-800 text-slate-500 dark:text-slate-400 text-left">
                {['ID', 'Título', 'Proyecto', 'Severidad', 'Asignado a', 'Vence', 'Estado', 'Días abierta'].map(h => (
                  <th key={h} className="px-4 py-3 font-medium whitespace-nowrap">{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {ncrs.map((ncr) => {
                const overdue = isOverdue(ncr.dueDate, ncr.status);
                return (
                  <tr key={ncr.id}
                    className={`border-t border-slate-100 dark:border-surface-700 hover:bg-slate-50 dark:hover:bg-slate-800/50 transition-colors cursor-pointer ${overdue ? 'bg-red-50/60 dark:bg-red-900/10' : ''}`}
                    onClick={() => setViewNcr(ncr)}>
                    <td className="px-4 py-3 font-mono text-xs text-slate-600 dark:text-slate-300 whitespace-nowrap">{ncr.id}</td>
                    <td className="px-4 py-3 text-slate-700 dark:text-slate-200 max-w-[200px] truncate">{ncr.title}</td>
                    <td className="px-4 py-3 text-slate-600 dark:text-slate-300 whitespace-nowrap">{ncr.project}</td>
                    <td className="px-4 py-3"><SeverityBadge severity={ncr.severity} /></td>
                    <td className="px-4 py-3 text-slate-600 dark:text-slate-300 whitespace-nowrap">{ncr.assignedTo}</td>
                    <td className={`px-4 py-3 whitespace-nowrap font-medium ${overdue ? 'text-red-600 dark:text-red-400' : 'text-slate-600 dark:text-slate-300'}`}>{ncr.dueDate}</td>
                    <td className="px-4 py-3"><NcrStatusBadge status={ncr.status} /></td>
                    <td className="px-4 py-3 text-slate-500 dark:text-slate-400 whitespace-nowrap">
                      {ncr.status === 'CERRADA' ? '—' : `${daysSince(ncr.detectedDate)} días`}
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      </div>

      {viewNcr && (
        <NcrDetailModal
          ncr={viewNcr}
          onClose={() => setViewNcr(null)}
          onUpdate={handleUpdate}
        />
      )}

      {(showNew || newNcrPrefill) && (
        <NewNcrModal
          onClose={() => { setShowNew(false); setNewNcrPrefill(null); }}
          onSave={handleSaveNew}
          prefill={newNcrPrefill}
        />
      )}
    </div>
  );
}

// ─── Mock data for new tabs ───────────────────────────────────────────────────

const DOD_CONSTRUCTION = [
  { id: 'dc1', item: 'Planos aprobados y firmados en sitio', role: 'Ing. Residente', mandatory: true },
  { id: 'dc2', item: 'Materiales en sitio con certificado de calidad', role: 'Almacenista', mandatory: true },
  { id: 'dc3', item: 'Personal con certificación vigente', role: 'RRHH / HSE', mandatory: true },
  { id: 'dc4', item: 'Permiso de trabajo activo (PTW)', role: 'Supervisor HSE', mandatory: true },
  { id: 'dc5', item: 'Supervisor presente durante ejecución', role: 'Supervisor', mandatory: true },
  { id: 'dc6', item: 'EPP verificado para todo el personal', role: 'HSE', mandatory: true },
  { id: 'dc7', item: 'Check HSE pre-tarea completado', role: 'HSE', mandatory: false },
  { id: 'dc8', item: 'Inspección QC programada y notificada', role: 'QC Inspector', mandatory: false },
];

const DOD_SOFTWARE = [
  { id: 'ds1', item: 'Código revisado por al menos un par (Code Review)', role: 'Dev Team', mandatory: true },
  { id: 'ds2', item: 'Tests unitarios con cobertura > 80%', role: 'QA / Dev', mandatory: true },
  { id: 'ds3', item: 'Sin vulnerabilidades críticas (SAST scan)', role: 'DevSecOps', mandatory: true },
  { id: 'ds4', item: 'Documentación técnica actualizada', role: 'Tech Lead', mandatory: true },
  { id: 'ds5', item: 'Aprobación formal del equipo QA', role: 'QA Lead', mandatory: true },
  { id: 'ds6', item: 'Demo completada con cliente o Product Owner', role: 'PM', mandatory: false },
  { id: 'ds7', item: 'Deployment exitoso en entorno Staging', role: 'DevOps', mandatory: true },
  { id: 'ds8', item: 'Plan de rollback documentado y probado', role: 'DevOps', mandatory: false },
];

// projectId → dod template
const DOD_BY_PROJECT = {
  p1: DOD_CONSTRUCTION, // AR-ProjectManagement
  p2: DOD_SOFTWARE,     // AR-ProjectManagement — usamos software como genérico
  p3: DOD_SOFTWARE,     // AR-ProjectManagement
  p4: DOD_SOFTWARE,     // AR-ProjectManagement
};

const DOD_PROJECT_NAMES = {
  p1: 'Construcción AR-ProjectManagement Norte',
  p2: 'AR-ProjectManagement "Horizontes"',
  p3: 'Implementación AR-ProjectManagement',
  p4: 'AR-ProjectManagement — Plataforma ERP',
};

const MOCK_AUDITS = [
  {
    id: 'AUD-2026-001', code: 'AUD-2026-001', type: 'PROGRAMADA',
    projectId: 'p4', project: 'AR-ProjectManagement',
    scope: 'Sistema de gestión de calidad — Fase estructural',
    auditor: 'Arq. Carmen Ríos', date: '2026-07-10',
    status: 'PROGRAMADA', checklistTemplate: 'ISO 9001:2015',
    findings: [],
  },
  {
    id: 'AUD-2026-002', code: 'AUD-2026-002', type: 'SORPRESA',
    projectId: 'p4', project: 'AR-ProjectManagement',
    scope: 'Cumplimiento HSE en área de excavación',
    auditor: 'Ing. Marco Fuentes', date: '2026-06-20',
    status: 'CON_HALLAZGOS', checklistTemplate: 'HSE-STD-001',
    findings: [
      { id: 'F001', description: 'Señalización de riesgo faltante en perímetro zona sur', severity: 'MAYOR' },
      { id: 'F002', description: 'Registro de inducción incompleto para 3 trabajadores', severity: 'MENOR' },
      { id: 'F003', description: 'Extintores sin revisión mensual en módulo temporal', severity: 'OBSERVACION' },
    ],
  },
  {
    id: 'AUD-2026-003', code: 'AUD-2026-003', type: 'GATE_REVIEW',
    projectId: 'p4', project: 'AR-ProjectManagement',
    scope: 'Gate Review — Fin de fase diseño técnico',
    auditor: 'Paula Soto / Comité directivo', date: '2026-06-25',
    status: 'COMPLETADA', checklistTemplate: 'Gate-Review-TI-v2',
    findings: [
      { id: 'F004', description: 'Arquitectura aprobada con condición: revisar modelo de seguridad RBAC', severity: 'MENOR' },
    ],
  },
  {
    id: 'AUD-2026-004', code: 'AUD-2026-004', type: 'PROGRAMADA',
    projectId: 'p4', project: 'AR-ProjectManagement',
    scope: 'Revisión de calidad de código y cobertura de tests',
    auditor: 'Álvaro Romero', date: '2026-07-15',
    status: 'EN_CURSO', checklistTemplate: 'DEV-QA-STD-002',
    findings: [
      { id: 'F005', description: 'Módulo Kanban sin tests de integración', severity: 'MAYOR' },
      { id: 'F006', description: 'Variables de entorno no documentadas en README', severity: 'OBSERVACION' },
    ],
  },
];

const QUALITY_TREND = [
  { mes: 'Ene', score: 62 },
  { mes: 'Feb', score: 68 },
  { mes: 'Mar', score: 71 },
  { mes: 'Abr', score: 75 },
  { mes: 'May', score: 79 },
  { mes: 'Jun', score: 83 },
];

const QUALITY_RADAR_DATA = [
  { axis: 'Inspecciones', value: 88 },
  { axis: 'NCRs', value: 72 },
  { axis: 'DoD', value: 80 },
  { axis: 'Auditorías', value: 75 },
  { axis: 'Satisfacción', value: 90 },
];

const QUALITY_BY_PROJECT = [
  { project: 'AR-ProjectManagement', score: 79, grade: 'C' },
  { project: 'AR-ProjectManagement', score: 91, grade: 'A' },
  { project: 'AR-ProjectManagement', score: 84, grade: 'B' },
  { project: 'AR-ProjectManagement', score: 88, grade: 'B' },
];

// ─── DoD Helpers ──────────────────────────────────────────────────────────────

function gradeFromScore(s) {
  if (s >= 90) return 'A';
  if (s >= 80) return 'B';
  if (s >= 70) return 'C';
  if (s >= 60) return 'D';
  return 'F';
}

function gradeColor(g) {
  const m = { A: 'text-emerald-600 dark:text-emerald-400', B: 'text-blue-600 dark:text-blue-400', C: 'text-amber-600 dark:text-amber-400', D: 'text-orange-600 dark:text-orange-400', F: 'text-red-600 dark:text-red-400' };
  return m[g] || 'text-slate-500';
}

// ─── TAB 3 — Definición de Listo (DoD) ───────────────────────────────────────

function DodTab() {
  const ALL_PROJECT_IDS = ['p4', 'p4', 'p4', 'p4'];
  const [checks, setChecks] = useState(() => {
    const init = {};
    ALL_PROJECT_IDS.forEach(pid => {
      const items = DOD_BY_PROJECT[pid] || [];
      items.forEach(it => { init[`${pid}_${it.id}`] = false; });
    });
    return init;
  });
  const [blockingActive, setBlockingActive] = useState({ p1: false, p2: false, p3: false, p4: false });
  const [saved, setSaved] = useState(false);

  function toggleCheck(pid, iid) {
    setChecks(p => ({ ...p, [`${pid}_${iid}`]: !p[`${pid}_${iid}`] }));
    setSaved(false);
  }

  function handleSave() { setSaved(true); }

  return (
    <div className="space-y-6">
      <div className="rounded-2xl border border-blue-200 dark:border-blue-800/50 bg-blue-50 dark:bg-blue-900/20 px-5 py-4">
        <p className="text-sm text-blue-800 dark:text-blue-200">
          <strong>Definición de Listo (DoD):</strong> La Definición de Listo establece los criterios mínimos que debe cumplir una tarea antes de considerarse completada. Si no cumple el DoD, el Kanban bloquea el movimiento a <span className="font-mono font-semibold">COMPLETADA</span>.
        </p>
      </div>

      {ALL_PROJECT_IDS.map(pid => {
        const items = DOD_BY_PROJECT[pid] || [];
        const name = DOD_PROJECT_NAMES[pid];
        const isBlocking = blockingActive[pid];
        const mandatoryItems = items.filter(i => i.mandatory);
        const allMandatoryDone = mandatoryItems.every(i => checks[`${pid}_${i.id}`]);

        return (
          <div key={pid} className="rounded-2xl border border-slate-200 dark:border-surface-700 bg-white dark:bg-slate-900 overflow-hidden">
            <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-2 px-5 py-4 border-b border-slate-100 dark:border-surface-700">
              <div>
                <h3 className="font-semibold text-slate-800 dark:text-slate-100 text-sm">{name}</h3>
                <p className="text-xs text-slate-400 mt-0.5">{mandatoryItems.length} criterios obligatorios · {items.length - mandatoryItems.length} opcionales</p>
              </div>
              <label className="flex items-center gap-2 cursor-pointer select-none">
                <span className="text-xs font-medium text-slate-500 dark:text-slate-400">Bloqueo activo</span>
                <div
                  onClick={() => setBlockingActive(p => ({ ...p, [pid]: !p[pid] }))}
                  className={`relative w-10 h-5 rounded-full transition-colors cursor-pointer ${isBlocking ? 'bg-red-500' : 'bg-slate-200 dark:bg-slate-700'}`}>
                  <span className={`absolute top-0.5 left-0.5 w-4 h-4 bg-white rounded-full shadow transition-transform ${isBlocking ? 'translate-x-5' : 'translate-x-0'}`} />
                </div>
              </label>
            </div>

            {isBlocking && !allMandatoryDone && (
              <div className="mx-5 mt-4 rounded-xl bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800/50 px-4 py-3">
                <p className="text-sm font-semibold text-red-700 dark:text-red-300">DoD activo: las tareas no pueden completarse sin cumplir todos los criterios obligatorios</p>
              </div>
            )}

            {isBlocking && allMandatoryDone && (
              <div className="mx-5 mt-4 rounded-xl bg-emerald-50 dark:bg-emerald-900/20 border border-emerald-200 dark:border-emerald-800/50 px-4 py-3">
                <p className="text-sm font-semibold text-emerald-700 dark:text-emerald-300">Todos los criterios obligatorios cumplidos — movimiento a COMPLETADA habilitado</p>
              </div>
            )}

            <div className="p-5 space-y-2">
              {items.map(it => {
                const key = `${pid}_${it.id}`;
                const checked = checks[key];
                return (
                  <div key={it.id} className={`flex items-start gap-3 rounded-xl p-3 border transition-colors ${checked ? 'border-emerald-200 bg-emerald-50 dark:border-emerald-800/40 dark:bg-emerald-900/10' : 'border-slate-100 dark:border-slate-800 bg-slate-50 dark:bg-slate-800/30'}`}>
                    <input type="checkbox" checked={checked} onChange={() => toggleCheck(pid, it.id)}
                      className="mt-0.5 accent-emerald-500 flex-shrink-0 w-4 h-4" />
                    <div className="flex-1 min-w-0">
                      <p className={`text-sm ${checked ? 'line-through text-slate-400 dark:text-slate-500' : 'text-slate-700 dark:text-slate-200'}`}>{it.item}</p>
                      <p className="text-xs text-slate-400 dark:text-slate-500 mt-0.5">Responsable: {it.role}</p>
                    </div>
                    <span className={`flex-shrink-0 rounded-full px-2 py-0.5 text-xs font-medium ${it.mandatory ? 'bg-red-100 text-red-700 dark:bg-red-900/40 dark:text-red-300' : 'bg-slate-100 text-slate-500 dark:bg-slate-700 dark:text-slate-400'}`}>
                      {it.mandatory ? 'Obligatorio' : 'Opcional'}
                    </span>
                  </div>
                );
              })}
            </div>
          </div>
        );
      })}

      <div className="flex justify-end">
        <button onClick={handleSave}
          className="px-5 py-2.5 rounded-xl bg-blue-600 hover:bg-blue-700 text-white text-sm font-medium transition-colors">
          {saved ? 'Configuración guardada' : 'Guardar configuración DoD'}
        </button>
      </div>
    </div>
  );
}

// ─── TAB 4 — Score de Calidad ─────────────────────────────────────────────────

const SCORE_COMPONENTS = [
  { label: 'Tasa de aprobación en inspecciones', weight: 40, score: 88, color: '#3b82f6' },
  { label: 'Tiempo promedio resolución NCR', weight: 30, score: 72, color: '#f59e0b' },
  { label: 'Cumplimiento DoD (criterios obligatorios)', weight: 20, score: 80, color: '#8b5cf6' },
  { label: 'Satisfacción cliente (CSAT)', weight: 10, score: 90, color: '#10b981' },
];

function QualityScoreTab() {
  const overall = Math.round(
    SCORE_COMPONENTS.reduce((acc, c) => acc + c.score * (c.weight / 100), 0)
  );
  const grade = gradeFromScore(overall);

  return (
    <div className="space-y-6">
      {/* Overall score */}
      <div className="rounded-2xl border border-slate-200 dark:border-surface-700 bg-white dark:bg-slate-900 p-6">
        <div className="flex flex-col sm:flex-row sm:items-center gap-6">
          <div className="flex flex-col items-center justify-center w-36 h-36 rounded-2xl bg-slate-50 dark:bg-slate-800 border border-slate-100 dark:border-slate-700 flex-shrink-0">
            <span className="text-5xl font-bold text-slate-900 dark:text-white">{overall}</span>
            <span className={`text-2xl font-bold mt-1 ${gradeColor(grade)}`}>{grade}</span>
            <span className="text-xs text-slate-400 mt-0.5">/ 100</span>
          </div>
          <div className="flex-1">
            <h3 className="font-bold text-slate-800 dark:text-slate-100 text-lg mb-1">Score Global de Calidad</h3>
            <p className="text-xs text-slate-500 dark:text-slate-400 mb-3">
              <strong>Fórmula:</strong> Tasa aprobación (40%) + Tiempo resolución NCR (30%) + Cumplimiento DoD (20%) + Satisfacción cliente (10%)
            </p>
            <div className="w-full bg-slate-200 dark:bg-slate-700 rounded-full h-3">
              <div className="bg-blue-500 h-3 rounded-full transition-all" style={{ width: `${overall}%` }} />
            </div>
          </div>
        </div>
      </div>

      {/* Component breakdown */}
      <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
        {SCORE_COMPONENTS.map((c, i) => (
          <div key={i} className="rounded-2xl border border-slate-200 dark:border-surface-700 bg-white dark:bg-slate-900 p-4">
            <div className="flex items-start justify-between gap-2 mb-2">
              <p className="text-sm text-slate-700 dark:text-slate-200 font-medium leading-snug">{c.label}</p>
              <span className="text-xs text-slate-400 flex-shrink-0">Peso: {c.weight}%</span>
            </div>
            <div className="flex items-center gap-3">
              <div className="flex-1 bg-slate-100 dark:bg-slate-700 rounded-full h-2">
                <div className="h-2 rounded-full" style={{ width: `${c.score}%`, backgroundColor: c.color }} />
              </div>
              <span className="text-lg font-bold" style={{ color: c.color }}>{c.score}</span>
            </div>
          </div>
        ))}
      </div>

      {/* RadarChart */}
      <div className="rounded-2xl border border-slate-200 dark:border-surface-700 bg-white dark:bg-slate-900 p-6">
        <h3 className="font-semibold text-slate-800 dark:text-slate-100 mb-4">Radar de Calidad</h3>
        <ResponsiveContainer width="100%" height={300}>
          <RadarChart data={QUALITY_RADAR_DATA}>
            <PolarGrid stroke="#e2e8f0" />
            <PolarAngleAxis dataKey="axis" tick={{ fill: '#94a3b8', fontSize: 12 }} />
            <PolarRadiusAxis angle={30} domain={[0, 100]} tick={{ fill: '#94a3b8', fontSize: 10 }} />
            <Radar name="Score" dataKey="value" stroke="#3b82f6" fill="#3b82f6" fillOpacity={0.25} />
          </RadarChart>
        </ResponsiveContainer>
      </div>

      {/* Trend chart */}
      <div className="rounded-2xl border border-slate-200 dark:border-surface-700 bg-white dark:bg-slate-900 p-6">
        <h3 className="font-semibold text-slate-800 dark:text-slate-100 mb-4">Evolución del Score (últimos 6 meses)</h3>
        <ResponsiveContainer width="100%" height={240}>
          <LineChart data={QUALITY_TREND}>
            <CartesianGrid strokeDasharray="3 3" stroke="#e2e8f0" />
            <XAxis dataKey="mes" tick={{ fill: '#94a3b8', fontSize: 12 }} />
            <YAxis domain={[50, 100]} tick={{ fill: '#94a3b8', fontSize: 12 }} />
            <Tooltip contentStyle={{ background: '#1e293b', border: '1px solid #334155', borderRadius: 8, color: '#f1f5f9' }} />
            <Line type="monotone" dataKey="score" stroke="#3b82f6" strokeWidth={2.5} dot={{ fill: '#3b82f6', r: 4 }} name="Score QC" />
          </LineChart>
        </ResponsiveContainer>
      </div>

      {/* Comparison table */}
      <div className="rounded-2xl border border-slate-200 dark:border-surface-700 bg-white dark:bg-slate-900 overflow-hidden">
        <div className="px-5 py-4 border-b border-slate-100 dark:border-surface-700">
          <h3 className="font-semibold text-slate-800 dark:text-slate-100">Score por Proyecto</h3>
        </div>
        <table className="w-full text-sm">
          <thead>
            <tr className="bg-slate-50 dark:bg-slate-800 text-left">
              <th className="text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase px-4 py-3">Proyecto</th>
              <th className="text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase px-4 py-3">Score</th>
              <th className="text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase px-4 py-3">Nota</th>
              <th className="text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase px-4 py-3">Barra</th>
            </tr>
          </thead>
          <tbody>
            {QUALITY_BY_PROJECT.map((row, i) => (
              <tr key={i} className="border-t border-slate-100 dark:border-surface-700 hover:bg-slate-50 dark:hover:bg-slate-800/40">
                <td className="px-4 py-3 text-slate-700 dark:text-slate-200 font-medium">{row.project}</td>
                <td className="px-4 py-3 text-slate-800 dark:text-slate-100 font-bold">{row.score}</td>
                <td className={`px-4 py-3 font-bold text-lg ${gradeColor(row.grade)}`}>{row.grade}</td>
                <td className="px-4 py-3 min-w-[120px]">
                  <div className="w-full bg-slate-100 dark:bg-slate-700 rounded-full h-2">
                    <div className="bg-blue-500 h-2 rounded-full" style={{ width: `${row.score}%` }} />
                  </div>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

// ─── TAB 5 — Auditorías ───────────────────────────────────────────────────────

function AuditTypeBadge({ type }) {
  const map = {
    PROGRAMADA: 'bg-blue-100 text-blue-700 dark:bg-blue-900/40 dark:text-blue-300',
    SORPRESA: 'bg-purple-100 text-purple-700 dark:bg-purple-900/40 dark:text-purple-300',
    GATE_REVIEW: 'bg-amber-100 text-amber-700 dark:bg-amber-900/40 dark:text-amber-300',
  };
  return <span className={`px-2 py-0.5 rounded-full text-xs font-medium ${map[type] || 'bg-slate-100 text-slate-500'}`}>{type.replace('_', ' ')}</span>;
}

function AuditStatusBadge({ status }) {
  const map = {
    PROGRAMADA: 'bg-slate-100 text-slate-500 dark:bg-slate-700 dark:text-slate-400',
    EN_CURSO: 'bg-blue-100 text-blue-700 dark:bg-blue-900/40 dark:text-blue-300',
    COMPLETADA: 'bg-emerald-100 text-emerald-700 dark:bg-emerald-900/40 dark:text-emerald-300',
    CON_HALLAZGOS: 'bg-red-100 text-red-700 dark:bg-red-900/40 dark:text-red-300',
  };
  return <span className={`px-2 py-0.5 rounded-full text-xs font-medium ${map[status] || 'bg-slate-100 text-slate-500'}`}>{status.replace('_', ' ')}</span>;
}

function FindingSeverityBadge({ severity }) {
  const map = {
    CRITICO: 'bg-red-100 text-red-700 dark:bg-red-900/40 dark:text-red-300',
    MAYOR: 'bg-amber-100 text-amber-700 dark:bg-amber-900/40 dark:text-amber-300',
    MENOR: 'bg-blue-100 text-blue-700 dark:bg-blue-900/40 dark:text-blue-300',
    OBSERVACION: 'bg-slate-100 text-slate-500 dark:bg-slate-700 dark:text-slate-400',
  };
  return <span className={`px-2 py-0.5 rounded-full text-xs font-medium ${map[severity] || 'bg-slate-100 text-slate-500'}`}>{severity}</span>;
}

function AuditDetailModal({ audit, onClose }) {
  return (
    <Modal title={`${audit.code} — ${audit.scope}`} onClose={onClose} wide>
      <div className="space-y-4 text-sm">
        <div className="grid grid-cols-2 gap-3">
          <div><span className="text-slate-500 dark:text-slate-400">Tipo: </span><AuditTypeBadge type={audit.type} /></div>
          <div><span className="text-slate-500 dark:text-slate-400">Estado: </span><AuditStatusBadge status={audit.status} /></div>
          <div><span className="text-slate-500 dark:text-slate-400">Proyecto: </span><span className="font-medium text-slate-800 dark:text-slate-100">{audit.project}</span></div>
          <div><span className="text-slate-500 dark:text-slate-400">Fecha: </span><span className="font-medium text-slate-800 dark:text-slate-100">{audit.date}</span></div>
          <div className="col-span-2"><span className="text-slate-500 dark:text-slate-400">Auditor: </span><span className="font-medium text-slate-800 dark:text-slate-100">{audit.auditor}</span></div>
          <div className="col-span-2"><span className="text-slate-500 dark:text-slate-400">Plantilla: </span><span className="font-mono text-xs text-blue-600 dark:text-blue-400">{audit.checklistTemplate}</span></div>
        </div>

        {audit.type === 'GATE_REVIEW' && (
          <div className="rounded-xl border border-amber-200 dark:border-amber-800/50 bg-amber-50 dark:bg-amber-900/20 px-4 py-3">
            <p className="text-xs font-semibold text-amber-700 dark:text-amber-300">Gate Review — Esta auditoría debe aprobarse antes de que el proyecto avance a la siguiente fase.</p>
          </div>
        )}

        {audit.findings.length > 0 ? (
          <div>
            <h4 className="font-semibold text-slate-700 dark:text-slate-200 mb-2">Hallazgos ({audit.findings.length})</h4>
            <div className="space-y-2">
              {audit.findings.map(f => (
                <div key={f.id} className="flex items-start gap-3 p-3 rounded-xl border border-slate-100 dark:border-slate-800 bg-slate-50 dark:bg-slate-800/30">
                  <span className="font-mono text-xs text-slate-400 flex-shrink-0 mt-0.5">{f.id}</span>
                  <p className="text-slate-700 dark:text-slate-200 flex-1">{f.description}</p>
                  <FindingSeverityBadge severity={f.severity} />
                </div>
              ))}
            </div>
          </div>
        ) : (
          <p className="text-slate-400 dark:text-slate-500 text-xs">Sin hallazgos registrados.</p>
        )}

        <div className="flex justify-end pt-2">
          <button onClick={onClose} className="px-4 py-2 rounded-xl bg-slate-100 dark:bg-slate-700 text-slate-700 dark:text-slate-200 text-sm font-medium hover:bg-slate-200 dark:hover:bg-slate-600 transition-colors">Cerrar</button>
        </div>
      </div>
    </Modal>
  );
}

function NewAuditModal({ onClose, onSave }) {
  const [form, setForm] = useState({
    type: 'PROGRAMADA', projectId: 'p4', scope: '', auditor: '', date: TODAY,
    checklistTemplate: 'ISO 9001:2015', status: 'PROGRAMADA',
  });

  const projectOptions = [
    { id: 'p4', name: 'AR-ProjectManagement' },
    { id: 'p4', name: 'AR-ProjectManagement "Horizontes"' },
    { id: 'p4', name: 'AR-ProjectManagement' },
    { id: 'p4', name: 'AR-ProjectManagement' },
  ];

  const templateOptions = ['ISO 9001:2015', 'HSE-STD-001', 'Gate-Review-TI-v2', 'DEV-QA-STD-002', 'Personalizado'];

  function handleSave() {
    if (!form.scope || !form.auditor) return;
    const projObj = projectOptions.find(p => p.id === form.projectId);
    onSave({ ...form, project: projObj?.name || form.projectId, findings: [] });
    onClose();
  }

  return (
    <Modal title="Nueva Auditoría" onClose={onClose} wide>
      <div className="space-y-4">
        <div className="grid grid-cols-2 gap-3">
          <Field label="Tipo">
            <select value={form.type} onChange={e => setForm(p => ({ ...p, type: e.target.value }))} className={inputCls}>
              <option value="PROGRAMADA">PROGRAMADA</option>
              <option value="SORPRESA">SORPRESA</option>
              <option value="GATE_REVIEW">GATE REVIEW</option>
            </select>
          </Field>
          <Field label="Estado">
            <select value={form.status} onChange={e => setForm(p => ({ ...p, status: e.target.value }))} className={inputCls}>
              <option value="PROGRAMADA">PROGRAMADA</option>
              <option value="EN_CURSO">EN CURSO</option>
              <option value="COMPLETADA">COMPLETADA</option>
              <option value="CON_HALLAZGOS">CON HALLAZGOS</option>
            </select>
          </Field>
          <Field label="Proyecto">
            <select value={form.projectId} onChange={e => setForm(p => ({ ...p, projectId: e.target.value }))} className={inputCls}>
              {projectOptions.map(p => <option key={p.id} value={p.id}>{p.name}</option>)}
            </select>
          </Field>
          <Field label="Fecha">
            <input type="date" value={form.date} onChange={e => setForm(p => ({ ...p, date: e.target.value }))} className={inputCls} />
          </Field>
          <Field label="Auditor">
            <input value={form.auditor} onChange={e => setForm(p => ({ ...p, auditor: e.target.value }))} className={inputCls} placeholder="Nombre del auditor" />
          </Field>
          <Field label="Plantilla checklist">
            <select value={form.checklistTemplate} onChange={e => setForm(p => ({ ...p, checklistTemplate: e.target.value }))} className={inputCls}>
              {templateOptions.map(t => <option key={t} value={t}>{t}</option>)}
            </select>
          </Field>
        </div>
        <Field label="Alcance">
          <textarea value={form.scope} onChange={e => setForm(p => ({ ...p, scope: e.target.value }))} rows={2} className={`${inputCls} resize-none`} placeholder="Describir el alcance de la auditoría..." />
        </Field>
        <div className="flex justify-end gap-2 pt-2">
          <button onClick={onClose} className="px-4 py-2 rounded-xl bg-slate-100 dark:bg-slate-700 text-slate-700 dark:text-slate-200 text-sm font-medium hover:bg-slate-200 dark:hover:bg-slate-600 transition-colors">Cancelar</button>
          <button onClick={handleSave} className="px-4 py-2 rounded-xl bg-blue-600 hover:bg-blue-700 text-white text-sm font-medium transition-colors">Crear auditoría</button>
        </div>
      </div>
    </Modal>
  );
}

function AuditoriasTab() {
  const [audits, setAudits] = useState(MOCK_AUDITS);
  const [viewAudit, setViewAudit] = useState(null);
  const [showNew, setShowNew] = useState(false);

  const programadas = audits.filter(a => a.status === 'PROGRAMADA').length;
  const enCurso = audits.filter(a => a.status === 'EN_CURSO').length;
  const completadas = audits.filter(a => a.status === 'COMPLETADA').length;
  const conHallazgos = audits.filter(a => a.status === 'CON_HALLAZGOS').length;
  const totalFindings = audits.reduce((s, a) => s + a.findings.length, 0);

  function handleSave(newAudit) {
    const num = audits.length + 1;
    const code = `AUD-2026-${String(num + 4).padStart(3, '0')}`;
    setAudits(p => [...p, { ...newAudit, id: code, code }]);
  }

  return (
    <div className="space-y-5">
      <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
        <KpiCard label="Programadas" value={programadas} color="text-slate-600 dark:text-slate-300" />
        <KpiCard label="En curso" value={enCurso} color="text-blue-600 dark:text-blue-400" />
        <KpiCard label="Completadas" value={completadas} color="text-emerald-600 dark:text-emerald-400" />
        <KpiCard label="Con hallazgos" value={conHallazgos} color="text-red-600 dark:text-red-400" sub={`${totalFindings} hallazgos totales`} />
      </div>

      <div className="rounded-2xl border border-slate-200 dark:border-surface-700 bg-white dark:bg-slate-900 overflow-hidden">
        <div className="flex items-center justify-between px-5 py-4 border-b border-slate-100 dark:border-surface-700">
          <h3 className="font-semibold text-slate-800 dark:text-slate-100">Auditorías de Calidad</h3>
          <button onClick={() => setShowNew(true)}
            className="px-4 py-2 rounded-xl bg-blue-600 hover:bg-blue-700 text-white text-sm font-medium transition-colors">
            + Nueva Auditoría
          </button>
        </div>
        <div className="overflow-x-auto">
          <table className="w-full text-sm">
            <thead>
              <tr className="bg-slate-50 dark:bg-slate-800 text-left">
                {['Código', 'Tipo', 'Proyecto', 'Alcance', 'Auditor', 'Fecha', 'Hallazgos', 'Estado'].map(h => (
                  <th key={h} className="text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase px-4 py-3 whitespace-nowrap">{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {audits.map((a) => (
                <tr key={a.id}
                  className="border-t border-slate-100 dark:border-surface-700 hover:bg-slate-50 dark:hover:bg-slate-800/40 cursor-pointer transition-colors"
                  onClick={() => setViewAudit(a)}>
                  <td className="px-4 py-3 font-mono text-xs text-slate-600 dark:text-slate-300 whitespace-nowrap">{a.code}</td>
                  <td className="px-4 py-3"><AuditTypeBadge type={a.type} /></td>
                  <td className="px-4 py-3 text-slate-700 dark:text-slate-200 whitespace-nowrap">{a.project}</td>
                  <td className="px-4 py-3 text-slate-600 dark:text-slate-300 max-w-[200px] truncate">{a.scope}</td>
                  <td className="px-4 py-3 text-slate-600 dark:text-slate-300 whitespace-nowrap">{a.auditor}</td>
                  <td className="px-4 py-3 text-slate-500 dark:text-slate-400 whitespace-nowrap">{a.date}</td>
                  <td className="px-4 py-3 text-center">
                    <span className={`inline-flex items-center justify-center w-7 h-7 rounded-full text-xs font-bold ${a.findings.length > 0 ? 'bg-red-100 text-red-700 dark:bg-red-900/40 dark:text-red-300' : 'bg-slate-100 text-slate-500 dark:bg-slate-700 dark:text-slate-400'}`}>
                      {a.findings.length}
                    </span>
                  </td>
                  <td className="px-4 py-3"><AuditStatusBadge status={a.status} /></td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      {viewAudit && <AuditDetailModal audit={viewAudit} onClose={() => setViewAudit(null)} />}
      {showNew && <NewAuditModal onClose={() => setShowNew(false)} onSave={handleSave} />}
    </div>
  );
}

// ─── TAB 2 — Punch List ───────────────────────────────────────────────────────

const PUNCH_STATUS_CYCLE = { PENDIENTE: 'EN_PROCESO', EN_PROCESO: 'COMPLETADO', COMPLETADO: 'PENDIENTE' };

function NewPunchModal({ onClose, onSave }) {
  const [form, setForm] = useState({
    description: '', area: '', project: '', assignedTo: '',
    dueDate: '', status: 'PENDIENTE', priority: 'MEDIA',
  });

  function handleSave() {
    if (!form.description || !form.project) return;
    onSave(form);
    onClose();
  }

  return (
    <Modal title="Nuevo ítem — Punch List" onClose={onClose}>
      <div className="space-y-4">
        <Field label="Descripción">
          <textarea value={form.description} onChange={e => setForm(p => ({ ...p, description: e.target.value }))} rows={3} className={`${inputCls} resize-none`} />
        </Field>
        <div className="grid grid-cols-2 gap-3">
          <Field label="Área"><input value={form.area} onChange={e => setForm(p => ({ ...p, area: e.target.value }))} className={inputCls} /></Field>
          <Field label="Proyecto"><input value={form.project} onChange={e => setForm(p => ({ ...p, project: e.target.value }))} className={inputCls} /></Field>
          <Field label="Asignado a"><input value={form.assignedTo} onChange={e => setForm(p => ({ ...p, assignedTo: e.target.value }))} className={inputCls} /></Field>
          <Field label="Fecha límite"><input type="date" value={form.dueDate} onChange={e => setForm(p => ({ ...p, dueDate: e.target.value }))} className={inputCls} /></Field>
          <Field label="Prioridad">
            <select value={form.priority} onChange={e => setForm(p => ({ ...p, priority: e.target.value }))} className={inputCls}>
              <option value="ALTA">ALTA</option>
              <option value="MEDIA">MEDIA</option>
              <option value="BAJA">BAJA</option>
            </select>
          </Field>
          <Field label="Estado">
            <select value={form.status} onChange={e => setForm(p => ({ ...p, status: e.target.value }))} className={inputCls}>
              <option value="PENDIENTE">PENDIENTE</option>
              <option value="EN_PROCESO">EN_PROCESO</option>
              <option value="COMPLETADO">COMPLETADO</option>
            </select>
          </Field>
        </div>
        <div className="flex justify-end gap-2 pt-2">
          <button onClick={onClose} className="px-4 py-2 rounded-xl bg-slate-100 dark:bg-slate-700 text-slate-700 dark:text-slate-200 text-sm font-medium hover:bg-slate-200 dark:hover:bg-slate-600 transition-colors">Cancelar</button>
          <button onClick={handleSave} className="px-4 py-2 rounded-xl bg-blue-600 hover:bg-blue-700 text-white text-sm font-medium transition-colors">Agregar</button>
        </div>
      </div>
    </Modal>
  );
}

function PunchListTab() {
  const [items, setItems] = useState(INITIAL_PUNCH);
  const [showNew, setShowNew] = useState(false);

  function toggleStatus(id) {
    setItems(p => p.map(i => i.id === id ? { ...i, status: PUNCH_STATUS_CYCLE[i.status] } : i));
  }

  function handleAdd(form) {
    const id = nextPunchId(items);
    setItems(p => [...p, { ...form, id }]);
  }

  const pendientes = items.filter(i => i.status === 'PENDIENTE').length;
  const enProceso = items.filter(i => i.status === 'EN_PROCESO').length;
  const completados = items.filter(i => i.status === 'COMPLETADO').length;

  return (
    <div className="space-y-5">
      <div className="grid grid-cols-3 gap-3">
        <KpiCard label="Pendientes" value={pendientes} color="text-slate-600 dark:text-slate-300" />
        <KpiCard label="En proceso" value={enProceso} color="text-amber-600 dark:text-amber-400" />
        <KpiCard label="Completados" value={completados} color="text-emerald-600 dark:text-emerald-400" />
      </div>

      <div className="rounded-2xl border border-slate-200 dark:border-surface-700 bg-white dark:bg-slate-900 overflow-hidden">
        <div className="flex items-center justify-between px-5 py-4 border-b border-slate-100 dark:border-surface-700">
          <h3 className="font-semibold text-slate-800 dark:text-slate-100">Punch List</h3>
          <button onClick={() => setShowNew(true)}
            className="px-4 py-2 rounded-xl bg-blue-600 hover:bg-blue-700 text-white text-sm font-medium transition-colors">
            + Agregar ítem
          </button>
        </div>
        <div className="overflow-x-auto">
          <table className="w-full text-sm">
            <thead>
              <tr className="bg-slate-50 dark:bg-slate-800 text-slate-500 dark:text-slate-400 text-left">
                {['ID', 'Descripción', 'Área', 'Proyecto', 'Asignado a', 'Vence', 'Prioridad', 'Estado'].map(h => (
                  <th key={h} className="px-4 py-3 font-medium whitespace-nowrap">{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {items.map((item) => {
                const overdue = isOverdue(item.dueDate, item.status);
                return (
                  <tr key={item.id} className={`border-t border-slate-100 dark:border-surface-700 hover:bg-slate-50 dark:hover:bg-slate-800/50 transition-colors ${overdue ? 'bg-red-50/50 dark:bg-red-900/10' : ''}`}>
                    <td className="px-4 py-3 font-mono text-xs text-slate-500 dark:text-slate-400 whitespace-nowrap">{item.id}</td>
                    <td className="px-4 py-3 text-slate-700 dark:text-slate-200 max-w-[240px]">
                      <span className={item.status === 'COMPLETADO' ? 'line-through text-slate-400 dark:text-slate-500' : ''}>{item.description}</span>
                    </td>
                    <td className="px-4 py-3 text-slate-600 dark:text-slate-300 whitespace-nowrap">{item.area}</td>
                    <td className="px-4 py-3 text-slate-600 dark:text-slate-300 whitespace-nowrap">{item.project}</td>
                    <td className="px-4 py-3 text-slate-600 dark:text-slate-300 whitespace-nowrap">{item.assignedTo}</td>
                    <td className={`px-4 py-3 whitespace-nowrap ${overdue ? 'text-red-600 dark:text-red-400 font-medium' : 'text-slate-500 dark:text-slate-400'}`}>{item.dueDate}</td>
                    <td className="px-4 py-3"><PriorityBadge priority={item.priority} /></td>
                    <td className="px-4 py-3 whitespace-nowrap">
                      <button onClick={() => toggleStatus(item.id)}
                        className="flex items-center gap-1.5 group">
                        <PunchStatusBadge status={item.status} />
                        <span className="text-xs text-slate-400 group-hover:text-slate-600 dark:group-hover:text-slate-300 transition-colors">↻</span>
                      </button>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      </div>

      {showNew && <NewPunchModal onClose={() => setShowNew(false)} onSave={handleAdd} />}
    </div>
  );
}

// ─── Page root ────────────────────────────────────────────────────────────────

const TABS = ['Inspecciones', 'No Conformidades (NCR)', 'Punch List', 'DoD / Criterios', 'Score QC', 'Auditorías'];

export default function QualityPage() {
  const [activeTab, setActiveTab] = useState(0);
  const [inspections, setInspections] = useState(MOCK_INSPECTIONS);
  const [ncrs, setNcrs] = useState(INITIAL_NCRS);
  const [newNcrPrefill, setNewNcrPrefill] = useState(null);

  function handleNewNcr(inspection) {
    setNewNcrPrefill(inspection);
    setActiveTab(1);
  }

  return (
    <div className="min-h-screen bg-slate-50 dark:bg-slate-950 p-4 sm:p-6">
      <div className="max-w-7xl mx-auto space-y-6">

        {/* Header */}
        <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
          <div>
            <h1 className="text-2xl font-bold text-slate-900 dark:text-slate-50">Control de Calidad</h1>
            <p className="text-sm text-slate-500 dark:text-slate-400 mt-0.5">Inspecciones, no conformidades y punch list</p>
          </div>
          <div className="text-xs text-slate-400 dark:text-slate-500 font-mono">{TODAY}</div>
        </div>

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

        {/* Tab content */}
        {activeTab === 0 && (
          <InspectionsTab
            inspections={inspections}
            setInspections={setInspections}
            onNewNcr={handleNewNcr}
          />
        )}
        {activeTab === 1 && (
          <NcrTab
            ncrs={ncrs}
            setNcrs={setNcrs}
            newNcrPrefill={newNcrPrefill}
            setNewNcrPrefill={setNewNcrPrefill}
          />
        )}
        {activeTab === 2 && <PunchListTab />}
        {activeTab === 3 && <DodTab />}
        {activeTab === 4 && <QualityScoreTab />}
        {activeTab === 5 && <AuditoriasTab />}
      </div>
    </div>
  );
}
