// src/screen-pendientes.jsx — §Pendientes. "El qué atiendo": la cola priorizada.
// Proyección del mismo motor que Eventos, pero SIN hora fija: obligaciones que
// atiendes por importancia/urgencia (renovaciones próximas, cobranza). Atendiéndola
// te mantienes al corriente. La "jugada de mayor palanca" vive en Cumplimiento —
// se complementan, no compiten. (La revisión de extracción se mudó a Importar.)

const PEND_TIPOS = {
  renovacion: { label: 'Renovación', tone: 'info', verb: 'Avisar al asegurado', toast: 'Aviso de renovación enviado' },
  cobranza:   { label: 'Cobranza',   tone: 'warm', verb: 'Registrar cobro',     toast: 'Cobro registrado' },
};

const PEND_BANDS = [
  { id: 'semana',   label: 'Para esta semana',    test: (d) => d <= 7 },
  { id: 'dos',      label: 'Próximas dos semanas', test: (d) => d > 7 && d <= 14 },
  { id: 'adelante', label: 'Más adelante',         test: (d) => d > 14 },
];

function PendientesScreen() {
  const { state, pushToast } = useAxStore();
  const { navigate } = useHashRoute();
  const [tipoF, setTipoF] = useState('all');
  const [done, setDone] = useState(() => new Set());

  const all = useMemo(
    () => (window.AdmixDerive ? AdmixDerive.derivePendientes(state.policies) : []),
    [state.policies]
  );
  const visible = useMemo(
    () => all.filter((p) => !done.has(p.id) && (tipoF === 'all' || p.tipo === tipoF)),
    [all, done, tipoF]
  );

  const attend = (item) => {
    const k = item.contratante ? AdmixData.contratanteById(item.contratante) : null;
    pushToast({ kind: 'success', message: PEND_TIPOS[item.tipo].toast + (k ? ' a ' + k.nombre + '.' : '.') });
    setDone((s) => { const n = new Set(s); n.add(item.id); return n; });
  };

  const total = all.filter((p) => !done.has(p.id)).length;
  const counts = {
    renovacion: all.filter((p) => !done.has(p.id) && p.tipo === 'renovacion').length,
    cobranza:   all.filter((p) => !done.has(p.id) && p.tipo === 'cobranza').length,
  };

  const bands = PEND_BANDS
    .map((b) => ({ ...b, items: visible.filter((p) => b.test(p.dueDays)) }))
    .filter((b) => b.items.length > 0);

  return (
    <div style={{ flex: 1, overflow: 'auto', display: 'flex', flexDirection: 'column' }}>
      <AxPageHeader
        eyebrow="Trabajo del día · qué atiendo"
        title="Pendientes"
        subtitle={total > 0
          ? `${total} cosas por atender, ordenadas por urgencia. Atiéndelas y te mantienes al corriente.`
          : 'Tu cola está al día.'}
        actions={
          <div style={{ display: 'flex', gap: 6 }}>
            {[['all', 'Todos'], ['renovacion', 'Renovaciones'], ['cobranza', 'Cobranza']].map(([v, label]) => (
              <button key={v} onClick={() => setTipoF(v)}
                className={'ax-btn ax-btn--sm ' + (tipoF === v ? 'ax-btn--secondary' : 'ax-btn--tertiary')}>
                {label}
                {v !== 'all' ? <span style={{ marginLeft: 6, fontFamily: 'var(--font-mono)', fontSize: 10, color: 'var(--ax-fg-faint)' }}>{counts[v]}</span> : null}
              </button>
            ))}
          </div>
        }
      />

      {/* puente con Cumplimiento — la jugada de mayor palanca */}
      <button onClick={() => navigate('/cumplimiento')} style={{
        appearance: 'none', textAlign: 'left', cursor: 'default',
        margin: '14px 32px 0', padding: '10px 14px',
        background: 'var(--ax-accent-soft)', border: '1px solid var(--ax-accent-line)',
        borderRadius: 8, color: 'inherit', display: 'flex', alignItems: 'center', gap: 10,
      }}>
        <AxIcon name="shield" size={15} style={{ color: 'var(--ax-accent)' }}/>
        <span style={{ flex: 1, fontSize: 12.5, color: 'var(--ax-fg)' }}>
          ¿Buscas la jugada de <span style={{ color: 'var(--ax-fg-strong)' }}>mayor palanca</span> — una acción que apaga muchos pendientes a la vez? Vive en Cumplimiento.
        </span>
        <AxIcon name="arrow-right" size={14} style={{ color: 'var(--ax-fg-faint)' }}/>
      </button>

      <div style={{ flex: 1, padding: '18px 32px 48px', maxWidth: 1000, width: '100%' }}>
        {visible.length === 0 ? (
          <AxEmpty
            icon="check"
            title={total === 0 ? 'Cola al día' : 'Nada en este filtro'}
            body={total === 0 ? 'No tienes pendientes por atender. Lo que tenga hora fija aparece en Eventos.' : 'Prueba con otro filtro.'}
            action={total === 0 ? <AxButton variant="secondary" iconRight="arrow-right" onClick={() => navigate('/eventos')}>Ir a Eventos</AxButton> : null}
          />
        ) : (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 22 }}>
            {bands.map((b) => (
              <div key={b.id}>
                <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, marginBottom: 8 }}>
                  <h2 style={{ margin: 0, fontSize: 13, fontWeight: 500, color: 'var(--ax-fg-strong)' }}>{b.label}</h2>
                  <span className="ax-mono" style={{ fontSize: 11, color: 'var(--ax-fg-faint)' }}>{b.items.length}</span>
                </div>
                <div className="ax-card">
                  {b.items.map((item, i) => <PendienteRow key={item.id} item={item} top={i > 0} attend={attend} navigate={navigate}/>)}
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}

function PendienteRow({ item, top, attend, navigate }) {
  const t = PEND_TIPOS[item.tipo];
  const k = item.contratante ? AdmixData.contratanteById(item.contratante) : null;
  const overdue = item.dueDays <= 0;
  const urgent = item.dueDays <= 3;
  const dueLabel = item.dueDays <= 0 ? 'hoy' : item.dueDays + 'd';
  const sub = item.tipo === 'renovacion' ? 'vence' : 'cobro';
  return (
    <div style={{
      padding: '12px 16px', borderTop: top ? '1px solid var(--ax-border)' : 'none',
      display: 'grid', gridTemplateColumns: '54px 116px 1fr auto', gap: 14, alignItems: 'center',
    }}>
      {/* urgencia — warm, nunca rojo */}
      <div style={{ textAlign: 'center' }}>
        <div className="ax-mono" style={{
          fontSize: 16, fontWeight: 700, lineHeight: 1, fontVariantNumeric: 'tabular-nums',
          color: urgent ? 'var(--ax-warm)' : 'var(--ax-fg-strong)',
        }}>{dueLabel}</div>
        <div style={{ fontSize: 9, fontFamily: 'var(--font-mono)', letterSpacing: '0.1em', textTransform: 'uppercase', color: 'var(--ax-fg-faint)', marginTop: 3 }}>{sub}</div>
      </div>

      {/* categoría */}
      <div><AxPill tone={t.tone} dot>{t.label}</AxPill></div>

      {/* sujeto */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, minWidth: 0 }}>
        <AxCarrierAvatar id={item.carrier} size={22}/>
        <div style={{ minWidth: 0 }}>
          <div style={{ fontSize: 13, color: 'var(--ax-fg-strong)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{item.title}</div>
          <div style={{ fontSize: 11, color: 'var(--ax-fg-muted)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
            {k ? k.nombre : '—'}{item.dueIso ? <span style={{ color: 'var(--ax-fg-faint)' }}> · {AdmixData.formatDateES(item.dueIso)}</span> : null}
          </div>
        </div>
      </div>

      {/* acciones */}
      <div style={{ display: 'flex', gap: 6, justifyContent: 'flex-end' }}>
        <AxButton variant="tertiary" size="sm" onClick={() => navigate('/polizas/' + item.policyId)}>Ver póliza</AxButton>
        <AxButton variant="secondary" size="sm" icon="check" onClick={() => attend(item)}>{t.verb}</AxButton>
      </div>
    </div>
  );
}

window.PendientesScreen = PendientesScreen;
