// Inicio de Service Desk -- lo primero que se ve al entrar al módulo de
// solicitudes: cuántos tickets hay abiertos, cuáles no tienen técnico y cuáles
// llevan más tiempo esperando. Solo lee window.CMDB_DATA.tickets (ya cargado);
// los helpers de tickets (esAbierto, haceCuanto, PrioridadTag…) vienen de
// tickets-view.jsx, que se carga antes.
const { useMemo: useMemoSdh, useState: useStateSdh } = React;

// Porcentaje de incidentes (sobre los tickets creados en el mes) a partir del cual se marca en rojo
const UMBRAL_INCIDENTES = 14;

function ServiceDeskHome({ openTicket, navigate }) {
  const D = window.CMDB_DATA;
  const cat = D.ticketCat;
  const yo = miEmpleadoId();
  const [nuevo, setNuevo] = useStateSdh(false);

  const d = useMemoSdh(() => {
    const ahora = Date.now();
    const abiertos = D.tickets.filter(esAbierto);
    const sinAsignar = abiertos.filter(t => !t.tecnicoId);
    const conRespuesta = abiertos.filter(t => t.respuestaNueva).sort((a, b) => new Date(b.ultimaRespuestaEn || 0) - new Date(a.ultimaRespuestaEn || 0));
    const mios = yo ? abiertos.filter(t => t.tecnicoId === yo) : [];
    const inicioHoy = new Date(); inicioHoy.setHours(0, 0, 0, 0);
    const creadosHoy = D.tickets.filter(t => new Date(t.creadoEn) >= inicioHoy).length;
    // Mes en curso: qué parte de lo creado son incidentes (tipo "Incidente" del catálogo), sobre el total creado en el mes
    const inicioMes = new Date(); inicioMes.setDate(1); inicioMes.setHours(0, 0, 0, 0);
    const tipoInc = (cat.tipos || []).filter(x => /^incidente/i.test(String(x.nombre).normalize('NFD').replace(/[\u0300-\u036f]/g, '').trim())).map(x => x.id);
    const delMes = D.tickets.filter(t => new Date(t.creadoEn) >= inicioMes);
    const incidentesMes = delMes.filter(t => tipoInc.includes(t.tipoId)).length;
    const pctIncidentes = delMes.length ? Math.round((incidentesMes / delMes.length) * 1000) / 10 : 0;
    const incidentesCritico = pctIncidentes > UMBRAL_INCIDENTES; // más de 14 % de los tickets del mes: se marca en rojo
    const mesNombre = new Date().toLocaleDateString('es-MX', { month: 'long' });
    const resueltos7 = D.tickets.filter(t => !esAbierto(t) && t.resueltoEn && ahora - new Date(t.resueltoEn).getTime() < 7 * 86400000).length;
    const porAntiguedad = [...abiertos].sort((a, b) => new Date(a.creadoEn) - new Date(b.creadoEn));
    const sobre7d = abiertos.filter(t => ahora - new Date(t.creadoEn).getTime() > 7 * 86400000).length;

    const cuenta = (clave) => {
      const m = new Map();
      abiertos.forEach(t => m.set(clave(t), (m.get(clave(t)) || 0) + 1));
      return m;
    };
    const porTecnico = [...cuenta(t => t.tecnicoId || '_none')].map(([id, n]) => {
      const e = id === '_none' ? null : tkEmp(id);
      return { label: id === '_none' ? 'Sin asignar' : (e ? e.nombre : id), value: n, kind: id === '_none' ? 'warn' : 'primary' };
    }).sort((a, b) => b.value - a.value);
    const porPrioridad = cat.prioridades.filter(p => p.activo).sort((a, b) => b.nivel - a.nivel).map(p => ({
      label: p.nombre, value: abiertos.filter(t => t.prioridadId === p.id).length, kind: p.nivel >= Math.max(...cat.prioridades.map(x => x.nivel)) ? 'crit' : 'primary',
    })).filter(x => x.value > 0);
    const porCategoria = [...cuenta(t => t.categoriaId || '_none')].map(([id, n]) => {
      const c = id === '_none' ? null : tkBuscar('categorias', id);
      return { label: c ? c.nombre : 'Sin categoría', value: n };
    }).sort((a, b) => b.value - a.value).slice(0, 6);

    return { abiertos, sinAsignar, conRespuesta, mios, creadosHoy, delMes: delMes.length, incidentesMes, pctIncidentes, mesNombre, hayTipoInc: tipoInc.length > 0, incidentesCritico, resueltos7, porAntiguedad, sobre7d, porTecnico, porPrioridad, porCategoria };
  }, [D, yo]);

  // Los primeros 7 días del mes se avisa que ya está listo el cierre del mes anterior (si hubo tickets)
  const cierreListo = (() => {
    const hoy = new Date(); if (hoy.getDate() > 7) return null;
    const ant = new Date(hoy.getFullYear(), hoy.getMonth() - 1, 1);
    const hubo = D.tickets.some(t => { const f = new Date(t.creadoEn); return f.getFullYear() === ant.getFullYear() && f.getMonth() === ant.getMonth(); });
    return hubo ? `${['enero', 'febrero', 'marzo', 'abril', 'mayo', 'junio', 'julio', 'agosto', 'septiembre', 'octubre', 'noviembre', 'diciembre'][ant.getMonth()]} ${ant.getFullYear()}` : null;
  })();
  const verLista = (scope) => navigate('tickets', { scope });
  // critico: la cifra misma se pone en rojo (alerta solo pinta la nota de abajo)
  const Tile = ({ label, value, unit, hint, onClick, alerta, critico }) => (
    <div className="kpi" style={{ cursor: onClick ? 'pointer' : 'default', ...(critico ? { borderColor: 'var(--crit)' } : null) }} onClick={onClick}>
      <div className="label">{label}</div>
      <div className="row"><div className="val" style={critico ? { color: 'var(--crit)' } : undefined}>{value}{unit && <span className="unit">{unit}</span>}</div></div>
      <div className="delta" style={{ color: alerta || critico ? 'var(--crit)' : 'var(--ink-3)' }}>{hint}</div>
    </div>
  );

  const Fila = ({ t }) => {
    const tec = t.tecnicoId ? tkEmp(t.tecnicoId) : null;
    return (
      <tr onClick={() => openTicket(t.id)}>
        <td className="id" style={{ whiteSpace: 'nowrap' }}>{t.id}</td>
        <td style={{ minWidth: 200, maxWidth: 360 }}>
          <strong style={{ fontWeight: 500 }}>{t.asunto}</strong>
          <div style={{ fontSize: 11, color: 'var(--ink-3)' }}>{solicitanteDe(t)}{t.respuestaNueva && esAbierto(t) ? <strong style={{ color: 'var(--warn)', fontWeight: 600 }}> · respondió {haceCuanto(t.ultimaRespuestaEn)}</strong> : ''}</div>
        </td>
        <td><PrioridadTag id={t.prioridadId} /></td>
        <td style={{ fontSize: 12 }}>{tec ? tec.nombre : <span style={{ color: 'var(--ink-4)' }}>Sin asignar</span>}</td>
        <td className="mono" data-l="Creado" style={{ fontSize: 11, whiteSpace: 'nowrap' }} title={fmtDT(t.creadoEn)}>{haceCuanto(t.creadoEn)}</td>
      </tr>
    );
  };
  const Tabla = ({ filas, vacio }) => (
    <div style={{ overflowX: 'auto' }}>
      <table className="tbl dense tbl-cards">
        <thead><tr><th>Folio</th><th>Asunto</th><th>Prioridad</th><th>Técnico</th><th>Creado</th></tr></thead>
        <tbody>
          {filas.length === 0 && <tr><td colSpan={5}><div className="empty">{vacio}</div></td></tr>}
          {filas.map(t => <Fila key={t.id} t={t} />)}
        </tbody>
      </table>
    </div>
  );

  return (
    <>
      <div className="page-head">
        <h1>Service Desk</h1>
        <span className="sub">Tickets de soporte · lo que necesita atención hoy</span>
        <div className="actions">
          <button className="btn" onClick={() => verLista('abiertos')}>Ver tickets</button>
          <button className="btn primary" onClick={() => setNuevo(true)}><Icon name="plus" /> Nuevo ticket</button>
        </div>
      </div>

      {cierreListo && (
        <div className="lic-aviso" style={{ marginBottom: 14 }}>
          <span>Ya puedes revisar el <strong>cierre de {cierreListo}</strong>: resumen, patrones de repetición, desempeño, rezago y plan de acción. Se exporta a PDF.</span>
          <span style={{ display: 'flex', gap: 6, flexShrink: 0 }}><button className="btn sm primary" onClick={() => navigate('sdreportes', { report: 'cierre' })}>Ver el cierre</button></span>
        </div>
      )}
      <div className="col">
        <div className="kpi-grid kpi-grid-5">
          <Tile label="Abiertos" value={d.abiertos.length} hint={`${d.creadosHoy} creado${d.creadosHoy === 1 ? '' : 's'} hoy`} onClick={() => verLista('abiertos')} />
          <Tile label="Sin asignar" value={d.sinAsignar.length} hint={d.sinAsignar.length ? 'esperan un técnico' : 'todo asignado'} alerta={d.sinAsignar.length > 0} onClick={() => verLista('sinasignar')} />
          <Tile label="Mis tickets" value={d.mios.length} hint={yo ? 'asignados a ti' : 'tu usuario no está ligado a un empleado'} onClick={yo ? () => verLista('mios') : undefined} />
          <Tile label={`Incidentes · ${d.mesNombre}`} value={d.hayTipoInc ? d.pctIncidentes : '—'} unit={d.hayTipoInc ? '%' : ''} critico={d.hayTipoInc && d.incidentesCritico} hint={d.hayTipoInc ? `${d.incidentesMes} de ${d.delMes} ticket${d.delMes === 1 ? '' : 's'} este mes${d.incidentesCritico ? ` · supera el ${UMBRAL_INCIDENTES}%` : ''}` : 'no hay un tipo "Incidente" en el catálogo'} />
          <Tile label="Resueltos · 7 días" value={d.resueltos7} hint={d.sobre7d ? `${d.sobre7d} abierto${d.sobre7d === 1 ? '' : 's'} con más de 7 días` : 'ninguno con más de 7 días'} alerta={d.sobre7d > 0} onClick={() => verLista('completados')} />
        </div>

        <div className="grid-2-1">
          <div className="col">
            {d.conRespuesta.length > 0 && (
              <Card title="Respondieron" sub="el solicitante escribió y aún no lo has visto" tight right={d.conRespuesta.length > 6 ? <button className="btn sm" onClick={() => verLista('respuestas')}>Ver los {d.conRespuesta.length}</button> : null}>
                <Tabla filas={d.conRespuesta.slice(0, 6)} vacio="" />
              </Card>
            )}
            <Card title="Sin asignar" sub="esperan un técnico" tight right={d.sinAsignar.length > 6 ? <button className="btn sm" onClick={() => verLista('sinasignar')}>Ver los {d.sinAsignar.length}</button> : null}>
              <Tabla filas={[...d.sinAsignar].sort((a, b) => new Date(a.creadoEn) - new Date(b.creadoEn)).slice(0, 6)} vacio="No hay tickets sin asignar." />
            </Card>
            <Card title="Más antiguos abiertos" sub="llevan más tiempo esperando" tight right={d.abiertos.length > 8 ? <button className="btn sm" onClick={() => verLista('abiertos')}>Ver todos</button> : null}>
              <Tabla filas={d.porAntiguedad.slice(0, 8)} vacio="No hay tickets abiertos." />
            </Card>
          </div>
          <div className="col">
            <Card title="Por técnico" sub="tickets abiertos">
              {d.porTecnico.length ? <BarList items={d.porTecnico} /> : <div className="empty">Sin tickets abiertos.</div>}
            </Card>
            <Card title="Por prioridad" sub="tickets abiertos">
              {d.porPrioridad.length ? <BarList items={d.porPrioridad} /> : <div className="empty">Sin tickets abiertos.</div>}
            </Card>
            <Card title="Por categoría" sub="tickets abiertos">
              {d.porCategoria.length ? <BarList items={d.porCategoria} /> : <div className="empty">Sin tickets abiertos.</div>}
            </Card>
          </div>
        </div>
      </div>
      {nuevo && <NuevoTicketModal onClose={() => setNuevo(false)} onCreated={(id) => openTicket(id)} />}
    </>
  );
}

Object.assign(window, { ServiceDeskHome });
