// Shared primitives: icons, sparklines, donut, bar chart, helpers
const { useState, useMemo, useEffect, useRef } = React;

// ---------- Type metadata ----------
const CI_TYPES = {
  USR: { label: 'Empleado',  plural: 'Empleados',     color: 'oklch(58% 0.13 260)' },
  EQP: { label: 'Equipo',    plural: 'Equipos',       color: 'oklch(55% 0.13 200)' },
  SRV: { label: 'Servidor',  plural: 'Servidores',    color: 'oklch(50% 0.13 290)' },
  LIC: { label: 'Licencia',  plural: 'Licencias',     color: 'oklch(60% 0.13 75)'  },
  MBX: { label: 'Buzón',     plural: 'Correos',       color: 'oklch(58% 0.13 155)' },
  PRV: { label: 'Proveedor', plural: 'Proveedores',   color: 'oklch(55% 0.13 25)'  },
  TEL: { label: 'Línea',     plural: 'Líneas telefónicas', color: 'oklch(60% 0.10 320)' },
  INF: { label: 'Infraestructura', plural: 'Infraestructura', color: 'oklch(52% 0.11 235)' },
  DOM: { label: 'Dominio',   plural: 'Dominios',      color: 'oklch(52% 0.12 200)' },
  HST: { label: 'Hosting',   plural: 'Hostings',      color: 'oklch(50% 0.13 245)' },
  MNT: { label: 'Mantto',    plural: 'Mantenimientos',color: 'oklch(55% 0.05 80)'  },
};

const typeOf = (id) => id ? CI_TYPES[id.slice(0, 3)] : null;

// ---------- Date helpers ----------
// Antes era una fecha fija (2026-05-27, congelada para las capturas de la
// demo) — con datos reales, los conteos de "vence en Xd"/"garantía vencida"
// deben calcularse contra HOY de verdad, no contra una fecha de hace meses.
const TODAY = new Date();
// `new Date("2026-10-02")` lo interpreta JS como medianoche UTC -- en
// México (UTC-6) eso cae en "01-oct 18:00" hora local, y cualquier
// .toLocaleDateString()/.getDate() de ahí en adelante muestra el día
// ANTERIOR al guardado. parseLocalDate evita esto construyendo la fecha
// con el constructor (año, mes, día) de JS, que siempre es medianoche en
// la zona horaria LOCAL del navegador -- sin importar si `s` viene como
// "YYYY-MM-DD" puro o como datetime ISO completo de SQL Server
// ("YYYY-MM-DDT00:00:00.000Z"), en ambos casos solo nos interesa la
// fecha de calendario, no la hora.
const parseLocalDate = (s) => {
  if (!s) return null;
  const m = String(s).match(/^(\d{4})-(\d{2})-(\d{2})/);
  if (!m) return new Date(s);
  return new Date(Number(m[1]), Number(m[2]) - 1, Number(m[3]));
};
const fmtDate = (s) => {
  if (!s) return '—';
  const d = parseLocalDate(s);
  return d.toLocaleDateString('es-MX', { day: '2-digit', month: 'short', year: 'numeric' });
};
const daysUntil = (s) => {
  if (!s) return 0;
  const d = parseLocalDate(s);
  return Math.round((d - TODAY) / (1000 * 60 * 60 * 24));
};
// Un monto vacío (sin costo capturado) se muestra como '—' en vez de tirar la pantalla
// Importes SIEMPRE en formato contable: $10,000.00 (símbolo, miles con coma, decimales con punto y dos decimales).
// Se fija 'en-US' a propósito para que no dependa del idioma del navegador.
const _fmtContable = new Intl.NumberFormat('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
const fmtMoney = (n) => {
  if (n == null || n === '' || isNaN(Number(n))) return '—';
  const v = Number(n);
  return (v < 0 ? '-$' : '$') + _fmtContable.format(Math.abs(v));
};
// Antes abreviaba ($405K, $1.2M); ahora los importes se muestran completos, igual que fmtMoney
const fmtMoneyK = (n) => fmtMoney(n);
// Importes en dólares: US$ 19,299.24
const fmtMoneyUSD = (n) => (n == null || n === '' || isNaN(Number(n))) ? '—' : 'US$ ' + _fmtContable.format(Number(n));

// ---------- Icons ----------
const Icon = ({ name, size = 14 }) => {
  const props = { width: size, height: size, viewBox: '0 0 16 16', fill: 'none', stroke: 'currentColor', strokeWidth: 1.5, strokeLinecap: 'round', strokeLinejoin: 'round' };
  switch (name) {
    case 'dashboard': return <svg {...props}><rect x="2" y="2" width="5" height="5"/><rect x="9" y="2" width="5" height="5"/><rect x="2" y="9" width="5" height="5"/><rect x="9" y="9" width="5" height="5"/></svg>;
    case 'list': return <svg {...props}><line x1="2" y1="4" x2="14" y2="4"/><line x1="2" y1="8" x2="14" y2="8"/><line x1="2" y1="12" x2="14" y2="12"/></svg>;
    case 'computer': return <svg {...props}><rect x="2" y="3" width="12" height="8" rx="1"/><line x1="6" y1="14" x2="10" y2="14"/><line x1="8" y1="11" x2="8" y2="14"/></svg>;
    case 'server': return <svg {...props}><rect x="2" y="2" width="12" height="5" rx="1"/><rect x="2" y="9" width="12" height="5" rx="1"/><circle cx="4.5" cy="4.5" r="0.5" fill="currentColor"/><circle cx="4.5" cy="11.5" r="0.5" fill="currentColor"/></svg>;
    case 'user': return <svg {...props}><circle cx="8" cy="6" r="3"/><path d="M2 14c0-3 2.5-5 6-5s6 2 6 5"/></svg>;
    case 'home': return <svg {...props}><path d="M2 8l6-5.5L14 8"/><path d="M3.5 7v6.5h9V7"/><path d="M6.5 13.5V9.5h3v4"/></svg>;
    case 'ticket': return <svg {...props}><path d="M2 5.5a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v1.2a1.3 1.3 0 0 0 0 2.6v1.2a1 1 0 0 1-1 1H3a1 1 0 0 1-1-1V9.3a1.3 1.3 0 0 0 0-2.6z"/><line x1="10" y1="5.2" x2="10" y2="10.8" strokeDasharray="1.2 1.4"/></svg>;
    case 'user-plus': return <svg {...props}><circle cx="6.5" cy="6" r="2.8"/><path d="M1.5 14c0-2.8 2.2-4.6 5-4.6"/><line x1="12" y1="8.5" x2="12" y2="13"/><line x1="9.75" y1="10.75" x2="14.25" y2="10.75"/></svg>;
    case 'user-check': return <svg {...props}><circle cx="6.5" cy="6" r="2.8"/><path d="M1.5 14c0-2.8 2.2-4.6 5-4.6"/><polyline points="9.5,11 11.2,12.7 14.2,9.3"/></svg>;
    case 'settings': return <svg {...props}><circle cx="8" cy="8" r="2.2"/><path d="M8 1.5v2M8 12.5v2M1.5 8h2M12.5 8h2M3.4 3.4l1.4 1.4M11.2 11.2l1.4 1.4M12.6 3.4l-1.4 1.4M4.8 11.2l-1.4 1.4"/></svg>;
    case 'book': return <svg {...props}><path d="M2.5 2.5h8a2 2 0 0 1 2 2v9h-8a2 2 0 0 1-2-2v-9z"/><path d="M4.5 13.5h8M5.5 5.5h5M5.5 8h5"/></svg>;
    case 'chat': return <svg {...props}><path d="M2.5 3.5h11a1 1 0 0 1 1 1v6a1 1 0 0 1-1 1H8l-3 2.5v-2.5H2.5a1 1 0 0 1-1-1v-6a1 1 0 0 1 1-1z"/><line x1="5" y1="6.5" x2="11" y2="6.5"/><line x1="5" y1="8.8" x2="9" y2="8.8"/></svg>;
    case 'reply': return <svg {...props}><polyline points="6,3 2,7 6,11"/><path d="M2 7h7a5 5 0 0 1 5 5v1"/></svg>;
    case 'cloud': return <svg {...props}><path d="M4.5 12.5a3 3 0 0 1-.4-5.97A4 4 0 0 1 11.8 6a3.2 3.2 0 0 1 .2 6.4H4.5z"/></svg>;
    case 'globe': return <svg {...props}><circle cx="8" cy="8" r="6"/><ellipse cx="8" cy="8" rx="2.6" ry="6"/><line x1="2" y1="8" x2="14" y2="8"/></svg>;
    case 'license': return <svg {...props}><rect x="2" y="3" width="12" height="10" rx="1"/><line x1="2" y1="6" x2="14" y2="6"/><circle cx="5" cy="9.5" r="1"/><line x1="8" y1="9.5" x2="13" y2="9.5"/><line x1="8" y1="11.5" x2="11" y2="11.5"/></svg>;
    case 'mail': return <svg {...props}><rect x="2" y="3" width="12" height="10" rx="1"/><path d="M2 4l6 5 6-5"/></svg>;
    case 'vendor': return <svg {...props}><path d="M2 7l6-4 6 4v6H2z"/><line x1="8" y1="7" x2="8" y2="13"/></svg>;
    case 'graph': return <svg {...props}><circle cx="4" cy="4" r="2"/><circle cx="12" cy="4" r="2"/><circle cx="8" cy="12" r="2"/><line x1="5.5" y1="5.5" x2="10.5" y2="5.5"/><line x1="4" y1="6" x2="7" y2="10"/><line x1="12" y1="6" x2="9" y2="10"/></svg>;
    case 'maint': return <svg {...props}><path d="M11 2l3 3-2 2-3-3zM11 2l-6 6-3 3v3h3l3-3 6-6"/></svg>;
    case 'search': return <svg {...props}><circle cx="7" cy="7" r="4.5"/><line x1="10.5" y1="10.5" x2="14" y2="14"/></svg>;
    case 'plus': return <svg {...props}><line x1="8" y1="3" x2="8" y2="13"/><line x1="3" y1="8" x2="13" y2="8"/></svg>;
    case 'filter': return <svg {...props}><path d="M2 3h12l-4.5 6v4l-3 1V9z"/></svg>;
    case 'download': return <svg {...props}><path d="M8 2v8m-3-3l3 3 3-3"/><path d="M2 12v2h12v-2"/></svg>;
    case 'arrow': return <svg {...props}><line x1="3" y1="8" x2="13" y2="8"/><polyline points="9,4 13,8 9,12"/></svg>;
    case 'arrow-up': return <svg {...props}><line x1="8" y1="13" x2="8" y2="3"/><polyline points="4,7 8,3 12,7"/></svg>;
    case 'arrow-down': return <svg {...props}><line x1="8" y1="3" x2="8" y2="13"/><polyline points="4,9 8,13 12,9"/></svg>;
    case 'check': return <svg {...props}><polyline points="3,8 7,12 13,4"/></svg>;
    case 'x': return <svg {...props}><line x1="4" y1="4" x2="12" y2="12"/><line x1="12" y1="4" x2="4" y2="12"/></svg>;
    case 'warn': return <svg {...props}><path d="M8 1l7 13H1z"/><line x1="8" y1="6" x2="8" y2="10"/><circle cx="8" cy="12" r="0.5" fill="currentColor"/></svg>;
    case 'clock': return <svg {...props}><circle cx="8" cy="8" r="6"/><polyline points="8,4 8,8 11,10"/></svg>;
    case 'building': return <svg {...props}><rect x="3" y="3" width="10" height="11"/><line x1="5" y1="6" x2="6" y2="6"/><line x1="8" y1="6" x2="9" y2="6"/><line x1="11" y1="6" x2="11" y2="6"/><line x1="5" y1="9" x2="6" y2="9"/><line x1="8" y1="9" x2="9" y2="9"/><line x1="11" y1="9" x2="11" y2="9"/><rect x="6" y="11" width="4" height="3"/></svg>;
    case 'pulse': return <svg {...props}><polyline points="1,8 4,8 6,4 8,12 10,6 12,8 15,8"/></svg>;
    case 'tag': return <svg {...props}><path d="M2 2h6l6 6-6 6-6-6z"/><circle cx="5" cy="5" r="1"/></svg>;
    case 'phone': return <svg {...props}><path d="M3 2h3l1.5 4-2 1.5c1 2.2 2.8 4 5 5l1.5-2 4 1.5v3c0 1-1 1.5-2 1.3-6-1.2-10.6-5.8-11.8-11.8C2.5 3 3 2 3 2z"/></svg>;
    case 'router': return <svg {...props}><rect x="2" y="9" width="12" height="4" rx="1"/><circle cx="5" cy="11" r="0.6" fill="currentColor"/><path d="M8 9V6.5"/><path d="M5.7 6.3a3.3 3.3 0 0 1 4.6 0"/><path d="M4.2 4.8a5.5 5.5 0 0 1 7.6 0"/></svg>;
    case 'cart': return <svg {...props}><path d="M2 3h2l1.5 8h7l1.5-5.5H5"/><circle cx="6.5" cy="13" r="1"/><circle cx="11.5" cy="13" r="1"/></svg>;
    default: return <svg {...props}></svg>;
  }
};

const iconForType = (prefix) => ({
  USR: 'user', EQP: 'computer', SRV: 'server', LIC: 'license',
  MBX: 'mail', PRV: 'vendor', MNT: 'maint', TEL: 'phone', INF: 'router', DOM: 'globe', HST: 'cloud'
}[prefix]);

// ---------- Badges ----------
const Badge = ({ kind = '', children, dot }) => (
  <span className={`badge ${kind}`}>
    {dot && <span className="dot" />}
    {children}
  </span>
);

const StatusBadge = ({ estado }) => {
  const map = {
    activo: ['good', 'Activo'],
    stock: ['info', 'En stock'],
    obsoleto: ['crit', 'Obsoleto'],
    baja: ['crit', 'Baja'],
    suspendido: ['warn', 'Suspendido'],
    suspendida: ['warn', 'Suspendida'],
    // Licencias (estado derivado de su vencimiento)
    vencida: ['crit', 'Vencida'],
    'por-vencer': ['warn', 'Por vencer'],
    vigente: ['good', 'Vigente'],
    mantenimiento: ['warn', 'Mantenimiento'],
    completado: ['good', 'Completado'],
    'en-curso': ['warn', 'En curso'],
    programado: ['info', 'Programado'],
    // Jornadas de mantenimiento preventivo (cabecera y línea por equipo)
    planeada: ['info', 'Planeada'],
    cerrada: ['good', 'Cerrada'],
    cancelada: ['crit', 'Cancelada'],
    Pendiente: ['', 'Pendiente'],
    Agendado: ['info', 'Agendado'],
    'En Proceso': ['warn', 'En proceso'],
    Realizado: ['good', 'Realizado'],
    Cancelado: ['crit', 'Cancelado'],
  };
  const [kind, label] = map[estado] || ['', estado];
  return <Badge kind={kind} dot>{label}</Badge>;
};

const VenceBadge = ({ dias }) => {
  if (dias < 0) return <Badge kind="crit" dot>Vencida · {Math.abs(dias)}d</Badge>;
  if (dias <= 14) return <Badge kind="crit" dot>{dias}d</Badge>;
  if (dias <= 60) return <Badge kind="warn" dot>{dias}d</Badge>;
  return <Badge kind="good">{dias}d</Badge>;
};

// ---------- Sparkline ----------
const Sparkline = ({ data, color = 'var(--primary)', height = 28, width = 100 }) => {
  const min = Math.min(...data), max = Math.max(...data);
  const range = max - min || 1;
  const step = width / (data.length - 1);
  const pts = data.map((v, i) => [i * step, height - ((v - min) / range) * (height - 4) - 2]);
  const linePath = 'M' + pts.map(p => p.join(',')).join(' L');
  const areaPath = `M${pts[0][0]},${height} L` + pts.map(p => p.join(',')).join(' L') + ` L${pts[pts.length-1][0]},${height} Z`;
  return (
    <svg width={width} height={height} className="sparkline">
      <path d={areaPath} fill={color} className="spark-area" />
      <path d={linePath} stroke={color} className="spark-line" />
    </svg>
  );
};

// ---------- Donut ----------
const Donut = ({ segments, size = 140, thickness = 18 }) => {
  const r = (size - thickness) / 2;
  const c = size / 2;
  const circ = 2 * Math.PI * r;
  const total = segments.reduce((s, x) => s + x.value, 0);
  let acc = 0;
  return (
    <svg width={size} height={size}>
      <circle cx={c} cy={c} r={r} stroke="var(--bg-3)" strokeWidth={thickness} fill="none" />
      {segments.map((s, i) => {
        const len = (s.value / total) * circ;
        const off = circ - len;
        const rot = (acc / total) * 360;
        acc += s.value;
        return (
          <circle
            key={i}
            cx={c} cy={c} r={r}
            stroke={s.color} strokeWidth={thickness} fill="none"
            strokeDasharray={`${len} ${circ}`}
            strokeDashoffset={0}
            transform={`rotate(${rot} ${c} ${c})`}
          />
        );
      })}
    </svg>
  );
};

// ---------- Bar list ----------
const BarList = ({ items, max, format = (v) => v, color = 'primary' }) => {
  const m = max ?? Math.max(...items.map(i => i.value));
  return (
    <div className="bar-chart">
      {items.map(it => (
        <div key={it.label} className="bar-row">
          <div className="lbl">{it.label}</div>
          <div className="bar-track"><div className={`bar-fill ${it.kind || color}`} style={{ width: (it.value/m*100) + '%' }} /></div>
          <div className="num">{format(it.value)}</div>
        </div>
      ))}
    </div>
  );
};

// ---------- Card shell ----------
const Card = ({ title, sub, right, tight, children, className = '' }) => (
  <div className={`card ${className}`}>
    {(title || right) && (
      <div className="card-h">
        {title && <h3>{title}</h3>}
        {sub && <span className="sub">{sub}</span>}
        {right && <div className="right">{right}</div>}
      </div>
    )}
    <div className={`card-b ${tight ? 'tight' : ''}`}>{children}</div>
  </div>
);

// ---------- Aggregations ----------
// ---------- Exportar a CSV ----------
// filas: arreglo de arreglos (la primera es el encabezado). Se escribe con
// BOM UTF-8 para que Excel respete acentos y la ñ, y se escapan comillas,
// comas y saltos de línea.
function descargarCSV(nombre, filas) {
  const esc = (v) => {
    const s = v == null ? '' : String(v);
    return /[",\n\r]/.test(s) ? '"' + s.replace(/"/g, '""') + '"' : s;
  };
  const texto = '\ufeff' + filas.map(f => f.map(esc).join(',')).join('\r\n');
  const url = URL.createObjectURL(new Blob([texto], { type: 'text/csv;charset=utf-8' }));
  const a = document.createElement('a');
  a.href = url; a.download = nombre;
  document.body.appendChild(a); a.click(); a.remove();
  setTimeout(() => URL.revokeObjectURL(url), 1000);
  window.notify && window.notify({ kind: 'ok', title: 'CSV descargado', detail: `${nombre} · ${Math.max(0, filas.length - 1)} fila(s)` });
}
// Convierte las tablas que hay dentro de un elemento en filas de CSV
// (lo que se ve en pantalla). Varias tablas se separan con una fila vacía.
function tablasACSV(raiz) {
  const filas = [];
  raiz.querySelectorAll('table').forEach((t, i) => {
    if (i > 0) filas.push([]);
    t.querySelectorAll('tr').forEach(tr => {
      const celdas = [...tr.children].map(c => c.innerText.replace(/\s+/g, ' ').trim());
      if (celdas.some(Boolean)) filas.push(celdas);
    });
  });
  return filas;
}

// ---------- CIs en baja ----------
// Un CI en estado "baja" ya no se atiende: no entra en recomendaciones de
// mantenimiento, alertas, KPIs ni reportes que generen un plan de acción
// (inmediato o futuro). Solo se consulta con el filtro "Baja" de los
// listados (y en el reporte de inactivos). datosVigentes() devuelve la misma
// estructura de CMDB_DATA pero sin esos CIs: úsala en todo lo que sea
// accionable. Se guarda por objeto de datos (cmdbLoadAll lo reemplaza entero
// en cada recarga), así no se recalcula en cada render.
const esBaja = (x) => !!x && x.estado === 'baja';
// Dominio de una dirección de correo (usuario@motionsi.com → motionsi.com)
const dominioDeCorreo = (a) => String(a || '').split('@')[1] ? String(a).split('@')[1].toLowerCase().trim() : '';
// Hosting: ciclos de pago y costo anualizado (el costo se guarda por ciclo, en pesos)
const HST_CICLOS = { 1: 'Mensual', 3: 'Trimestral', 6: 'Semestral', 12: 'Anual', 24: 'Bienal', 36: 'Trianual', 48: 'Cada 4 años', 60: 'Cada 5 años' };
const hostingCicloLabel = (m) => HST_CICLOS[m] || `Cada ${m} meses`;
const hostingCicloMeses = (label) => Number((Object.entries(HST_CICLOS).find(([, l]) => l === label) || [])[0]) || 12;
const hostingAnual = (h) => (h && h.costoCiclo ? (h.costoCiclo * 12) / (h.cicloMeses || 12) : 0);
const _vigentesCache = new WeakMap();
function datosVigentes(D) {
  D = D || window.CMDB_DATA;
  if (_vigentesCache.has(D)) return _vigentesCache.get(D);
  const vig = (arr) => (arr || []).filter(x => !esBaja(x));
  const bajaIds = new Set();
  ['equipos', 'servidores', 'infraestructura', 'lineas', 'correos', 'empleados'].forEach(k =>
    (D[k] || []).forEach(x => { if (esBaja(x)) bajaIds.add(x.id); }));
  const V = {
    ...D,
    equipos: vig(D.equipos), servidores: vig(D.servidores), infraestructura: vig(D.infraestructura),
    lineas: vig(D.lineas), correos: vig(D.correos), empleados: vig(D.empleados), dominios: vig(D.dominios), hostings: vig(D.hostings),
    // Una licencia suspendida tampoco genera alertas ni recomendaciones
    licencias: (D.licencias || []).filter(l => l.estado !== 'suspendida'),
    // Pendientes de un CI que ya está en baja no se atienden; lo ya hecho (historial) se conserva
    mantenimientos: (D.mantenimientos || []).filter(m => !(bajaIds.has(m.ciId) && (m.estado === 'programado' || m.estado === 'en-curso'))),
    jornadaEquipos: (D.jornadaEquipos || []).filter(je => !(bajaIds.has(je.ciId) && je.estado !== 'Realizado')),
    bajaIds,
  };
  _vigentesCache.set(D, V);
  return V;
}

const useDerivedStats = () => {
  return useMemo(() => {
    const D = datosVigentes();
    const stats = {
      empleadosActivos: D.empleados.filter(e => e.estado === 'activo' && e.categoria !== 'externo').length,
      equiposTotal: D.equipos.length,
      equiposAsignados: D.equipos.filter(e => e.asignadoA).length,
      equiposStock: D.equipos.filter(e => e.estado === 'stock').length,
      equiposObsoletos: D.equipos.filter(e => e.obsoleto).length,
      servidoresActivos: D.servidores.filter(s => s.estado === 'activo').length,
      servidoresObsoletos: D.servidores.filter(s => s.estado === 'obsoleto').length,
      licenciasTotal: D.licencias.length,
      licenciasVencidas: D.licencias.filter(l => daysUntil(l.vence) < 0).length,
      licenciasPorVencer30: D.licencias.filter(l => { const d = daysUntil(l.vence); return d >= 0 && d <= 30; }).length,
      licenciasPorVencer60: D.licencias.filter(l => { const d = daysUntil(l.vence); return d > 30 && d <= 60; }).length,
      costoAnualLicencias: D.licencias.reduce((s, l) => s + l.costoAnual, 0),
      asientosTotal: D.licencias.reduce((s, l) => s + l.asientos, 0),
      asientosUsados: D.licencias.reduce((s, l) => s + l.usados, 0),
      mantenimientosProgramados: D.mantenimientos.filter(m => m.estado === 'programado').length,
      mantenimientosEnCurso: D.mantenimientos.filter(m => m.estado === 'en-curso').length,
      valorTotalActivos: D.equipos.reduce((s, e) => s + e.costo, 0),
      proveedores: D.proveedores.length,
      lineasActivas: D.lineas.filter(t => t.estado === 'activo').length,
      costoMensualLineas: D.lineas.reduce((s, t) => s + (t.estado === 'activo' ? (t.importeMensual || 0) : 0), 0),
    };

    stats.areaBreakdown = Object.entries(
      D.empleados.filter(e => e.estado === 'activo' && e.categoria !== 'externo').reduce((acc, e) => {
        acc[e.area] = (acc[e.area] || 0) + 1; return acc;
      }, {})
    ).sort((a, b) => b[1] - a[1]);

    stats.equipoTipo = Object.entries(
      D.equipos.reduce((acc, e) => { acc[e.tipo] = (acc[e.tipo] || 0) + 1; return acc; }, {})
    );

    stats.equipoEdad = D.equipos.reduce((acc, e) => {
      const b = e.edadAnios < 2 ? '<2 años' : e.edadAnios < 4 ? '2–4 años' : e.edadAnios < 6 ? '4–6 años' : '6+ años';
      acc[b] = (acc[b] || 0) + 1; return acc;
    }, {});

    stats.licenciasPorTipo = Object.entries(
      D.licencias.reduce((acc, l) => { acc[l.tipo] = (acc[l.tipo] || 0) + 1; return acc; }, {})
    );

    return stats;
  }, [window.CMDB_DATA]);
};


// ---------- Estado de pantalla que sobrevive a la navegación ----------
// Cada pantalla visitada es una "entrada" del historial del navegador (ver
// App en app.jsx). usePersist guarda el estado de la UI (pestaña, filtros,
// búsqueda, jornada abierta...) por entrada: al volver con "Atrás" o con el
// botón ← la pantalla reaparece exactamente como se dejó, y al entrar desde
// el menú lateral arranca limpia. Solo valores serializables (texto,
// números, booleanos, ids), nunca Sets ni Dates.
const UIS_KEY = 'cmdb_ui';
window.__UIS = (() => { try { return JSON.parse(sessionStorage.getItem(UIS_KEY) || '{}'); } catch (e) { return {}; } })();
window.__uisSave = () => {
  try {
    const ids = Object.keys(window.__UIS);
    if (ids.length > 60) ids.slice(0, ids.length - 60).forEach(k => delete window.__UIS[k]); // las más viejas
    sessionStorage.setItem(UIS_KEY, JSON.stringify(window.__UIS));
  } catch (e) { /* sin sessionStorage: sigue funcionando en memoria */ }
};
function usePersist(key, initial) {
  const entry = window.__navEntryId || '_';
  const [v, setV] = useState(() => {
    const s = window.__UIS[entry];
    if (s && Object.prototype.hasOwnProperty.call(s, key)) return s[key];
    return typeof initial === 'function' ? initial() : initial;
  });
  const set = React.useCallback((nv) => {
    setV(prev => {
      const val = typeof nv === 'function' ? nv(prev) : nv;
      (window.__UIS[entry] || (window.__UIS[entry] = {}))[key] = val;
      window.__uisSave();
      return val;
    });
  }, [entry, key]);
  return [v, set];
}

Object.assign(window, {
  dominioDeCorreo, HST_CICLOS, hostingCicloLabel, hostingCicloMeses, hostingAnual, usePersist, esBaja, datosVigentes, descargarCSV, tablasACSV,
  Icon, Badge, StatusBadge, VenceBadge, Sparkline, Donut, BarList, Card,
  CI_TYPES, typeOf, iconForType,
  TODAY, fmtDate, daysUntil, fmtMoney, fmtMoneyK, fmtMoneyUSD,
  useDerivedStats,
});
