// src/screen-operaciones.jsx — Operaciones: bandeja de GESTIONES (trámites ante GNP)
// + detalle a pantalla completa. Retro de Miguel 2026-07-30 aplicada:
// - Sin franja de vigía (lo urgente vive en el "hoy te toca" del Inicio).
// - Columna "Siguiente movimiento" con fecha y hora; la tabla se ordena por
//   lo más quemado (vencidos primero).
// - UNA espera activa por gestión. "Contratante", no "Cliente".
// - Las terminadas salen de la bandeja (filtro propio; permanencia configurable
//   en Ajustes). Gotcha vigente: breadcrumb SIEMPRE como nodo <AxCrumb/>.

function OperacionesScreen() {
  const { match } = useHashRoute();
  const detailMatch = match('/operaciones/gestion/:id');
  if (detailMatch) return <GestionDetalle id={detailMatch.params.id}/>;
  return <OperacionesBandeja/>;
}

// ─────────────────────────────────────────────────────────────────────────
// BANDEJA
// ─────────────────────────────────────────────────────────────────────────
function OperacionesBandeja() {
  const { navigate } = useHashRoute();
  const D = window.AdmixOperaciones;
  const [familiaF, setFamiliaF] = useState('all');

  const abiertas = D.GESTIONES.filter((g) => g.estadoDespacho !== 'terminada');
  const terminadas = D.GESTIONES.filter((g) => g.estadoDespacho === 'terminada');
  const enTransito = abiertas.filter((g) => g.folioEstado === 'en_transito');
  const vencidas = abiertas.filter((g) => g.siguienteMovimiento && g.siguienteMovimiento.vencido);

  const filtered = useMemo(() => {
    if (familiaF === 'terminadas') return terminadas;
    const base = familiaF === 'all'
      ? abiertas
      : abiertas.filter((g) => {
          const t = D.tramiteById(g.tramiteId);
          return t && t.familia === familiaF;
        });
    // Lo más quemado primero: vencidos arriba, luego por fecha del siguiente movimiento.
    return base.slice().sort((a, b) => {
      const oa = a.siguienteMovimiento ? a.siguienteMovimiento.orden : '9999';
      const ob = b.siguienteMovimiento ? b.siguienteMovimiento.orden : '9999';
      return oa < ob ? -1 : oa > ob ? 1 : 0;
    });
  }, [familiaF]);

  return (
    <div style={{ flex: 1, overflow: 'auto', display: 'flex', flexDirection: 'column' }}>
      <AxPageHeader
        title="Operaciones"
        subtitle={`${abiertas.length} abiertas · ${enTransito.length} en tránsito · ${vencidas.length} con movimiento vencido`}
      />

      {/* Filtros por familia + terminadas */}
      <div style={{
        padding: '18px 32px 14px', display: 'flex', gap: 8, alignItems: 'center', flexWrap: 'wrap',
        borderBottom: '1px solid var(--ax-border)',
      }}>
        <FamiliaChip label="Todas" active={familiaF === 'all'} onClick={() => setFamiliaF('all')}/>
        {D.FAMILIAS.map((f) => (
          <FamiliaChip key={f.id} label={f.label} active={familiaF === f.id} onClick={() => setFamiliaF(f.id)}/>
        ))}
        <div style={{ flex: 1 }}/>
        <FamiliaChip label={`Terminadas (${terminadas.length})`} active={familiaF === 'terminadas'} onClick={() => setFamiliaF('terminadas')}/>
        <span style={{ fontSize: 11, color: 'var(--ax-fg-faint)', fontFamily: 'var(--font-mono)' }}>
          {filtered.length} gestiones
        </span>
      </div>

      {familiaF === 'terminadas' ? (
        <div style={{ padding: '10px 32px 0', fontSize: 11, color: 'var(--ax-fg-faint)' }}>
          Las gestiones confirmadas por el portal salen de la bandeja. Cuánto tiempo permanecen visibles aquí es configurable en Ajustes.
        </div>
      ) : null}

      {/* Lista de gestiones */}
      {filtered.length === 0 ? (
        <AxEmpty icon="folder" title="Sin gestiones en esta vista" body="Prueba otro filtro de familia."/>
      ) : (
        <div style={{ flex: 1, overflow: 'auto' }}>
          <table className="ax-table">
            <thead>
              <tr>
                <th>Trámite</th>
                <th style={{ width: 220 }}>Contratante y póliza</th>
                <th style={{ width: 170 }}>Despacho</th>
                <th style={{ width: 170 }}>Aseguradora</th>
                <th style={{ width: 60 }}>Asignada</th>
                <th style={{ width: 250 }}>Siguiente movimiento</th>
                <th style={{ width: 32 }}/>
              </tr>
            </thead>
            <tbody>
              {filtered.map((g) => {
                const t = D.tramiteById(g.tramiteId);
                const familia = D.familiaById(t.familia);
                const eDespacho = D.estadoDespachoInfo(g.estadoDespacho);
                const eAseguradora = D.estadoAseguradoraInfo(g.estadoAseguradora);
                const sm = g.siguienteMovimiento;
                const vencido = sm && sm.vencido;
                return (
                  <tr key={g.id} onClick={() => navigate(`/operaciones/gestion/${g.id}`)}>
                    <td>
                      <div style={{ fontSize: 13, color: 'var(--ax-fg-strong)', fontWeight: 500 }}>{t.nombre}</div>
                      <div style={{ marginTop: 4 }}>
                        <AxPill tone="neutral">{familia.label}</AxPill>
                      </div>
                    </td>
                    <td>
                      <div style={{ fontSize: 13, color: 'var(--ax-fg)' }}>{g.contratante}</div>
                      <div className="ax-mono" style={{ fontSize: 11, color: 'var(--ax-fg-muted)', marginTop: 2, display: 'flex', alignItems: 'center', gap: 6 }}>
                        {g.poliza} <AxRamoTag code={g.ramo}/>
                      </div>
                    </td>
                    <td><AxPill tone={eDespacho.tone}>{eDespacho.label}</AxPill></td>
                    <td><AxPill tone={eAseguradora.tone}>{eAseguradora.label}</AxPill></td>
                    <td><AxAvatar name={g.asignado} size={26}/></td>
                    <td>
                      {sm ? (
                        <div>
                          <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                            {vencido ? <AxIcon name="alert" size={13} style={{ color: 'var(--ax-danger)' }}/> : null}
                            <span className="ax-mono" style={{
                              fontSize: 12, fontWeight: 600,
                              color: vencido ? 'var(--ax-danger)' : sm.tone === 'danger' ? 'var(--ax-danger)' : sm.tone === 'warm' ? 'var(--ax-warm)' : 'var(--ax-fg)',
                            }}>
                              {sm.cuando}
                            </span>
                          </div>
                          <div style={{ fontSize: 11, color: 'var(--ax-fg-muted)', marginTop: 2 }}>{sm.etiqueta}</div>
                        </div>
                      ) : <span style={{ color: 'var(--ax-fg-faint)', fontSize: 12 }}>Sin movimientos pendientes</span>}
                    </td>
                    <td style={{ textAlign: 'right' }}>
                      <AxIcon name="chevron-right" size={14} style={{ color: 'var(--ax-fg-faint)' }}/>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
}

function FamiliaChip({ label, active, onClick }) {
  return (
    <button onClick={onClick} style={{
      appearance: 'none', cursor: 'default',
      padding: '6px 12px', borderRadius: 999, fontSize: 12,
      border: '1px solid ' + (active ? 'var(--ax-accent-line)' : 'var(--ax-border)'),
      background: active ? 'var(--ax-accent-soft)' : 'var(--ax-bg-4)',
      color: active ? 'var(--ax-accent)' : 'var(--ax-fg-muted)',
      fontWeight: active ? 600 : 400,
    }}>
      {label}
    </button>
  );
}

// ─────────────────────────────────────────────────────────────────────────
// DETALLE — pantalla completa. Columna principal (proceso + requisitos) +
// rail derecho (cierre + siguiente movimiento + bitácora).
// ─────────────────────────────────────────────────────────────────────────
function GestionDetalle({ id }) {
  const { navigate } = useHashRoute();
  const D = window.AdmixOperaciones;
  const g = D.gestionById(id);
  const [folioDraft, setFolioDraft] = useState(g ? (g.folio || '') : '');

  if (!g) {
    return (
      <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        <AxEmpty icon="folder" title="Gestión no encontrada" body="Puede que haya sido archivada."
          action={<AxButton variant="secondary" onClick={() => navigate('/operaciones')}>Volver a Operaciones</AxButton>}/>
      </div>
    );
  }

  const t = D.tramiteById(g.tramiteId);
  const eDespacho = D.estadoDespachoInfo(g.estadoDespacho);
  const eAseguradora = D.estadoAseguradoraInfo(g.estadoAseguradora);
  const totalPasos = t.proceso.length;
  const nombreCorto = t.nombre.length > 28 ? t.nombre.slice(0, 26) + '…' : t.nombre;
  const requisitos = [...t.requisitos, ...(g.requisitosExtra || [])];
  const sm = g.siguienteMovimiento;

  return (
    <div style={{ flex: 1, overflow: 'auto', display: 'flex', flexDirection: 'column' }}>
      <AxPageHeader
        breadcrumb={<AxCrumb items={[{ label: 'Operaciones', to: '/operaciones' }, { label: nombreCorto }]}/>}
        title={t.nombre}
        subtitle={t.variante ? `Variante: ${t.variante}${g.varianteDetalle ? ' · ' + g.varianteDetalle : ''}` : (g.varianteDetalle || null)}
        actions={
          <div style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
            <AxPill tone={eDespacho.tone} style={{ fontSize: 13, padding: '6px 14px' }}>{eDespacho.label}</AxPill>
            <AxPill tone={eAseguradora.tone} style={{ fontSize: 13, padding: '6px 14px' }}>{eAseguradora.label}</AxPill>
          </div>
        }
      />

      {/* Franja de identidad: contratante, póliza, ramo, asignación */}
      <div style={{
        padding: '14px 32px', display: 'flex', gap: 28, alignItems: 'center', flexWrap: 'wrap',
        borderBottom: '1px solid var(--ax-border)', background: 'var(--ax-bg-1)',
      }}>
        <IdentityField label="Contratante" value={g.contratante}/>
        <IdentityField label="Póliza" value={g.poliza} mono/>
        <IdentityField label="Ramo" value={<AxRamoTag code={g.ramo} showLabel/>}/>
        <IdentityField label="Familia" value={D.familiaById(t.familia).label}/>
        <div style={{ marginLeft: 'auto', display: 'flex', alignItems: 'center', gap: 8 }}>
          <AxAvatar name={g.asignado} size={28}/>
          <div>
            <div style={{ fontSize: 10, color: 'var(--ax-fg-faint)', textTransform: 'uppercase', letterSpacing: '0.1em' }}>Asignada</div>
            <div style={{ fontSize: 13, color: 'var(--ax-fg-strong)' }}>{g.asignado}</div>
          </div>
        </div>
      </div>

      <div style={{ flex: 1, display: 'grid', gridTemplateColumns: '1.6fr 1fr', gap: 0 }}>
        {/* Columna principal */}
        <div style={{ padding: '24px 32px', borderRight: '1px solid var(--ax-border)' }}>
          {g.nota ? (
            <div style={{
              marginBottom: 20, padding: '10px 12px', display: 'flex', gap: 8, alignItems: 'flex-start',
              background: 'var(--ax-bg-2)', border: '1px solid var(--ax-border)', borderRadius: 8,
            }}>
              <AxIcon name="info" size={14} style={{ color: 'var(--ax-fg-muted)', marginTop: 1 }}/>
              <span style={{ fontSize: 12, color: 'var(--ax-fg-muted)' }}>{g.nota}</span>
            </div>
          ) : null}

          <AxEyebrow style={{ marginBottom: 12 }}>El proceso</AxEyebrow>
          <div style={{ display: 'flex', flexDirection: 'column' }}>
            {t.proceso.map((paso, i) => (
              <ProcesoStep
                key={i}
                label={paso}
                estado={i < g.pasoActualIndex ? 'hecho' : i === g.pasoActualIndex && g.pasoActualIndex < totalPasos ? 'actual' : 'futuro'}
                last={i === totalPasos - 1}
              />
            ))}
          </div>

          <AxEyebrow style={{ margin: '28px 0 12px' }}>Requisitos</AxEyebrow>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {requisitos.map((req) => {
              const faltante = g.requisitosFaltantes.includes(req);
              const adicional = (g.requisitosExtra || []).includes(req);
              return (
                <div key={req} style={{
                  display: 'flex', alignItems: 'center', gap: 10,
                  padding: '9px 12px', borderRadius: 7,
                  background: faltante ? 'var(--ax-warm-soft)' : 'var(--ax-bg-2)',
                  border: '1px solid ' + (faltante ? 'var(--ax-warm-line)' : 'var(--ax-border)'),
                }}>
                  <AxIcon name={faltante ? 'x' : 'check'} size={14} style={{ color: faltante ? 'var(--ax-warm)' : 'var(--ax-accent)' }}/>
                  <span style={{ flex: 1, fontSize: 13, color: 'var(--ax-fg)' }}>{req}</span>
                  {adicional ? <AxPill tone="info">Solicitado por GNP</AxPill> : null}
                  <AxPill tone={faltante ? 'warm' : 'accent'}>{faltante ? 'Faltante' : 'Completo'}</AxPill>
                </div>
              );
            })}
          </div>
        </div>

        {/* Rail derecho */}
        <div style={{ padding: '24px 24px', display: 'flex', flexDirection: 'column', gap: 24 }}>
          {/* SIGUIENTE MOVIMIENTO — una sola espera activa por gestión */}
          <div>
            <AxEyebrow style={{ marginBottom: 10 }}>Siguiente movimiento</AxEyebrow>
            {sm ? (
              <div style={{
                display: 'flex', gap: 10, alignItems: 'flex-start',
                padding: '12px 14px', borderRadius: 8,
                background: sm.tone === 'danger' ? 'var(--ax-danger-soft)' : sm.tone === 'warm' ? 'var(--ax-warm-soft)' : 'var(--ax-info-soft)',
                border: '1px solid ' + (sm.tone === 'danger' ? 'rgba(233,76,77,0.28)' : sm.tone === 'warm' ? 'var(--ax-warm-line)' : 'var(--ax-info-line)'),
              }}>
                <AxIcon name={sm.vencido ? 'alert' : 'cal'} size={15} style={{
                  marginTop: 1,
                  color: sm.tone === 'danger' ? 'var(--ax-danger)' : sm.tone === 'warm' ? 'var(--ax-warm)' : 'var(--ax-info)',
                }}/>
                <div>
                  <div className="ax-mono" style={{ fontSize: 13, fontWeight: 600, color: 'var(--ax-fg-strong)' }}>{sm.cuando}</div>
                  <div style={{ fontSize: 12, color: 'var(--ax-fg-muted)', marginTop: 2 }}>{sm.etiqueta}</div>
                  {sm.vencido ? (
                    <div style={{ fontSize: 11, color: 'var(--ax-danger)', marginTop: 4, fontWeight: 600 }}>
                      Vencido — actividad de seguimiento creada
                    </div>
                  ) : null}
                </div>
              </div>
            ) : (
              <div style={{ fontSize: 12, color: 'var(--ax-fg-faint)' }}>Sin movimientos pendientes.</div>
            )}
          </div>

          {/* CIERRE */}
          <div>
            <AxEyebrow style={{ marginBottom: 10 }}>Cierre</AxEyebrow>
            <AxField label="Número de transacción" helper="El cierre lo da el portal: tras el folio, la gestión queda en tránsito hasta que el motor lo confirma.">
              <AxInput
                value={folioDraft}
                onChange={(e) => setFolioDraft(e.target.value)}
                placeholder="SIGPRC… · SIGREE… · OT-…"
                style={{ fontFamily: 'var(--font-mono)' }}
              />
            </AxField>
            <div style={{ marginTop: 10 }}>
              {g.folioEstado === 'confirmado' ? (
                <div style={{ display: 'flex', alignItems: 'center', gap: 6, color: 'var(--ax-accent)', fontSize: 12, fontWeight: 600 }}>
                  <AxIcon name="check" size={13}/> Confirmada por el portal
                </div>
              ) : g.folioEstado === 'en_transito' ? (
                <div style={{ display: 'flex', alignItems: 'center', gap: 6, color: 'var(--ax-info)', fontSize: 12, fontWeight: 600 }}>
                  <AxIcon name="refresh" size={13}/> En tránsito — esperando confirmación del portal
                </div>
              ) : (
                <div style={{ fontSize: 12, color: 'var(--ax-fg-faint)' }}>Aún sin folio capturado</div>
              )}
            </div>
          </div>

          {/* BITÁCORA */}
          <div>
            <AxEyebrow style={{ marginBottom: 10 }}>Bitácora</AxEyebrow>
            <div style={{ display: 'flex', flexDirection: 'column' }}>
              {g.bitacora.map((b, i) => (
                <div key={i} style={{ display: 'flex', gap: 10 }}>
                  <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', width: 10 }}>
                    <span style={{
                      width: 7, height: 7, borderRadius: '50%', marginTop: 5, flexShrink: 0,
                      background: i === g.bitacora.length - 1 ? 'var(--ax-accent)' : 'var(--ax-fg-faint)',
                    }}/>
                    {i < g.bitacora.length - 1 ? <span style={{ flex: 1, width: 1, background: 'var(--ax-border)', minHeight: 18 }}/> : null}
                  </div>
                  <div style={{ fontSize: 12, color: 'var(--ax-fg-muted)', paddingBottom: 14 }}>{b.texto}</div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

function IdentityField({ label, value, mono }) {
  return (
    <div>
      <div style={{ fontSize: 10, color: 'var(--ax-fg-faint)', textTransform: 'uppercase', letterSpacing: '0.1em', marginBottom: 3 }}>{label}</div>
      <div className={mono ? 'ax-mono' : ''} style={{ fontSize: 13, color: 'var(--ax-fg-strong)' }}>{value}</div>
    </div>
  );
}

function ProcesoStep({ label, estado, last }) {
  const color = estado === 'hecho' ? 'var(--ax-accent)' : estado === 'actual' ? 'var(--ax-fg-strong)' : 'var(--ax-fg-faint)';
  return (
    <div style={{ display: 'flex', gap: 12 }}>
      <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', width: 18 }}>
        <span style={{
          width: 18, height: 18, borderRadius: '50%', flexShrink: 0,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          background: estado === 'hecho' ? 'var(--ax-accent-soft)' : estado === 'actual' ? 'var(--ax-bg-4)' : 'transparent',
          border: '1.5px solid ' + (estado === 'futuro' ? 'var(--ax-border-strong)' : color),
        }}>
          {estado === 'hecho' ? <AxIcon name="check" size={11} style={{ color: 'var(--ax-accent)' }}/> : null}
        </span>
        {!last ? <span style={{ flex: 1, width: 1.5, background: 'var(--ax-border)', minHeight: 22 }}/> : null}
      </div>
      <div style={{ paddingBottom: 18, fontSize: 13, color, fontWeight: estado === 'actual' ? 600 : 400 }}>
        {label}
        {estado === 'actual' ? <span style={{ marginLeft: 8 }}><AxPill tone="info">siguiente</AxPill></span> : null}
      </div>
    </div>
  );
}

Object.assign(window, { OperacionesScreen });
