// src/screen-dashboard.jsx — §2 Dashboard / home. Hub after sign-in.
// Layouts (tweak "inicioLayout"): 'agenda' (nuevo default — el día del agente
// como lista accionable), 'resumen3' (panorama 3 vistas) y 'clasico' (variantes
// action/queue/data). El clásico intacto vive abajo; el rediseño es AGENDA.

function DashboardScreen() {
  const { state } = useAxStore();
  const { navigate } = useHashRoute();
  const tweaks = state.tweaks || {};
  const variant = tweaks.dashboardFold || 'action_first';
  const layout = tweaks.inicioLayout || 'agenda';

  // ─── Derived stats ───────────────────────────────────────────
  const stats = useMemo(() => {
    const policies = state.policies;
    const pendientes = state.pendientes;
    const renewals = policies.filter((p) => p.status === 'RENEWAL_PENDING').length;
    const rulesetsCount = state.rulesets.filter((r) => r.installed).length;
    return {
      booked: policies.length,
      pendientes: pendientes.length,
      renewals,
      rulesets: rulesetsCount,
    };
  }, [state.policies, state.pendientes, state.rulesets]);

  const fechaHoy = AdmixPersonas.TODAY.toLocaleDateString('es-MX', { weekday: 'long', day: 'numeric', month: 'long' });

  return (
    <div style={{ flex: 1, overflow: 'auto', display: 'flex', flexDirection: 'column' }}>
      <AxPageHeader
        eyebrow={`Hola, ${state.user.name.split(' ')[0]}`}
        title="Inicio"
        subtitle={layout === 'agenda'
          ? fechaHoy.charAt(0).toUpperCase() + fechaHoy.slice(1) + ' — esto es lo que apremia hoy.'
          : layout === 'resumen3'
            ? 'Tu día de un vistazo — eventos, pendientes y cumplimiento.'
            : `Tu libro tiene ${stats.booked} pólizas, ${stats.pendientes} esperan tu revisión.`}
        actions={
          <>
            <AxButton variant="secondary" icon="refresh" onClick={() => navigate('/importar')}>
              Buscar reglas
            </AxButton>
            <AxButton variant="primary" icon="upload" onClick={() => navigate('/importar')}>
              Cargar pólizas
            </AxButton>
          </>
        }
      />

      {layout === 'agenda'
        ? <InicioAgenda stats={stats}/>
        : layout === 'resumen3'
          ? <ResumenTresVistas stats={stats}/>
          : <DashboardClasico stats={stats} variant={variant}/>}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// AGENDA (nuevo default) — el día del agente como LISTA ACCIONABLE:
// renovaciones, cobros y expedientes por completar, fechados y en lenguaje
// llano. A la derecha, el libro de un vistazo y los avisos de la cartera.
// ─────────────────────────────────────────────────────────────
function InicioAgenda({ stats }) {
  const { state } = useAxStore();
  const { navigate } = useHashRoute();

  const acciones = useMemo(() => {
    const out = [];

    // 1 · Renovaciones próximas — el ingreso del agente vive aquí.
    state.policies
      .filter((p) => p.status === 'RENEWAL_PENDING')
      .sort((a, b) => a.finVigencia.localeCompare(b.finVigencia))
      .slice(0, 5)
      .forEach((p) => {
        const parties = AdmixPersonas.partiesOfPolicy(p.id);
        const kp = (parties.find((x) => x.rol === 'CONTRATANTE') || {}).persona;
        const d = AdmixPersonas.daysUntil(p.finVigencia);
        out.push({
          id: 'ren-' + p.id, tipo: 'renovacion', icon: 'refresh', tone: 'info', dueDays: d,
          texto: <span>Renueva <strong>{p.producto}</strong> de {kp ? kp.nombre.split(/\s+/).slice(0, 2).join(' ') : '—'}</span>,
          sub: (AdmixData.carrierById(p.carrier) || {}).name + ' · ' + AdmixData.formatMoney(p.primaTotal),
          onClick: () => navigate('/polizas/' + p.id),
        });

        // …y si a quien renueva le falta identificación, hay que conseguirla ANTES.
        if (kp) {
          const kyc = AdmixPersonas.kycDe(kp.id);
          if (kyc && kyc.estado !== 'ok' && out.filter((x) => x.tipo === 'docs').length < 3) {
            out.push({
              id: 'doc-' + p.id, tipo: 'docs', icon: 'shield', tone: 'warm', dueDays: d,
              texto: <span>Consigue la identificación de <strong>{kp.nombre.split(/\s+/).slice(0, 2).join(' ')}</strong> antes de renovar</span>,
              sub: 'Art. 492 · ' + kyc.etiqueta,
              onClick: () => navigate('/clientes/' + kp.id),
            });
          }
        }
      });

    // 2 · Cobros de la semana (mensualidades).
    (window.AdmixDerive ? AdmixDerive.derivePendientes(state.policies) : [])
      .filter((t) => t.tipo === 'cobranza')
      .slice(0, 3)
      .forEach((t) => {
        const parties = AdmixPersonas.partiesOfPolicy(t.policyId);
        const kp = (parties.find((x) => x.rol === 'CONTRATANTE') || {}).persona;
        out.push({
          id: t.id, tipo: 'cobro', icon: 'inbox', tone: 'warm', dueDays: t.dueDays,
          texto: <span>Cobra la mensualidad de <strong>{kp ? kp.nombre.split(/\s+/).slice(0, 2).join(' ') : '—'}</strong></span>,
          sub: t.title.replace('Cobro mensual · ', '') + ' · ' + (AdmixData.carrierById(t.carrier) || {}).name,
          onClick: () => navigate('/polizas/' + t.policyId),
        });
      });

    // 3 · Archivos importados esperando revisión (una sola línea, al final:
    // es trabajo de rutina — lo fechado con dinero en juego va primero).
    if (state.pendientes.length > 0) {
      out.push({
        id: 'rev', tipo: 'revision', icon: 'eye', tone: 'neutral', dueDays: 99,
        texto: <span>Revisa <strong>{state.pendientes.length} archivos</strong> recién importados</span>,
        sub: '≈ ' + Math.round(state.pendientes.length * 40 / 60) + ' min en total',
        onClick: () => navigate('/pendientes'),
      });
    }

    out.sort((a, b) => a.dueDays - b.dueDays);
    return out.slice(0, 9);
  }, [state.policies, state.pendientes]);

  const primaLibro = state.policies
    .filter((p) => ['AUTO_APPROVED', 'MANUALLY_APPROVED', 'RENEWED', 'RENEWAL_PENDING'].includes(p.status))
    .reduce((s, p) => s + p.primaTotal, 0);
  const vigentes = state.policies.filter((p) => ['AUTO_APPROVED', 'MANUALLY_APPROVED', 'RENEWED', 'RENEWAL_PENDING'].includes(p.status)).length;
  const personas = AdmixPersonas.personasConCartera();
  const nDup = AdmixPersonas.DUP_CLUSTERS.length;
  const expedientesIncompletos = personas.filter((r) => r.kyc && r.kyc.perfil.requiereCopias && r.kyc.estado !== 'ok').length;
  const reglasNuevas = state.rulesets.filter((r) => !r.installed).length;

  return (
    <div style={{ flex: 1, padding: '24px 32px 48px', maxWidth: 1240, width: '100%' }}>
      <div style={{ display: 'grid', gridTemplateColumns: '1.5fr 1fr', gap: 18, alignItems: 'start' }}>
        {/* HOY TE TOCA */}
        <div className="ax-card">
          <div style={{ padding: '14px 18px', borderBottom: '1px solid var(--ax-border)', display: 'flex', alignItems: 'baseline', justifyContent: 'space-between' }}>
            <h3 style={{ margin: 0, fontSize: 14, fontWeight: 600, color: 'var(--ax-fg-strong)' }}>Hoy te toca</h3>
            <span className="ax-mono" style={{ fontSize: 11, color: 'var(--ax-fg-faint)' }}>{acciones.length} acciones</span>
          </div>
          {acciones.length === 0 ? (
            <AxEmpty icon="check" title="Nada urgente por hoy" body="Sin renovaciones ni cobros en la ventana próxima."/>
          ) : (
            <div style={{ display: 'flex', flexDirection: 'column' }}>
              {acciones.map((a, i) => {
                const color = a.tone === 'info' ? 'var(--ax-info)' : a.tone === 'warm' ? 'var(--ax-warm)' : 'var(--ax-fg-muted)';
                const soft  = a.tone === 'info' ? 'var(--ax-info-soft)' : a.tone === 'warm' ? 'var(--ax-warm-soft)' : 'var(--ax-bg-3)';
                return (
                  <button key={a.id} onClick={a.onClick} style={{
                    appearance: 'none', border: 0, background: 'transparent', color: 'inherit',
                    padding: '12px 18px', textAlign: 'left', cursor: 'default',
                    borderTop: i > 0 ? '1px solid var(--ax-border)' : 'none',
                    display: 'flex', alignItems: 'center', gap: 12,
                  }}
                    onMouseEnter={(e) => e.currentTarget.style.background = 'var(--ax-bg-3)'}
                    onMouseLeave={(e) => e.currentTarget.style.background = 'transparent'}
                  >
                    <span style={{
                      width: 28, height: 28, borderRadius: 7, flexShrink: 0,
                      background: soft, color, border: '1px solid ' + color + '33',
                      display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                    }}><AxIcon name={a.icon} size={14}/></span>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontSize: 13, color: 'var(--ax-fg)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{a.texto}</div>
                      <div style={{ fontSize: 11, color: 'var(--ax-fg-muted)', marginTop: 1 }}>{a.sub}</div>
                    </div>
                    <span className="ax-mono" style={{
                      fontSize: 11, fontWeight: 600, whiteSpace: 'nowrap',
                      color: a.dueDays <= 3 ? 'var(--ax-warm)' : 'var(--ax-fg-muted)',
                    }}>
                      {a.tipo === 'revision' ? '' : a.dueDays <= 0 ? 'hoy' : a.dueDays === 1 ? 'mañana' : 'en ' + a.dueDays + ' días'}
                    </span>
                    <AxIcon name="chevron-right" size={12} style={{ color: 'var(--ax-fg-faint)' }}/>
                  </button>
                );
              })}
            </div>
          )}
        </div>

        {/* LIBRO + AVISOS */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          <div className="ax-card">
            <div style={{ padding: '14px 18px', borderBottom: '1px solid var(--ax-border)', display: 'flex', alignItems: 'baseline', justifyContent: 'space-between' }}>
              <h3 style={{ margin: 0, fontSize: 14, fontWeight: 600, color: 'var(--ax-fg-strong)' }}>Tu libro</h3>
              <button className="ax-btn ax-btn--tertiary ax-btn--sm" onClick={() => navigate('/polizas')}>
                Ver pólizas <AxIcon name="arrow-right" size={11}/>
              </button>
            </div>
            <div style={{ padding: 18, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
              <MiniStat label="Pólizas vigentes" value={vigentes} onClick={() => navigate('/polizas')}/>
              <MiniStat label="Prima anual" value={AdmixData.formatMoney(primaLibro)} mono/>
              <MiniStat label="Personas en cartera" value={personas.length} onClick={() => navigate('/clientes')}/>
              <MiniStat label="Por renovar (30d)" value={stats.renewals} tone="info" onClick={() => navigate('/polizas?filter=renewal')}/>
            </div>
          </div>

          <div className="ax-card">
            <div style={{ padding: '14px 18px', borderBottom: '1px solid var(--ax-border)' }}>
              <h3 style={{ margin: 0, fontSize: 14, fontWeight: 600, color: 'var(--ax-fg-strong)' }}>Para tu tranquilidad</h3>
            </div>
            <div style={{ display: 'flex', flexDirection: 'column' }}>
              <AvisoRow
                icon="copy" tone={nDup > 0 ? 'warm' : 'ok'}
                texto={nDup > 0 ? nDup + ' personas con fichas repetidas' : 'Sin fichas repetidas'}
                sub={nDup > 0 ? 'Únelas para ver su cartera completa' : 'Cada persona tiene una sola ficha'}
                onClick={nDup > 0 ? () => navigate('/clientes/duplicados') : null}
              />
              <AvisoRow
                icon="shield" tone={expedientesIncompletos > 0 ? 'warm' : 'ok'}
                texto={expedientesIncompletos > 0 ? expedientesIncompletos + ' expedientes de identificación incompletos' : 'Identificación al día'}
                sub={expedientesIncompletos > 0 ? 'Art. 492 · documentos por conseguir o cotejar' : 'Todos los expedientes en regla'}
                onClick={expedientesIncompletos > 0 ? () => navigate('/clientes') : null}
                top
              />
              <AvisoRow
                icon="tag" tone={reglasNuevas > 0 ? 'info' : 'ok'}
                texto={reglasNuevas > 0 ? reglasNuevas + ' formatos nuevos disponibles' : 'Catálogo al día'}
                sub={reglasNuevas > 0 ? 'Instálalos para reconocer más PDFs' : 'Piixi reconoce tus formatos'}
                onClick={reglasNuevas > 0 ? () => navigate('/catalogo') : null}
                top
              />
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

function MiniStat({ label, value, sub, mono, tone, onClick }) {
  const color = tone === 'info' ? 'var(--ax-info)' : tone === 'warm' ? 'var(--ax-warm)' : 'var(--ax-fg-strong)';
  return (
    <button onClick={onClick} style={{
      appearance: 'none', border: 0, background: 'transparent', textAlign: 'left',
      color: 'inherit', cursor: 'default', padding: 0,
    }}>
      <div className="ax-eyebrow">{label}</div>
      <div className={mono ? 'ax-mono' : undefined} style={{
        marginTop: 6, fontSize: mono ? 17 : 24, fontWeight: 700, color,
        fontVariantNumeric: 'tabular-nums', letterSpacing: '-0.01em',
      }}>{value}</div>
      {sub ? <div style={{ fontSize: 11, color: 'var(--ax-fg-muted)' }}>{sub}</div> : null}
    </button>
  );
}

function AvisoRow({ icon, tone, texto, sub, onClick, top }) {
  const color = tone === 'warm' ? 'var(--ax-warm)' : tone === 'info' ? 'var(--ax-info)' : 'var(--ax-accent)';
  return (
    <button onClick={onClick || undefined} style={{
      appearance: 'none', border: 0, background: 'transparent', color: 'inherit',
      padding: '12px 18px', textAlign: 'left', cursor: 'default',
      borderTop: top ? '1px solid var(--ax-border)' : 'none',
      display: 'flex', alignItems: 'center', gap: 12, width: '100%',
    }}
      onMouseEnter={(e) => { if (onClick) e.currentTarget.style.background = 'var(--ax-bg-3)'; }}
      onMouseLeave={(e) => e.currentTarget.style.background = 'transparent'}
    >
      <span style={{
        width: 26, height: 26, borderRadius: 6, flexShrink: 0,
        background: color + '18', color, border: '1px solid ' + color + '33',
        display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
      }}><AxIcon name={tone === 'ok' ? 'check' : icon} size={13}/></span>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 13, color: 'var(--ax-fg)' }}>{texto}</div>
        <div style={{ fontSize: 11, color: 'var(--ax-fg-muted)', marginTop: 1 }}>{sub}</div>
      </div>
      {onClick ? <AxIcon name="chevron-right" size={12} style={{ color: 'var(--ax-fg-faint)' }}/> : null}
    </button>
  );
}

// ─────────────────────────────────────────────────────────────
// CLÁSICO — el dashboard original intacto (variantes de fold)
// ─────────────────────────────────────────────────────────────
function DashboardClasico({ stats, variant }) {
  return (
    <div style={{ flex: 1, padding: '24px 32px 48px', maxWidth: 1200, width: '100%' }}>
      {variant === 'action_first' && <FoldActionFirst stats={stats}/>}
      {variant === 'queue_first'  && <FoldQueueFirst stats={stats}/>}
      {variant === 'data_first'   && <FoldDataFirst stats={stats}/>}

      <KpiRow stats={stats}/>

      <div style={{ marginTop: 28, display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 18 }}>
        <RecentActivity/>
        <NextRenewals/>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// RESUMEN 3 VISTAS — Inicio como panorama del día (eventos · pendientes · cumplimiento)
// ─────────────────────────────────────────────────────────────
function ResumenTresVistas({ stats }) {
  const { state } = useAxStore();
  const { navigate } = useHashRoute();

  const hoy = (window.AdmixEventos && window.AdmixEventos.deHoy) ? window.AdmixEventos.deHoy() : [];
  const proxEvento = hoy.filter((e) => e.type === 'tarea')[0] || hoy[0] || null;
  const tareasHoy = hoy.filter((e) => e.type === 'tarea').length;

  const pend = window.AdmixDerive ? AdmixDerive.derivePendientes(state.policies) : [];
  const topPend = pend[0] || null;

  const progreso = window.AdmixCumplimiento ? window.AdmixCumplimiento.progresoCartera : 0;
  const palanca = (window.AdmixCumplimiento && window.AdmixCumplimiento.jugadaMayorPalanca)
    ? window.AdmixCumplimiento.jugadaMayorPalanca()[0] : null;

  return (
    <div style={{ flex: 1, padding: '24px 32px 48px', maxWidth: 1200, width: '100%' }}>
      <AxEyebrow style={{ marginBottom: 12 }}>Trabajo del día</AxEyebrow>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 16, marginBottom: 28 }}>
        <ResumenViewCard
          tone="accent" icon="cal" titulo="Eventos" subtitulo="el cuándo"
          metric={hoy.length} metricLabel={hoy.length === 1 ? 'evento hoy' : 'eventos hoy'}
          linea={proxEvento ? ('Próximo · ' + proxEvento.time + ' · ' + proxEvento.title) : 'Nada agendado hoy'}
          extra={tareasHoy > 0 ? (tareasHoy + ' te ' + (tareasHoy === 1 ? 'toca' : 'tocan')) : null}
          cta="Ver agenda" onClick={() => navigate('/eventos')}
        />
        <ResumenViewCard
          tone="warm" icon="inbox" titulo="Pendientes" subtitulo="qué atiendo"
          metric={pend.length} metricLabel="por atender"
          linea={topPend ? ('Más urgente · ' + (topPend.dueDays <= 0 ? 'hoy' : topPend.dueDays + 'd') + ' · ' + topPend.title) : 'Cola al día'}
          extra={null}
          cta="Ir a la cola" onClick={() => navigate('/pendientes')}
        />
        <ResumenViewCard
          tone="accent" icon="shield" titulo="Cumplimiento" subtitulo="qué falta"
          metric={progreso + '%'} metricLabel="de tu cartera al día"
          linea={palanca ? ('Mayor palanca · ' + palanca.polizasImpactadas + ' pólizas de una vez') : 'Sin jugadas pendientes'}
          extra={palanca ? palanca.label : null}
          cta="Ver cumplimiento" onClick={() => navigate('/cumplimiento')}
        />
      </div>

      <KpiRow stats={stats}/>

      <div style={{ marginTop: 28, display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 18 }}>
        <RecentActivity/>
        <NextRenewals/>
      </div>
    </div>
  );
}

function ResumenViewCard({ tone, icon, titulo, subtitulo, metric, metricLabel, linea, extra, cta, onClick }) {
  const color = tone === 'warm' ? 'var(--ax-warm)' : tone === 'info' ? 'var(--ax-info)' : 'var(--ax-accent)';
  const soft  = tone === 'warm' ? 'var(--ax-warm-soft)' : tone === 'info' ? 'var(--ax-info-soft)' : 'var(--ax-accent-soft)';
  const line  = tone === 'warm' ? 'var(--ax-warm-line)' : tone === 'info' ? 'var(--ax-info-line)' : 'var(--ax-accent-line)';
  const [hover, setHover] = useState(false);
  return (
    <button
      onClick={onClick}
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      style={{
        appearance: 'none', textAlign: 'left', cursor: 'default', color: 'inherit',
        background: 'var(--ax-bg-2)', border: '1px solid ' + (hover ? line : 'var(--ax-border)'),
        borderRadius: 12, padding: 20, display: 'flex', flexDirection: 'column', gap: 14,
        transition: 'border-color 160ms',
      }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
        <div style={{
          width: 30, height: 30, borderRadius: 8, flexShrink: 0,
          background: soft, border: '1px solid ' + line, color: color,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          <AxIcon name={icon} size={16}/>
        </div>
        <div style={{ display: 'flex', flexDirection: 'column' }}>
          <span style={{ fontSize: 14, fontWeight: 600, color: 'var(--ax-fg-strong)' }}>{titulo}</span>
          <span style={{ fontSize: 11, color: 'var(--ax-fg-faint)', fontFamily: 'var(--font-mono)', letterSpacing: '0.06em' }}>{subtitulo}</span>
        </div>
      </div>
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 8 }}>
        <span className="ax-mono" style={{ fontSize: 34, fontWeight: 700, color: color, lineHeight: 1, letterSpacing: '-0.02em', fontVariantNumeric: 'tabular-nums' }}>{metric}</span>
        <span style={{ fontSize: 12, color: 'var(--ax-fg-muted)' }}>{metricLabel}</span>
      </div>
      <div style={{ minHeight: 34 }}>
        <div style={{
          fontSize: 12, color: 'var(--ax-fg)', lineHeight: 1.4,
          overflow: 'hidden', display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical',
        }}>{linea}</div>
        {extra ? <div style={{ marginTop: 3, fontSize: 11, color: color, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{extra}</div> : null}
      </div>
      <div style={{ marginTop: 'auto', display: 'flex', alignItems: 'center', gap: 6, fontSize: 12, color: hover ? color : 'var(--ax-fg-muted)', transition: 'color 160ms' }}>
        <span>{cta}</span><AxIcon name="arrow-right" size={13}/>
      </div>
    </button>
  );
}

// ─────────────────────────────────────────────────────────────
// VARIANT A — ACTION FIRST (Cargar pólizas as the hero)
// ─────────────────────────────────────────────────────────────
function FoldActionFirst({ stats }) {
  const { navigate } = useHashRoute();
  return (
    <div className="ax-fade-in" style={{
      display: 'grid', gridTemplateColumns: '1.5fr 1fr', gap: 16, marginBottom: 28,
    }}>
      <div style={{
        background: 'linear-gradient(180deg, rgba(0,255,136,0.06), rgba(0,255,136,0.01))',
        border: '1px solid var(--ax-accent-line)',
        borderRadius: 12, padding: 28,
        position: 'relative', overflow: 'hidden',
      }}>
        <div aria-hidden style={{
          position: 'absolute', right: -40, bottom: -90,
          fontFamily: 'var(--font-logo)', fontWeight: 800,
          fontSize: 240, color: 'rgba(0,255,136,0.04)',
          letterSpacing: '-0.05em', lineHeight: 0.85, pointerEvents: 'none',
        }}>PX</div>
        <AxEyebrow style={{ color: 'var(--ax-accent)' }}>Acción principal</AxEyebrow>
        <h2 style={{
          margin: '8px 0 6px', fontFamily: 'var(--font-body)', fontWeight: 600,
          color: 'var(--ax-fg-strong)', fontSize: 26, letterSpacing: '-0.01em',
        }}>
          Carga las pólizas que faltan en tu libro.
        </h2>
        <p style={{ margin: 0, color: 'var(--ax-fg-muted)', fontSize: 14, maxWidth: 460, lineHeight: 1.55, position: 'relative', zIndex: 1 }}>
          Arrastra una carpeta o conecta tu Drive. Piixi las clasifica, extrae los campos y deja por revisar sólo lo que necesita tu confirmación.
        </p>
        <div style={{ marginTop: 22, display: 'flex', gap: 10, position: 'relative', zIndex: 1 }}>
          <AxButton variant="primary" icon="upload" onClick={() => navigate('/importar')}>
            Cargar pólizas
          </AxButton>
          <AxButton variant="tertiary" iconRight="arrow-right" onClick={() => navigate('/importar/revision')}>
            Ir a revisar
          </AxButton>
        </div>
      </div>

      <PendingPanel stats={stats} compact/>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// VARIANT B — QUEUE FIRST (Pendientes is the priority)
// ─────────────────────────────────────────────────────────────
function FoldQueueFirst({ stats }) {
  const { state } = useAxStore();
  const { navigate } = useHashRoute();
  const recent = state.pendientes.slice(0, 4);
  return (
    <div className="ax-fade-in" style={{
      background: 'var(--ax-warm-soft)',
      border: '1px solid var(--ax-warm-line)',
      borderRadius: 12,
      padding: 24, marginBottom: 28,
    }}>
      <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 16 }}>
        <div>
          <AxEyebrow style={{ color: 'var(--ax-warm)' }}>Por revisar</AxEyebrow>
          <div style={{
            marginTop: 6, fontFamily: 'var(--font-body)', fontWeight: 600,
            fontSize: 26, color: 'var(--ax-fg-strong)',
          }}>
            <span style={{ fontFamily: 'var(--font-mono)', color: 'var(--ax-warm)' }}>{stats.pendientes}</span>
            <span style={{ color: 'var(--ax-fg)', marginLeft: 10 }}>esperan tu confirmación.</span>
          </div>
          <div style={{ marginTop: 6, fontSize: 13, color: 'var(--ax-fg-muted)' }}>
            Ritmo de la cohorte: ≈40s por póliza. Te toma ≈{Math.round(stats.pendientes * 40 / 60)} min cerrarlas todas.
          </div>
        </div>
        <AxButton variant="primary" iconRight="arrow-right" onClick={() => navigate('/importar/revision')}>
          Revisar
        </AxButton>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 10 }}>
        {recent.map((p) => {
          const c = p.carrier ? AdmixData.carrierById(p.carrier) : null;
          return (
            <button
              key={p.id}
              onClick={() => navigate(`/importar/revision/${p.id}`)}
              style={{
                appearance: 'none',
                background: 'var(--ax-bg-2)',
                border: '1px solid var(--ax-border)',
                borderRadius: 8, padding: 12,
                textAlign: 'left', color: 'inherit',
                display: 'flex', flexDirection: 'column', gap: 6,
                cursor: 'default',
              }}
              onMouseEnter={(e) => e.currentTarget.style.borderColor = 'var(--ax-warm-line)'}
              onMouseLeave={(e) => e.currentTarget.style.borderColor = 'var(--ax-border)'}
            >
              <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                {c ? <AxCarrierAvatar id={p.carrier} size={18}/> : <span style={{ width: 18 }}/>}
                <span style={{ fontSize: 12, color: 'var(--ax-fg)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                  {c ? c.name : 'Sin clasificar'}
                </span>
                <AxRamoTag code={p.ramo}/>
              </div>
              <div style={{ fontSize: 12, fontFamily: 'var(--font-mono)', color: 'var(--ax-fg-muted)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                {p.filename}
              </div>
              <div style={{ fontSize: 11, color: 'var(--ax-warm)' }}>
                {AdmixData.PENDING_REASONS[p.reason].label}
              </div>
            </button>
          );
        })}
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// VARIANT C — DATA FIRST (KPI tiles dominate, smaller CTA)
// ─────────────────────────────────────────────────────────────
function FoldDataFirst({ stats }) {
  const { navigate } = useHashRoute();
  return (
    <div className="ax-fade-in" style={{
      display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12,
      marginBottom: 28,
    }}>
      <BigStat label="En tu libro"            value={stats.booked}     sub="pólizas activas"     accent="neutral" onClick={() => navigate('/polizas')}/>
      <BigStat label="Por revisar"            value={stats.pendientes} sub="esperan confirmación" accent="warm"    onClick={() => navigate('/importar/revision')}/>
      <BigStat label="Renovaciones próximas"  value={stats.renewals}   sub="próximos 30 días"     accent="info"    onClick={() => navigate('/polizas?filter=renewal')}/>
      <BigStat label="Reglas instaladas"      value={stats.rulesets}   sub="catálogo activo"      accent="accent"  onClick={() => navigate('/catalogo')}/>
    </div>
  );
}

function BigStat({ label, value, sub, accent, onClick }) {
  const accents = {
    accent:  'var(--ax-accent)',
    warm:    'var(--ax-warm)',
    info:    'var(--ax-info)',
    neutral: 'var(--ax-fg-strong)',
  };
  const [hover, setHover] = useState(false);
  return (
    <button
      onClick={onClick}
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      style={{
        appearance: 'none', textAlign: 'left',
        background: hover ? 'var(--ax-bg-3)' : 'var(--ax-bg-2)',
        border: '1px solid ' + (hover ? 'var(--ax-border-strong)' : 'var(--ax-border)'),
        borderRadius: 10, padding: 18,
        display: 'flex', flexDirection: 'column', gap: 6,
        cursor: 'default', color: 'inherit',
        transition: 'all 180ms',
      }}
    >
      <AxEyebrow>{label}</AxEyebrow>
      <div className="ax-mono" style={{
        fontSize: 40, fontWeight: 700, color: accents[accent] || accents.neutral,
        lineHeight: 1, letterSpacing: '-0.02em', marginTop: 8,
        fontVariantNumeric: 'tabular-nums',
      }}>{value}</div>
      <div style={{ fontSize: 12, color: 'var(--ax-fg-muted)' }}>{sub}</div>
    </button>
  );
}

// ─────────────────────────────────────────────────────────────
// COMMON: PENDING PANEL (used inside ActionFirst)
// ─────────────────────────────────────────────────────────────
function PendingPanel({ stats, compact }) {
  const { state } = useAxStore();
  const { navigate } = useHashRoute();
  const recent = state.pendientes.slice(0, 3);
  return (
    <div style={{
      background: 'var(--ax-bg-2)',
      border: '1px solid var(--ax-border)',
      borderRadius: 12,
      padding: 22,
    }}>
      <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 12 }}>
        <AxEyebrow style={{ color: 'var(--ax-warm)' }}>Por revisar</AxEyebrow>
        <span style={{
          fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--ax-fg-faint)',
        }}>{stats.pendientes} archivos</span>
      </div>
      <div style={{ fontSize: 14, color: 'var(--ax-fg-strong)', marginBottom: 14 }}>
        Lo más reciente que esperaba tu mirada.
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
        {recent.map((p) => {
          const c = p.carrier ? AdmixData.carrierById(p.carrier) : null;
          return (
            <button
              key={p.id}
              onClick={() => navigate(`/importar/revision/${p.id}`)}
              style={{
                appearance: 'none',
                background: 'transparent', border: 0, color: 'inherit',
                padding: '8px 6px', borderRadius: 6,
                display: 'flex', alignItems: 'center', gap: 10, cursor: 'default',
                textAlign: 'left',
              }}
              onMouseEnter={(e) => e.currentTarget.style.background = 'var(--ax-bg-3)'}
              onMouseLeave={(e) => e.currentTarget.style.background = 'transparent'}
            >
              <span className="ax-pill-dot" style={{ background: 'var(--ax-warm)' }}/>
              {c ? <AxCarrierAvatar id={p.carrier} size={18}/> : <span style={{ width: 18, height: 18, borderRadius: 3, border: '1px dashed var(--ax-border-strong)' }}/>}
              <span style={{ flex: 1, fontSize: 13, color: 'var(--ax-fg)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                {c ? c.name : 'Sin clasificar'} · <span className="ax-mono" style={{ color: 'var(--ax-fg-muted)' }}>{p.filename}</span>
              </span>
              <AxIcon name="chevron-right" size={12} style={{ color: 'var(--ax-fg-faint)' }}/>
            </button>
          );
        })}
      </div>
      <div style={{ marginTop: 12, paddingTop: 12, borderTop: '1px solid var(--ax-border)' }}>
        <AxButton variant="secondary" size="sm" iconRight="arrow-right" onClick={() => navigate('/importar/revision')} style={{ width: '100%' }}>
          Ver los {stats.pendientes} por revisar
        </AxButton>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// KPI ROW (always visible; complements above-the-fold variants)
// ─────────────────────────────────────────────────────────────
function KpiRow({ stats }) {
  const { navigate } = useHashRoute();
  const tiles = [
    { label: 'En tu libro',           v: stats.booked,     hint: 'pólizas activas',    onClick: () => navigate('/polizas') },
    { label: 'Por revisar',           v: stats.pendientes, hint: 'esperando revisión', onClick: () => navigate('/importar/revision'), tone: 'warm' },
    { label: 'Renovaciones (30d)',    v: stats.renewals,   hint: 'próximas',           onClick: () => navigate('/pendientes'), tone: 'info' },
    { label: 'Reglas en catálogo',    v: stats.rulesets,   hint: 'instaladas',         onClick: () => navigate('/catalogo'), tone: 'accent' },
  ];
  return (
    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12 }}>
      {tiles.map((t) => {
        const color =
          t.tone === 'warm'    ? 'var(--ax-warm)'    :
          t.tone === 'info'    ? 'var(--ax-info)'    :
          t.tone === 'accent'  ? 'var(--ax-accent)'  : 'var(--ax-fg-strong)';
        return (
          <button
            key={t.label}
            onClick={t.onClick}
            style={{
              appearance: 'none', textAlign: 'left',
              background: 'var(--ax-bg-2)',
              border: '1px solid var(--ax-border)',
              borderRadius: 8, padding: '14px 16px',
              display: 'flex', alignItems: 'center', gap: 14,
              cursor: 'default', color: 'inherit',
              transition: 'background 150ms',
            }}
            onMouseEnter={(e) => e.currentTarget.style.background = 'var(--ax-bg-3)'}
            onMouseLeave={(e) => e.currentTarget.style.background = 'var(--ax-bg-2)'}
          >
            <div className="ax-mono" style={{
              fontSize: 30, fontWeight: 700, color, letterSpacing: '-0.02em',
              fontVariantNumeric: 'tabular-nums', minWidth: 56,
            }}>{t.v}</div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 13, color: 'var(--ax-fg-strong)', fontWeight: 500 }}>{t.label}</div>
              <div style={{ fontSize: 11, color: 'var(--ax-fg-muted)' }}>{t.hint}</div>
            </div>
            <AxIcon name="arrow-right" size={13} style={{ color: 'var(--ax-fg-faint)' }}/>
          </button>
        );
      })}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// RECENT ACTIVITY
// ─────────────────────────────────────────────────────────────
function RecentActivity() {
  const { state } = useAxStore();
  const { navigate } = useHashRoute();
  const recent = useMemo(() => {
    return state.policies.slice(0, 8).map((p) => {
      const c = AdmixData.carrierById(p.carrier);
      const k = AdmixData.contratanteById(p.contratante);
      return { ...p, _c: c, _k: k };
    });
  }, [state.policies]);

  return (
    <div className="ax-card">
      <div style={{
        padding: '14px 18px', display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        borderBottom: '1px solid var(--ax-border)',
      }}>
        <h3 style={{ margin: 0, fontSize: 14, fontWeight: 500, color: 'var(--ax-fg-strong)' }}>
          Actividad reciente
        </h3>
        <button className="ax-btn ax-btn--tertiary ax-btn--sm" onClick={() => navigate('/polizas')}>
          Ver todo <AxIcon name="arrow-right" size={11}/>
        </button>
      </div>
      <div style={{ display: 'flex', flexDirection: 'column' }}>
        {recent.map((p, i) => (
          <button
            key={p.id}
            onClick={() => navigate(`/polizas/${p.id}`)}
            style={{
              appearance: 'none', border: 0, background: 'transparent',
              padding: '12px 18px', textAlign: 'left',
              borderTop: i > 0 ? '1px solid var(--ax-border)' : 'none',
              display: 'grid', gridTemplateColumns: '24px 1.4fr 1fr auto auto', gap: 14,
              alignItems: 'center', cursor: 'default', color: 'inherit',
            }}
            onMouseEnter={(e) => e.currentTarget.style.background = 'var(--ax-bg-3)'}
            onMouseLeave={(e) => e.currentTarget.style.background = 'transparent'}
          >
            <AxCarrierAvatar id={p.carrier} size={22}/>
            <div style={{ minWidth: 0 }}>
              <div style={{ fontSize: 13, color: 'var(--ax-fg-strong)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                {p._k ? p._k.nombre : '—'}
              </div>
              <div style={{ fontSize: 11, color: 'var(--ax-fg-muted)' }}>
                <span className="ax-mono">{p.polizaNumero}</span> · {p.producto}
              </div>
            </div>
            <AxRamoTag code={p.ramo}/>
            <span style={{ fontSize: 11, color: 'var(--ax-fg-muted)' }}>
              {AdmixData.formatDateES(p.createdAt)}
            </span>
            <AxStatusPill code={p.status}/>
          </button>
        ))}
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// NEXT RENEWALS
// ─────────────────────────────────────────────────────────────
function NextRenewals() {
  const { state } = useAxStore();
  const { navigate } = useHashRoute();
  const renewals = useMemo(() => {
    return state.policies
      .filter((p) => p.status === 'RENEWAL_PENDING')
      .sort((a, b) => a.finVigencia.localeCompare(b.finVigencia))
      .slice(0, 6);
  }, [state.policies]);

  return (
    <div className="ax-card">
      <div style={{
        padding: '14px 18px', display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        borderBottom: '1px solid var(--ax-border)',
      }}>
        <h3 style={{ margin: 0, fontSize: 14, fontWeight: 500, color: 'var(--ax-fg-strong)' }}>
          Renovaciones próximas
        </h3>
        <span className="ax-mono" style={{ fontSize: 11, color: 'var(--ax-fg-faint)' }}>30 días</span>
      </div>
      <div style={{ display: 'flex', flexDirection: 'column' }}>
        {renewals.map((p, i) => {
          const k = AdmixData.contratanteById(p.contratante);
          const today = new Date('2026-05-18');
          const fin = new Date(p.finVigencia);
          const days = Math.ceil((fin - today) / (1000 * 60 * 60 * 24));
          return (
            <button
              key={p.id}
              onClick={() => navigate(`/polizas/${p.id}`)}
              style={{
                appearance: 'none', border: 0, background: 'transparent',
                padding: '12px 18px', textAlign: 'left',
                borderTop: i > 0 ? '1px solid var(--ax-border)' : 'none',
                display: 'grid', gridTemplateColumns: '1fr auto', gap: 14,
                alignItems: 'center', cursor: 'default', color: 'inherit',
              }}
              onMouseEnter={(e) => e.currentTarget.style.background = 'var(--ax-bg-3)'}
              onMouseLeave={(e) => e.currentTarget.style.background = 'transparent'}
            >
              <div style={{ minWidth: 0 }}>
                <div style={{ fontSize: 13, color: 'var(--ax-fg-strong)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                  {k ? k.nombre : '—'}
                </div>
                <div style={{ fontSize: 11, color: 'var(--ax-fg-muted)' }}>
                  <span className="ax-mono">{p.polizaNumero}</span> · {AdmixData.carrierById(p.carrier).name}
                </div>
              </div>
              <div style={{ textAlign: 'right' }}>
                <div className="ax-mono" style={{ fontSize: 14, color: days <= 7 ? 'var(--ax-warm)' : 'var(--ax-info)', fontWeight: 600 }}>
                  {days <= 0 ? 'hoy' : days + 'd'}
                </div>
                <div className="ax-mono" style={{ fontSize: 10, color: 'var(--ax-fg-faint)' }}>
                  {AdmixData.formatDateES(p.finVigencia)}
                </div>
              </div>
            </button>
          );
        })}
      </div>
    </div>
  );
}

window.DashboardScreen = DashboardScreen;
