// Búsqueda global — paleta de comandos (⌘K) sobre todo el CMDB
const { useState: useStateS, useMemo: useMemoS, useEffect: useEffectS, useRef: useRefS } = React;

// Índice plano de todo lo buscable
function buildIndex() {
  const D = window.CMDB_DATA;
  const emp = (id) => D.empleados.find(e => e.id === id);
  const prv = (id) => D.proveedores.find(p => p.id === id);
  const idx = [];

  D.empleados.forEach(e => idx.push({
    kind: 'ci', type: 'USR', id: e.id, title: e.nombre,
    sub: `${e.puesto} · ${e.area}`,
    meta: e.estado === 'baja' ? 'Baja' : null,
    terms: [e.id, e.nombre, e.puesto, e.area, e.email, e.estado],
  }));
  D.equipos.forEach(e => idx.push({
    kind: 'ci', type: 'EQP', id: e.id, title: e.modelo,
    sub: `${e.numActivo} · ${e.serie} · ${e.asignadoA ? emp(e.asignadoA)?.nombre : e.ubicacion}`,
    meta: e.estado === 'activo' ? null : e.estado === 'stock' ? 'En stock' : 'Obsoleto',
    terms: [e.id, e.modelo, e.numActivo, e.serie, e.tipo, e.sistema, e.ram, e.estado, e.ubicacion, e.asignadoA ? emp(e.asignadoA)?.nombre : ''],
  }));
  D.servidores.forEach(s => idx.push({
    kind: 'ci', type: 'SRV', id: s.id, title: s.nombre,
    sub: `${s.tipo} · ${s.so} · ${s.ip}`,
    meta: s.estado === 'activo' ? null : 'Obsoleto',
    terms: [s.id, s.nombre, s.tipo, s.so, s.ip, s.ubicacion, s.estado],
  }));
  D.licencias.forEach(l => idx.push({
    kind: 'ci', type: 'LIC', id: l.id, title: l.producto,
    sub: `${l.tipo} · ${l.usados}/${l.asientos} asientos · vence ${fmtDate(l.vence)}`,
    meta: daysUntil(l.vence) < 0 ? 'Vencida' : null,
    terms: [l.id, l.producto, l.tipo, prv(l.proveedor)?.nombre],
  }));
  D.correos.forEach(m => idx.push({
    kind: 'ci', type: 'MBX', id: m.id, title: m.direccion,
    sub: `${m.tipo} · ${m.plan} · ${m.usadoGB}/${m.cuotaGB} GB`,
    terms: [m.id, m.direccion, m.tipo, m.plan],
  }));
  D.proveedores.forEach(p => idx.push({
    kind: 'ci', type: 'PRV', id: p.id, title: p.nombre,
    sub: `${p.tipo} · ${p.contacto} · ${p.rfc}`,
    terms: [p.id, p.nombre, p.tipo, p.contacto, p.rfc, p.email, p.telefono],
  }));
  D.lineas.forEach(t => idx.push({
    kind: 'ci', type: 'TEL', id: t.id, title: t.numero,
    sub: `${t.compania} · ${t.asignadoA ? emp(t.asignadoA)?.nombre : 'sin asignar'}`,
    meta: t.estado === 'activo' ? null : t.estado === 'stock' ? 'En stock' : 'Baja',
    terms: [t.id, t.numero, t.compania, t.asignadoA ? emp(t.asignadoA)?.nombre : ''],
  }));
  D.infraestructura.forEach(i => idx.push({
    kind: 'ci', type: 'INF', id: i.id, title: i.modelo,
    sub: `${i.tipo} · ${i.serie || i.ip || '—'} · ${i.ubicacion || ''}`,
    meta: i.estado === 'activo' ? null : i.estado === 'stock' ? 'En stock' : i.estado === 'obsoleto' ? 'Obsoleto' : 'Baja',
    terms: [i.id, i.modelo, i.tipo, i.serie, i.ip, i.numActivo, i.ubicacion],
  }));
  (D.dominios || []).forEach(dm => idx.push({
    kind: 'ci', type: 'DOM', id: dm.id, title: dm.dominio,
    sub: `${empresaNombre(dm.empresaId)} · vence ${fmtDate(dm.vence)}`,
    meta: dm.estado === 'baja' ? 'Baja' : daysUntil(dm.vence) < 0 ? 'Vencido' : daysUntil(dm.vence) <= 30 ? 'Por vencer' : null,
    terms: [dm.id, dm.dominio, empresaNombre(dm.empresaId), dm.notas],
  }));
  (D.hostings || []).forEach(h => idx.push({
    kind: 'ci', type: 'HST', id: h.id, title: h.nombre,
    sub: `${h.tipo} · ${prv(h.proveedor)?.nombre || '—'} · se renueva ${fmtDate(h.vence)}`,
    meta: h.estado === 'baja' ? 'Baja' : daysUntil(h.vence) < 0 ? 'Vencido' : daysUntil(h.vence) <= 60 ? 'Por vencer' : null,
    terms: [h.id, h.nombre, h.tipo, prv(h.proveedor)?.nombre, empresaNombre(h.empresaId), h.notas],
  }));
  D.mantenimientos.forEach(m => {
    const ci = findCI(m.ciId);
    idx.push({
      kind: 'ci', type: 'MNT', id: m.id, title: m.descripcion, goTo: m.ciId,
      sub: `${m.tipo} · ${ciLabel(ci)} · ${fmtDate(m.fecha)}`,
      meta: m.estado === 'programado' ? 'Programado' : m.estado === 'en-curso' ? 'En curso' : null,
      terms: [m.id, m.descripcion, m.tipo, m.ciId, ciLabel(ci), m.estado],
    });
  });
  // Solicitudes (tickets): se buscan por folio, folio de ManageEngine, asunto,
  // solicitante (nombre o correo) y técnico asignado
  (D.tickets || []).forEach(t => {
    const est = (D.ticketCat.estados || []).find(e => e.id === t.estadoId);
    const tec = t.tecnicoId ? emp(t.tecnicoId) : null;
    idx.push({
      kind: 'ticket', id: t.id, icon: 'ticket', title: t.asunto, abierto: esAbierto(t), sinTecnico: !t.tecnicoId,
      sub: `${solicitanteDe(t)} · ${tec ? tec.nombre : 'sin asignar'}`,
      meta: est ? est.nombre : null,
      terms: [t.id, t.folioOrigen != null ? String(t.folioOrigen) : '', t.asunto, solicitanteDe(t), t.solicitanteCorreo, t.descripcionCorta, tec ? tec.nombre : ''],
    });
  });
  return idx;
}

const NAV_COMMANDS = [
  { id: 'nav-sd',    title: 'Ir a Service Desk',   icon: 'home',      terms: ['service desk', 'servicedesk', 'inicio', 'home', 'tickets'], go: ['sdhome'] },
  { id: 'nav-tkt',   title: 'Ver Tickets',         icon: 'ticket',      terms: ['tickets', 'solicitudes', 'soporte', 'incidentes'], go: ['tickets'] },
  { id: 'nav-kb',    title: 'Ir a Conocimiento',   icon: 'book',      terms: ['conocimiento', 'base de conocimiento', 'kb', 'articulos', 'soluciones'], go: ['kb'] },
  { id: 'nav-dash',  title: 'Ir al Dashboard del CMDB', icon: 'dashboard', terms: ['dashboard', 'cmdb'], go: ['dashboard'] },
  { id: 'nav-all',   title: 'Ver todos los CIs',   icon: 'list',      terms: ['todos', 'inventario', 'cis'], go: ['list', { filter: null }] },
  { id: 'nav-usr',   title: 'Ver Empleados',       icon: 'user',      terms: ['empleados', 'usuarios', 'personal'], go: ['list', { filter: 'USR' }] },
  { id: 'nav-eqp',   title: 'Ver Equipos',         icon: 'computer',  terms: ['equipos', 'laptops', 'computo'], go: ['list', { filter: 'EQP' }] },
  { id: 'nav-srv',   title: 'Ver Servidores',      icon: 'server',    terms: ['servidores'], go: ['list', { filter: 'SRV' }] },
  { id: 'nav-lic',   title: 'Ver Licencias',       icon: 'license',   terms: ['licencias', 'software', 'saas'], go: ['list', { filter: 'LIC' }] },
  { id: 'nav-mbx',   title: 'Ver Correos',         icon: 'mail',      terms: ['correos', 'buzones', 'mailbox'], go: ['list', { filter: 'MBX' }] },
  { id: 'nav-dom',   title: 'Ver Dominios',        icon: 'globe',     terms: ['dominios', 'dominio', 'dns', 'renovacion'], go: ['list', { filter: 'DOM' }] },
  { id: 'nav-hst',   title: 'Ver Hostings',        icon: 'cloud',     terms: ['hostings', 'hosting', 'mochahost', 'planes', 'renovacion'], go: ['list', { filter: 'HST' }] },
  { id: 'nav-prv',   title: 'Ver Proveedores',     icon: 'vendor',    terms: ['proveedores'], go: ['list', { filter: 'PRV' }] },
  { id: 'nav-mnt',   title: 'Ver Mantenimientos',  icon: 'maint',     terms: ['mantenimientos', 'preventivo', 'correctivo'], go: ['maintenance'] },
  { id: 'nav-rel',   title: 'Ver Relaciones',      icon: 'graph',     terms: ['relaciones', 'grafo', 'topologia'], go: ['relations'] },
  { id: 'nav-sdrep', title: 'Reportes de Service Desk (cierre mensual)', icon: 'pulse', terms: ['reportes', 'cierre', 'mensual', 'cierre mensual', 'incidentes', 'tickets', 'service desk'], go: ['sdreportes'] },
  { id: 'nav-rep',   title: 'Ver Reportes del CMDB',        icon: 'pulse',     terms: ['reportes', 'reporte'], go: ['reports'] },
];

// Puntaje simple: prefijo exacto > palabra que inicia > subcadena
function score(item, q) {
  const hay = item.terms.filter(Boolean).map(t => String(t).toLowerCase());
  let best = 0;
  for (const t of hay) {
    if (t === q) best = Math.max(best, 100);
    else if (t.startsWith(q)) best = Math.max(best, 80);
    else if (t.split(/[\s·@.\-_/]+/).some(w => w.startsWith(q))) best = Math.max(best, 60);
    else if (t.includes(q)) best = Math.max(best, 35);
  }
  return best;
}

function SearchPalette({ open, onClose, onOpenCI, navigate, openForm }) {
  const [q, setQ] = useStateS('');
  const [sel, setSel] = useStateS(0);
  const inputRef = useRefS(null);
  const listRef = useRefS(null);
  // Se rehace al abrir: los tickets (y los CIs) cambian y CMDB_LOAD reemplaza los datos
  const index = useMemoS(buildIndex, [open]);

  useEffectS(() => {
    if (open) { setQ(''); setSel(0); setTimeout(() => inputRef.current?.focus(), 20); }
  }, [open]);

  const groups = useMemoS(() => {
    const query = q.trim().toLowerCase();
    if (!query) {
      const D = window.CMDB_DATA;
      const sinAsignar = index.filter(i => i.kind === 'ticket' && i.abierto && i.sinTecnico).slice(0, 4);
      const sugeridos = ['EQP-0022', 'LIC-0007', 'SRV-0007', 'USR-0002']
        .map(id => index.find(i => i.id === id)).filter(Boolean);
      return [
        { label: 'Ir a', items: NAV_COMMANDS.slice(0, 5).map(c => ({ ...c, kind: 'cmd' })) },
        { label: 'Requieren atención', items: sugeridos },
        ...(sinAsignar.length ? [{ label: 'Tickets sin asignar', items: sinAsignar }] : []),
      ].filter(g => g.items.length);
    }
    const cmds = NAV_COMMANDS.map(c => ({ ...c, kind: 'cmd', s: score(c, query) }))
      .filter(c => c.s > 0).sort((a, b) => b.s - a.s).slice(0, 4);
    const todos = index.map(i => ({ ...i, s: score(i, query) }))
      .filter(i => i.s > 0)
      .sort((a, b) => b.s - a.s || a.id.localeCompare(b.id));
    const cis = todos.filter(i => i.kind !== 'ticket');
    const tks = todos.filter(i => i.kind === 'ticket');

    const byType = {};
    cis.forEach(i => { (byType[i.type] = byType[i.type] || []).push(i); });
    const order = ['EQP', 'USR', 'SRV', 'LIC', 'MBX', 'DOM', 'HST', 'PRV', 'MNT'];
    const g = [];
    if (cmds.length) g.push({ label: 'Acciones', items: cmds });
    order.forEach(t => {
      if (byType[t]) g.push({ label: CI_TYPES[t].plural, items: byType[t].slice(0, 8), more: byType[t].length - 8 });
    });
    // Solicitudes: antes de los CIs si coinciden mejor que ellos (p. ej. buscar "TKT-0123")
    if (tks.length) {
      const grupo = { label: 'Tickets', items: tks.slice(0, 8), more: tks.length - 8 };
      const mejorCI = cis.length ? cis[0].s : 0;
      const pos = tks[0].s > mejorCI ? g.findIndex(x => x.label !== 'Acciones') : -1;
      if (pos >= 0) g.splice(pos, 0, grupo); else g.push(grupo);
    }
    return g;
  }, [q, index]);

  const flat = useMemoS(() => groups.flatMap(g => g.items), [groups]);
  useEffectS(() => { setSel(0); }, [q]);

  const run = (item) => {
    if (!item) return;
    if (item.kind === 'cmd') navigate(...item.go);
    else if (item.kind === 'ticket') navigate('ticket', { ticketId: item.id });
    else onOpenCI(item.goTo || item.id);
    onClose();
  };

  const onKey = (e) => {
    if (e.key === 'ArrowDown') { e.preventDefault(); setSel(s => Math.min(s + 1, flat.length - 1)); }
    else if (e.key === 'ArrowUp') { e.preventDefault(); setSel(s => Math.max(s - 1, 0)); }
    else if (e.key === 'Enter') { e.preventDefault(); run(flat[sel]); }
    else if (e.key === 'Escape') { e.preventDefault(); onClose(); }
  };

  useEffectS(() => {
    const el = listRef.current?.querySelector('.sr-item.on');
    if (el) {
      const p = listRef.current;
      const top = el.offsetTop, bot = top + el.offsetHeight;
      if (top < p.scrollTop) p.scrollTop = top - 8;
      else if (bot > p.scrollTop + p.clientHeight) p.scrollTop = bot - p.clientHeight + 8;
    }
  }, [sel]);

  if (!open) return null;
  let running = -1;

  return (
    <div className="sr-overlay" onMouseDown={onClose}>
      <div className="sr-panel" onMouseDown={e => e.stopPropagation()} onKeyDown={onKey}>
        <div className="sr-input">
          <Icon name="search" size={15} />
          <input ref={inputRef} value={q} onChange={e => setQ(e.target.value)}
            placeholder="Buscar CI, ticket, persona, serie, IP, licencia o acción…" />
          {q && <button className="sr-clear" onClick={() => { setQ(''); inputRef.current?.focus(); }}><Icon name="x" size={11} /></button>}
          <span className="kbd">ESC</span>
        </div>

        <div className="sr-list" ref={listRef}>
          {flat.length === 0 && (
            <div className="sr-empty">
              <span>Sin resultados para <strong>“{q}”</strong></span>
              <button className="btn sm primary" onClick={() => { openForm({ mode: 'create' }); onClose(); }}>
                <Icon name="plus" /> Dar de alta un CI
              </button>
            </div>
          )}
          {groups.map(g => (
            <div key={g.label} className="sr-group">
              <div className="sr-group-label">{g.label}</div>
              {g.items.map(item => {
                running++;
                const i = running;
                const t = item.kind === 'cmd' || item.kind === 'ticket' ? null : CI_TYPES[item.type];
                return (
                  <button key={item.id + i} className={`sr-item ${sel === i ? 'on' : ''}`}
                    onMouseMove={() => setSel(i)} onClick={() => run(item)}>
                    <span className="sr-ico" style={t ? { color: t.color } : null}>
                      <Icon name={item.kind === 'cmd' || item.kind === 'ticket' ? item.icon : iconForType(item.type)} size={13} />
                    </span>
                    <span className="sr-txt">
                      <span className="t"><Hl text={item.title} q={q} /></span>
                      {item.sub && <span className="s"><Hl text={item.sub} q={q} /></span>}
                    </span>
                    {item.meta && <span className="sr-meta">{item.meta}</span>}
                    {item.kind !== 'cmd' && <span className="mono sr-id">{item.id}</span>}
                  </button>
                );
              })}
              {g.more > 0 && <div className="sr-more">+{g.more} más — refina la búsqueda</div>}
            </div>
          ))}
        </div>

        <div className="sr-foot">
          <span><span className="kbd">↑</span><span className="kbd">↓</span> navegar</span>
          <span><span className="kbd">↵</span> abrir</span>
          <span className="sr-count mono">{flat.length} resultado{flat.length === 1 ? '' : 's'}</span>
        </div>
      </div>
    </div>
  );
}

// Resalta la coincidencia
function Hl({ text, q }) {
  const query = (q || '').trim();
  if (!query) return text;
  const i = String(text).toLowerCase().indexOf(query.toLowerCase());
  if (i < 0) return text;
  const s = String(text);
  return <>{s.slice(0, i)}<mark>{s.slice(i, i + query.length)}</mark>{s.slice(i + query.length)}</>;
}

Object.assign(window, { SearchPalette, buildIndex });
