/* global React */
// Alertas y Plazos — HU.3.2
// Lista de notificaciones del semáforo D-7 / D-3 / D-1 / D / D+1
// + panel de configuración de hitos y canales

const { useState: useStateAl, useMemo: useMemoAl } = React;

function AlertasScreen({ roleId, user, onOpenDetalle }) {
  const I = window.Icons;
  const alertas = window.getAlertas(roleId);

  const [filter, setFilter] = useStateAl('todas');
  const [scope, setScope] = useStateAl('todas'); // todas, vencimientos, devoluciones, sin_avance, sistema

  // Cuenta de hitos
  const counts = useMemoAl(() => {
    const c = { todas: alertas.length, unread: 0, d7: 0, d3: 0, d1: 0, d0: 0, dplus: 0, sin: 0 };
    alertas.forEach(a => {
      if (!a.read) c.unread++;
      if (a.code === 'D-7') c.d7++;
      else if (a.code === 'D-3') c.d3++;
      else if (a.code === 'D-1') c.d1++;
      else if (a.code === 'D') c.d0++;
      else if (a.code.startsWith('D+')) c.dplus++;
      else if (a.code === 'sin' || a.code === 'devol') c.sin++;
    });
    return c;
  }, [alertas]);

  const filtered = useMemoAl(() => {
    return alertas.filter(a => {
      if (filter === 'unread' && a.read) return false;
      if (filter === 'D-7' && a.code !== 'D-7') return false;
      if (filter === 'D-3' && a.code !== 'D-3') return false;
      if (filter === 'D-1' && a.code !== 'D-1') return false;
      if (filter === 'D' && a.code !== 'D') return false;
      if (filter === 'overdue' && !a.code.startsWith('D+')) return false;
      if (filter === 'sin_plazo' && a.code !== 'sin') return false;

      if (scope === 'vencimientos' && a.tipo !== 'vencimiento') return false;
      if (scope === 'devoluciones' && a.tipo !== 'devolucion') return false;
      if (scope === 'sin_avance' && a.tipo !== 'sin_avance') return false;
      if (scope === 'sistema' && a.tipo !== 'sistema') return false;
      return true;
    });
  }, [alertas, filter, scope]);

  return (
    <div data-screen-label="03 Alertas y Plazos">
      {/* Header */}
      <div className="page-head">
        <div>
          <div className="page-head__eyebrow">{user.org}</div>
          <h1 className="page-head__title">Alertas y Plazos</h1>
          <p className="page-head__sub">
            Notificaciones automáticas del semáforo D-7 / D-3 / D-1 / D / D+1.
            {roleId === 'institucion'
              ? ' Cubre tus compromisos asignados.'
              : ' Sobre el universo de las 527 recomendaciones del país.'}
          </p>
        </div>
        <div className="page-head__actions">
          <button type="button" className="btn btn--ghost">
            <I.Eye size={14} /> Marcar todas como leídas
          </button>
          {roleId !== 'institucion' && (
            <button type="button" className="btn btn--secondary">
              <I.Settings size={14} /> Configurar alertas
            </button>
          )}
        </div>
      </div>

      {/* KPI strip */}
      <div className="compkpi-row">
        <div className="compkpi">
          <div className="compkpi__icon"><I.Bell size={15} /></div>
          <div className="compkpi__body">
            <div className="compkpi__num">{counts.todas}</div>
            <div className="compkpi__label">Alertas activas</div>
            <div className="compkpi__sub">{counts.unread} sin leer</div>
          </div>
        </div>
        <div className="compkpi is-danger">
          <div className="compkpi__icon"><I.AlertCircle size={15} /></div>
          <div className="compkpi__body">
            <div className="compkpi__num">{counts.d1 + counts.d0}</div>
            <div className="compkpi__label">D-1 / Hoy</div>
            <div className="compkpi__sub">Acción urgente</div>
          </div>
        </div>
        <div className="compkpi is-warn">
          <div className="compkpi__icon"><I.Clock size={15} /></div>
          <div className="compkpi__body">
            <div className="compkpi__num">{counts.d3}</div>
            <div className="compkpi__label">D-3</div>
            <div className="compkpi__sub">Próximos 3 días</div>
          </div>
        </div>
        <div className="compkpi">
          <div className="compkpi__icon"><I.Calendar size={15} /></div>
          <div className="compkpi__body">
            <div className="compkpi__num">{counts.d7}</div>
            <div className="compkpi__label">D-7</div>
            <div className="compkpi__sub">Primer aviso</div>
          </div>
        </div>
        <div className="compkpi is-dark">
          <div className="compkpi__icon"><I.AlertTriangle size={15} /></div>
          <div className="compkpi__body">
            <div className="compkpi__num">{counts.dplus}</div>
            <div className="compkpi__label">Vencidos · D+</div>
            <div className="compkpi__sub">Sin avance registrado</div>
          </div>
        </div>
      </div>

      <div className="alertas-layout">
        {/* MAIN */}
        <div className="alertas-main">
          {/* Tabs por hito */}
          <div className="ciclo-tabs">
            <button type="button" className={`ciclo-tab${filter === 'todas' ? ' is-active' : ''}`} onClick={() => setFilter('todas')}>
              <span>Todas</span><span className="ciclo-tab__count">{counts.todas}</span>
            </button>
            <button type="button" className={`ciclo-tab${filter === 'unread' ? ' is-active' : ''}`} onClick={() => setFilter('unread')}>
              <span>● No leídas</span><span className="ciclo-tab__count">{counts.unread}</span>
            </button>
            <button type="button" className={`ciclo-tab ciclo-tab--danger${filter === 'D-1' ? ' is-active' : ''}`} onClick={() => setFilter('D-1')}>
              <span className="dcode mono">D-1</span><span className="ciclo-tab__count">{counts.d1}</span>
            </button>
            <button type="button" className={`ciclo-tab ciclo-tab--warn${filter === 'D-3' ? ' is-active' : ''}`} onClick={() => setFilter('D-3')}>
              <span className="dcode mono">D-3</span><span className="ciclo-tab__count">{counts.d3}</span>
            </button>
            <button type="button" className={`ciclo-tab ciclo-tab--info${filter === 'D-7' ? ' is-active' : ''}`} onClick={() => setFilter('D-7')}>
              <span className="dcode mono">D-7</span><span className="ciclo-tab__count">{counts.d7}</span>
            </button>
            <button type="button" className={`ciclo-tab ciclo-tab--dark${filter === 'overdue' ? ' is-active' : ''}`} onClick={() => setFilter('overdue')}>
              <span className="dcode mono">D+</span><span className="ciclo-tab__count">{counts.dplus}</span>
            </button>
            <button type="button" className={`ciclo-tab${filter === 'sin_plazo' ? ' is-active' : ''}`} onClick={() => setFilter('sin_plazo')}>
              <span>Sin plazo</span><span className="ciclo-tab__count">{counts.sin}</span>
            </button>
          </div>

          {/* Scope chips */}
          <div className="chips" style={{ marginTop: 4 }}>
            {[
              { v: 'todas', l: 'Todos los tipos' },
              { v: 'vencimientos', l: '⏱ Vencimientos' },
              { v: 'sin_avance', l: '⚠ Sin avance' },
              { v: 'devoluciones', l: '↩ Devoluciones' },
              { v: 'sistema', l: '⚙ Sistema' },
            ].map(it => (
              <button key={it.v} type="button"
                className={`chip${scope === it.v ? ' is-active' : ''}`}
                onClick={() => setScope(it.v)}>
                {it.l}
              </button>
            ))}
          </div>

          {/* Lista de alertas */}
          <ul className="alert-list">
            {filtered.map(a => (
              <AlertItem key={a.id} a={a} onOpen={onOpenDetalle} roleId={roleId} />
            ))}
          </ul>

          {filtered.length === 0 && (
            <div className="empty">
              <I.Bell size={28} />
              <h4>No hay alertas con esta combinación</h4>
              <p>Ajusta los filtros o vuelve a "Todas" para ver el conjunto completo.</p>
            </div>
          )}
        </div>

        {/* RAIL */}
        <aside className="alertas-rail">
          <div className="rail-card">
            <div className="rail-card__head"><h4>Configuración de hitos</h4></div>
            <div className="rail-card__body" style={{ padding: 0 }}>
              <ul className="hitos-list">
                {window.ALERTAS_CONFIG.map(h => (
                  <li key={h.code} className={`hitos-item${h.enabled ? '' : ' is-off'}`}>
                    <div className="hitos-code mono">{h.code}</div>
                    <div className="hitos-body">
                      <strong>{h.label}</strong>
                      <small>{h.desc}</small>
                      <div className="hitos-channels">
                        {h.channels.includes('email') && <span><I.MessageSquare size={10} /> Correo</span>}
                        {h.channels.includes('platform') && <span><I.Bell size={10} /> Plataforma</span>}
                      </div>
                    </div>
                    <label className="hitos-toggle">
                      <input type="checkbox" defaultChecked={h.enabled} disabled={roleId === 'institucion'} />
                      <span></span>
                    </label>
                  </li>
                ))}
              </ul>
            </div>
            {roleId !== 'institucion' && (
              <div className="rail-card__foot">
                <button type="button" className="btn btn--secondary btn--sm" style={{ width: '100%', justifyContent: 'center' }}>
                  <I.Settings size={13} /> Editar configuración global
                </button>
              </div>
            )}
          </div>

          <div className="rail-card rail-card--accent">
            <div className="rail-card__head"><h4>¿Cómo funcionan las alertas?</h4></div>
            <div className="rail-card__body">
              <p>
                El sistema envía notificaciones automáticas a la institución responsable
                {roleId === 'institucion' ? '' : ' y al Administrador'} en los hitos
                D-7, D-3, D-1, D y D+1.
              </p>
              <p>
                Las alertas {roleId !== 'institucion' ? 'son configurables y ' : ''}
                no bloquean la carga posterior de información. El vencimiento no impide reportar.
              </p>
              <small style={{ color: 'var(--cgr-text-muted)', fontSize: '11px' }}>
                Regla CGR-08 · Épica de Compromisos Internacionales
              </small>
            </div>
          </div>
        </aside>
      </div>
    </div>
  );
}

// ---------------- Alert item ----------------
function AlertItem({ a, onOpen, roleId }) {
  const I = window.Icons;
  const tipoMeta = {
    vencimiento: { icon: 'Clock',         label: 'Vencimiento' },
    sin_avance:  { icon: 'AlertTriangle', label: 'Sin avance' },
    devolucion:  { icon: 'AlertCircle',   label: 'Devolución' },
    sistema:     { icon: 'Settings',      label: 'Sistema' },
  }[a.tipo] || { icon: 'Bell', label: 'Notificación' };
  const ICON = I[tipoMeta.icon];

  return (
    <li className={`alert-item alert-item--${a.severity}${a.read ? ' is-read' : ''}`}>
      <div className={`alert-item__code alert-item__code--${a.severity}`}>
        <span className="mono">{a.code === 'sin' ? '—' : a.code === 'devol' ? '↩' : a.code}</span>
      </div>

      <div className="alert-item__body">
        <div className="alert-item__top">
          <span className={`alert-tipo alert-tipo--${a.tipo}`}>
            <ICON size={10} /> {tipoMeta.label}
          </span>
          <span className={`mech-tag mech-tag--${a.mecanismo.toLowerCase()}`}>{a.mecanismo}</span>
          <span className="alert-item__id mono">{a.compromisoId}</span>
          <span className="alert-item__inst">
            <I.Building2 size={11} /> {a.institucion}
          </span>
          {!a.read && <span className="alert-item__unread-dot" title="No leída"></span>}
        </div>

        <button type="button" className="alert-item__title" onClick={() => onOpen(a.compromisoId)}>
          {a.recomendacion}
        </button>

        <div className="alert-item__msg">{a.msg}</div>

        <div className="alert-item__foot">
          <span><I.Calendar size={11} /> Plazo: <strong className="mono">{a.plazo}</strong></span>
          <span className="muted">· Enviada {a.sentAt}</span>
          <div className="alert-item__actions">
            <button type="button" className="btn btn--ghost btn--sm" onClick={() => onOpen(a.compromisoId)}>
              <I.Eye size={12} /> Ver detalle
            </button>
            {roleId !== 'institucion' && a.tipo === 'vencimiento' && (
              <button type="button" className="btn btn--ghost btn--sm">
                <I.MessageSquare size={12} /> Reenviar
              </button>
            )}
          </div>
        </div>
      </div>
    </li>
  );
}

Object.assign(window, { AlertasScreen });
