// src/screen-import.jsx — §4 Bulk import. The cohort's canonical first-hour move.
// Polish target: end-to-end (source pick → progress → summary → idempotency replay
// → ruleset pull notification). Ahora también es la casa de la REVISIÓN de extracción
// (la cola de "por revisar" se mudó aquí desde Pendientes).

function ImportScreen() {
  const { state, runImport, cancelImport, dismissImport, pullRulesets, pushToast } = useAxStore();
  const { navigate } = useHashRoute();
  const tweaks = state.tweaks || {};
  const sourcePickerStyle = tweaks.importPicker || 'side_by_side';

  // local UI state
  const [source, setSource] = useState(null); // 'local' | 'drive' | null
  const [folder, setFolder] = useState(null);
  const [step, setStep] = useState('pick'); // pick | confirm | running | done | replay

  // Pull live state from the job
  const job = state.lastImport;

  // When a job is running, force the UI into running step
  useEffect(() => {
    if (job && job.status === 'running') setStep('running');
    else if (job && (job.status === 'done' || job.status === 'idempotent')) setStep('done');
  }, [job && job.status, job && job.id]);

  // ─── Source pick ───────────────────────────────────────────
  const onPickLocal = () => {
    setSource('local');
    setFolder('~/Pólizas/2026/Mayo');
    setStep('confirm');
  };
  const onPickDrive = () => {
    setSource('drive');
    setFolder('Drive: Mi unidad / Pólizas / Mayo 2026');
    setStep('confirm');
  };

  const onStart = (opts = {}) => {
    runImport(folder, opts);
    setStep('running');
  };

  const onReset = () => {
    dismissImport();
    setSource(null);
    setFolder(null);
    setStep('pick');
  };

  const onPullRulesets = () => {
    const n = pullRulesets();
    if (n > 0) {
      pushToast({
        kind: 'success',
        title: 'Catálogo actualizado',
        message: `Piixi ahora reconoce ${n} formatos más. 5 pólizas se actualizaron en tu libro.`,
        action: { label: 'Ver actualizadas', onClick: () => navigate('/polizas') },
        timeout: 10000,
      });
    } else {
      pushToast({ kind: 'info', message: 'Tu catálogo ya está al día. No hay reglas nuevas en este momento.' });
    }
  };

  return (
    <div style={{ flex: 1, overflow: 'auto', display: 'flex', flexDirection: 'column' }}>
      <AxPageHeader
        eyebrow="Importar"
        title="Cargar pólizas"
        subtitle="Piixi procesa los PDFs en tu computadora. Los archivos no se suben a ningún servidor."
        actions={
          <AxButton variant="secondary" icon="refresh" onClick={onPullRulesets}>
            Buscar reglas nuevas
          </AxButton>
        }
      />

      <div style={{ flex: 1, padding: '24px 32px 48px', maxWidth: 1100, width: '100%' }}>
        {/* Entrada persistente a la cola de revisión (lo que quedó de importaciones pasadas) */}
        {state.pendientes.length > 0 ? (
          <button onClick={() => navigate('/importar/revision')} style={{
            appearance: 'none', textAlign: 'left', cursor: 'default', width: '100%',
            marginBottom: 20, padding: '14px 16px',
            background: 'var(--ax-warm-soft)', border: '1px solid var(--ax-warm-line)',
            borderRadius: 10, color: 'inherit', display: 'flex', alignItems: 'center', gap: 14,
          }}>
            <div style={{
              width: 38, height: 38, borderRadius: 9, flexShrink: 0,
              background: 'var(--ax-bg-2)', border: '1px solid var(--ax-warm-line)',
              color: 'var(--ax-warm)', display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}><AxIcon name="inbox" size={18}/></div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 14, color: 'var(--ax-fg-strong)', fontWeight: 500 }}>
                <span className="ax-mono" style={{ color: 'var(--ax-warm)' }}>{state.pendientes.length}</span> pólizas por revisar
              </div>
              <div style={{ fontSize: 12, color: 'var(--ax-fg-muted)' }}>
                Piixi extrajo lo que pudo de importaciones anteriores. Confirma un par de campos y pasan a tu libro.
              </div>
            </div>
            <AxButton variant="secondary" size="sm" iconRight="arrow-right" onClick={(e) => { e.stopPropagation(); navigate('/importar/revision'); }}>
              Revisar
            </AxButton>
          </button>
        ) : null}

        {step === 'pick' && <SourcePicker style={sourcePickerStyle} onLocal={onPickLocal} onDrive={onPickDrive}/>}
        {step === 'confirm' && (
          <ConfirmFolder source={source} folder={folder} onBack={() => setStep('pick')}
            onStart={() => onStart()}
            previousRun={state.importHistory.find((h) => h.folder === folder)}
            onReplay={() => onStart({ replay: true })}
          />
        )}
        {step === 'running' && job && <ImportProgress job={job} onCancel={cancelImport}/>}
        {step === 'done' && job && (
          <ImportSummary job={job} onReset={onReset}
            onReplay={() => { onReset(); setSource(job.folder.startsWith('Drive') ? 'drive' : 'local'); setFolder(job.folder); setStep('confirm'); }}
          />
        )}

        <ImportHistory history={state.importHistory} currentJobId={job ? job.id : null}/>
      </div>
    </div>
  );
}

// ──────────────────────────────────────────────────────────────
// SOURCE PICKER — two variants
// ──────────────────────────────────────────────────────────────
function SourcePicker({ style, onLocal, onDrive }) {
  if (style === 'sequential') {
    return <SourcePickerSequential onLocal={onLocal} onDrive={onDrive}/>;
  }
  return <SourcePickerCards onLocal={onLocal} onDrive={onDrive}/>;
}

function SourcePickerCards({ onLocal, onDrive }) {
  return (
    <div className="ax-fade-in">
      <div style={{ marginBottom: 18, fontSize: 13, color: 'var(--ax-fg-muted)' }}>
        ¿De dónde traes las pólizas hoy?
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
        <SourceCard
          icon="folder"
          title="Carpeta local"
          body="Selecciona una carpeta en tu disco. Piixi solo lee los archivos que elijas."
          tag="Recomendado"
          onClick={onLocal}
          chip="Acceso directo"
        />
        <SourceCard
          icon="drive"
          title="Google Drive"
          body="Conecta tu cuenta y elige una carpeta. Los archivos se procesan localmente al descargarlos."
          tag="Beta"
          onClick={onDrive}
          chip="OAuth · sólo lectura"
        />
      </div>

      <div style={{
        marginTop: 24, padding: '14px 16px',
        background: 'var(--ax-bg-2)',
        border: '1px solid var(--ax-border)',
        borderRadius: 8,
        display: 'flex', alignItems: 'flex-start', gap: 12,
      }}>
        <div style={{ color: 'var(--ax-accent)', marginTop: 1 }}><AxIcon name="shield" size={16}/></div>
        <div style={{ fontSize: 12, color: 'var(--ax-fg-muted)', lineHeight: 1.55 }}>
          <strong style={{ color: 'var(--ax-fg)' }}>Procesamiento local.</strong>{' '}
          Tus pólizas se procesan en esta computadora. Piixi no las sube a ningún servidor, no las envía a la nube, y no usa IA externa.
        </div>
      </div>
    </div>
  );
}

function SourceCard({ icon, title, body, tag, onClick, chip }) {
  const [hover, setHover] = useState(false);
  return (
    <button
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      onClick={onClick}
      style={{
        appearance: 'none',
        textAlign: 'left',
        background: hover ? 'var(--ax-bg-3)' : 'var(--ax-bg-2)',
        border: '1px solid ' + (hover ? 'var(--ax-accent-line)' : 'var(--ax-border)'),
        borderRadius: 10, padding: 20,
        display: 'flex', flexDirection: 'column', gap: 14,
        transition: 'background 200ms, border-color 200ms',
        cursor: 'default', color: 'inherit',
      }}
    >
      <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between' }}>
        <div style={{
          width: 44, height: 44, borderRadius: 10,
          background: 'var(--ax-bg-3)',
          border: '1px solid var(--ax-border-strong)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          color: 'var(--ax-fg)',
        }}>
          <AxIcon name={icon} size={20}/>
        </div>
        {tag ? <AxPill tone={tag === 'Recomendado' ? 'accent' : 'neutral'}>{tag}</AxPill> : null}
      </div>
      <div>
        <h3 style={{ margin: 0, fontFamily: 'var(--font-body)', fontWeight: 600, color: 'var(--ax-fg-strong)', fontSize: 17 }}>{title}</h3>
        <p style={{ margin: '6px 0 0', fontSize: 13, color: 'var(--ax-fg-muted)', lineHeight: 1.55 }}>{body}</p>
      </div>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginTop: 4 }}>
        <span className="ax-mono" style={{ fontSize: 10, color: 'var(--ax-fg-faint)', letterSpacing: '0.12em', textTransform: 'uppercase' }}>
          {chip}
        </span>
        <span style={{ color: hover ? 'var(--ax-accent)' : 'var(--ax-fg-faint)', transition: 'color 200ms', display: 'inline-flex' }}>
          <AxIcon name="arrow-right" size={16}/>
        </span>
      </div>
    </button>
  );
}

function SourcePickerSequential({ onLocal, onDrive }) {
  const [seen, setSeen] = useState('local');
  return (
    <div className="ax-fade-in" style={{ maxWidth: 640 }}>
      <div style={{ marginBottom: 12, fontSize: 13, color: 'var(--ax-fg-muted)' }}>
        Paso 1 de 2
      </div>
      <h2 style={{ margin: 0, fontSize: 22, fontFamily: 'var(--font-body)', fontWeight: 600, color: 'var(--ax-fg-strong)' }}>
        ¿De dónde traes las pólizas?
      </h2>
      <p style={{ marginTop: 6, fontSize: 13, color: 'var(--ax-fg-muted)' }}>
        Elige una sola fuente para esta carga. Después puedes correr otra desde la misma pantalla.
      </p>

      <div style={{ marginTop: 22, display: 'flex', flexDirection: 'column', gap: 8 }}>
        <SequentialOption
          icon="folder" title="Carpeta local" body="Una carpeta en este equipo."
          active={seen === 'local'} onClick={() => setSeen('local')} onChoose={onLocal} chip="Recomendado"
        />
        <SequentialOption
          icon="drive" title="Google Drive" body="Una carpeta de Drive vía OAuth."
          active={seen === 'drive'} onClick={() => setSeen('drive')} onChoose={onDrive} chip="Beta"
        />
      </div>

      <div style={{ marginTop: 24, fontSize: 12, color: 'var(--ax-fg-faint)', display: 'flex', gap: 6, alignItems: 'center' }}>
        <AxIcon name="shield" size={13}/> Los archivos se procesan en tu computadora.
      </div>
    </div>
  );
}

function SequentialOption({ icon, title, body, active, onClick, onChoose, chip }) {
  return (
    <div
      onClick={onClick}
      style={{
        background: active ? 'var(--ax-bg-3)' : 'var(--ax-bg-2)',
        border: '1px solid ' + (active ? 'var(--ax-accent-line)' : 'var(--ax-border)'),
        borderRadius: 10, padding: 16,
        display: 'flex', alignItems: 'center', gap: 14,
        transition: 'all 180ms', cursor: 'default',
      }}
    >
      <div style={{
        width: 14, height: 14, borderRadius: '50%',
        border: '1.5px solid ' + (active ? 'var(--ax-accent)' : 'var(--ax-border-strong)'),
        background: active ? 'var(--ax-accent)' : 'transparent',
        flexShrink: 0, display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
      }}>
        {active ? <span style={{ width: 6, height: 6, borderRadius: '50%', background: '#0A0A0A' }}/> : null}
      </div>
      <AxIcon name={icon} size={20} style={{ color: 'var(--ax-fg-muted)' }}/>
      <div style={{ flex: 1 }}>
        <div style={{ fontWeight: 500, color: 'var(--ax-fg-strong)' }}>{title}</div>
        <div style={{ fontSize: 12, color: 'var(--ax-fg-muted)' }}>{body}</div>
      </div>
      {chip ? <AxPill tone={chip === 'Recomendado' ? 'accent' : 'neutral'}>{chip}</AxPill> : null}
      {active ? <AxButton size="sm" variant="primary" onClick={(e) => { e.stopPropagation(); onChoose(); }}>Continuar</AxButton> : null}
    </div>
  );
}

// ──────────────────────────────────────────────────────────────
// CONFIRM FOLDER
// ──────────────────────────────────────────────────────────────
function ConfirmFolder({ source, folder, onBack, onStart, previousRun, onReplay }) {
  const fileCount = AdmixData.IMPORT_FILES.length;
  return (
    <div className="ax-fade-in" style={{ maxWidth: 720 }}>
      <button onClick={onBack} className="ax-btn ax-btn--tertiary ax-btn--sm" style={{ paddingLeft: 6, marginBottom: 12 }}>
        <AxIcon name="arrow-left" size={12}/> Cambiar fuente
      </button>
      <div className="ax-card" style={{ padding: 24, background: 'var(--ax-bg-2)' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
          <div style={{
            width: 48, height: 48, borderRadius: 10,
            background: 'var(--ax-accent-soft)',
            border: '1px solid var(--ax-accent-line)',
            color: 'var(--ax-accent)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}>
            <AxIcon name={source === 'drive' ? 'drive' : 'folder'} size={22}/>
          </div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div className="ax-eyebrow" style={{ marginBottom: 4 }}>
              {source === 'drive' ? 'Google Drive' : 'Carpeta local'}
            </div>
            <div style={{ fontFamily: 'var(--font-mono)', fontSize: 14, color: 'var(--ax-fg-strong)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
              {folder}
            </div>
            <div style={{ fontSize: 12, color: 'var(--ax-fg-muted)', marginTop: 4 }}>
              {fileCount} archivos PDF detectados.
            </div>
          </div>
        </div>

        {previousRun ? (
          <div style={{
            marginTop: 18,
            padding: '12px 14px',
            background: 'var(--ax-warm-soft)',
            border: '1px solid var(--ax-warm-line)',
            borderRadius: 8,
            display: 'flex', alignItems: 'flex-start', gap: 10,
          }}>
            <div style={{ color: 'var(--ax-warm)', marginTop: 1 }}><AxIcon name="info" size={15}/></div>
            <div style={{ flex: 1, fontSize: 12, color: 'var(--ax-fg)', lineHeight: 1.5 }}>
              <div style={{ fontWeight: 500, color: 'var(--ax-fg-strong)' }}>
                Esta carpeta ya se procesó el {AdmixData.formatDateES(previousRun.startedAt.slice(0,10))}.
              </div>
              <div style={{ color: 'var(--ax-fg-muted)', marginTop: 2 }}>
                Volver a correr es seguro: los archivos repetidos se detectan por huella digital y no se duplican en tu libro.
              </div>
            </div>
          </div>
        ) : null}

        <div style={{ marginTop: 22, display: 'flex', gap: 10, justifyContent: 'flex-end' }}>
          {previousRun ? (
            <AxButton variant="secondary" icon="refresh" onClick={onReplay}>
              Volver a verificar
            </AxButton>
          ) : null}
          <AxButton variant="primary" icon="play" onClick={onStart}>
            Empezar importación
          </AxButton>
        </div>
      </div>
    </div>
  );
}

// ──────────────────────────────────────────────────────────────
// PROGRESS
// ──────────────────────────────────────────────────────────────
function ImportProgress({ job, onCancel }) {
  const pct = job.total > 0 ? Math.min(100, (job.progress / job.total) * 100) : 0;
  const elapsed = Math.round((Date.now() - job.startedAt) / 1000);
  const rate = job.progress > 0 ? job.progress / Math.max(elapsed, 1) : 1.5;
  const remaining = Math.max(0, Math.round((job.total - job.progress) / Math.max(rate, 0.5)));

  return (
    <div className="ax-fade-in" style={{ maxWidth: 720 }}>
      <div className="ax-card" style={{ padding: 24 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 14 }}>
          <div>
            <AxEyebrow>Procesando</AxEyebrow>
            <div style={{ fontSize: 22, fontWeight: 600, color: 'var(--ax-fg-strong)', marginTop: 4 }}>
              <span className="ax-mono">{job.progress}</span>
              <span style={{ color: 'var(--ax-fg-muted)' }}> / </span>
              <span className="ax-mono">{job.total}</span>
              <span style={{ color: 'var(--ax-fg-muted)', fontSize: 14, marginLeft: 6 }}>archivos</span>
            </div>
          </div>
          <div style={{ textAlign: 'right' }}>
            <div className="ax-mono" style={{ fontSize: 12, color: 'var(--ax-fg-muted)' }}>
              ≈ {remaining}s restantes
            </div>
            <div className="ax-mono" style={{ fontSize: 10, color: 'var(--ax-fg-faint)', letterSpacing: '0.1em', textTransform: 'uppercase', marginTop: 3 }}>
              {job.folder}
            </div>
          </div>
        </div>

        {/* Progress bar */}
        <div style={{
          height: 4, borderRadius: 2,
          background: 'var(--ax-bg-4)',
          overflow: 'hidden',
        }}>
          <div style={{
            height: '100%',
            width: pct + '%',
            background: 'var(--ax-accent)',
            transition: 'width 240ms var(--ease-out-expo)',
            boxShadow: '0 0 10px var(--ax-accent-soft)',
          }}/>
        </div>

        {/* Currently processing */}
        <div style={{
          marginTop: 16,
          display: 'flex', alignItems: 'center', gap: 10,
          padding: '12px 14px',
          background: 'var(--ax-bg-3)',
          borderRadius: 8,
          fontFamily: 'var(--font-mono)', fontSize: 12,
          color: 'var(--ax-fg-muted)',
        }}>
          <span className="ax-spinner" style={{ color: 'var(--ax-accent)' }}/>
          <span style={{ flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
            {job.processing || 'Iniciando…'}
          </span>
          <span style={{ color: 'var(--ax-fg-faint)' }}>{Math.round(pct)}%</span>
        </div>

        <div style={{
          marginTop: 14, fontSize: 12, color: 'var(--ax-fg-muted)',
          display: 'flex', justifyContent: 'space-between', alignItems: 'center',
        }}>
          <span>Puedes seguir trabajando — te avisamos cuando termine.</span>
          <button className="ax-btn ax-btn--tertiary ax-btn--sm" onClick={onCancel}>Cancelar</button>
        </div>
      </div>
    </div>
  );
}

// ──────────────────────────────────────────────────────────────
// SUMMARY
// ──────────────────────────────────────────────────────────────
function ImportSummary({ job, onReset, onReplay }) {
  const { navigate } = useHashRoute();
  if (job.status === 'idempotent') {
    return (
      <div className="ax-fade-in" style={{ maxWidth: 720 }}>
        <div className="ax-card" style={{ padding: 32, textAlign: 'left' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 12 }}>
            <div style={{
              width: 44, height: 44, borderRadius: 10,
              background: 'var(--ax-warm-soft)',
              border: '1px solid var(--ax-warm-line)',
              color: 'var(--ax-warm)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}>
              <AxIcon name="check" size={20}/>
            </div>
            <div>
              <AxEyebrow>Nada nuevo</AxEyebrow>
              <div style={{ fontSize: 18, fontWeight: 600, color: 'var(--ax-fg-strong)', marginTop: 2 }}>
                Estas {job.summary.alreadyImported} pólizas ya estaban en tu libro
              </div>
            </div>
          </div>
          <p style={{ margin: 0, fontSize: 13, color: 'var(--ax-fg-muted)', lineHeight: 1.6 }}>
            Procesadas el {AdmixData.formatDateES(job.summary.previousDate.slice(0,10))}. Volver a correr no duplica nada: Piixi reconoce los PDFs por huella digital.
          </p>
          <div style={{ marginTop: 20, display: 'flex', gap: 8 }}>
            <AxButton variant="secondary" icon="book" onClick={() => navigate('/polizas')}>Ver el libro</AxButton>
            <AxButton variant="tertiary" onClick={onReset}>Cargar otra carpeta</AxButton>
          </div>
        </div>
      </div>
    );
  }

  const s = job.summary;
  return (
    <div className="ax-fade-in" style={{ maxWidth: 1000 }}>
      <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 16 }}>
        <div>
          <AxEyebrow style={{ color: 'var(--ax-accent)' }}>Importación lista</AxEyebrow>
          <div style={{ fontSize: 28, fontFamily: 'var(--font-body)', fontWeight: 600, color: 'var(--ax-fg-strong)', marginTop: 4 }}>
            {job.total} archivos procesados
          </div>
          <div style={{ fontSize: 12, color: 'var(--ax-fg-muted)', marginTop: 4 }}>
            De <span className="ax-mono">{job.folder}</span> · en {Math.round((job.finishedAt - job.startedAt) / 100) / 10}s
          </div>
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          <AxButton variant="tertiary" icon="refresh" onClick={onReplay}>Re-verificar</AxButton>
          <AxButton variant="secondary" onClick={onReset}>Cargar otra</AxButton>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1.5fr 1fr 1fr', gap: 14 }}>
        {/* Matched bucket */}
        <SummaryBucket
          tone="accent" count={s.matched}
          label="Guardadas en tu libro"
          body="Reconocidas por el catálogo y aprobadas automáticamente."
          onOpen={() => navigate('/polizas')}
          openLabel="Ver pólizas"
          breakdown={s.byCarrierRamo}
        />
        <SummaryBucket
          tone="warm" count={s.pending}
          label="Por revisar"
          body="Se extrajo lo que se pudo. Necesitan un par de campos antes de aprobarlas."
          onOpen={() => navigate('/importar/revision')}
          openLabel="Ir a revisar"
        />
        <SummaryBucket
          tone="ghost" count={s.unmatched}
          label="No leídos"
          body="Archivos corruptos o protegidos con contraseña. No pasaron del clasificador."
          onOpen={() => navigate('/importar/revision?bucket=unmatched')}
          openLabel="Ver detalles"
        />
      </div>

      <div style={{
        marginTop: 20, padding: '14px 18px',
        background: 'var(--ax-bg-2)',
        border: '1px solid var(--ax-border)',
        borderRadius: 8,
        display: 'flex', alignItems: 'flex-start', gap: 12,
      }}>
        <div style={{ color: 'var(--ax-fg-muted)', marginTop: 1 }}><AxIcon name="info" size={15}/></div>
        <div style={{ fontSize: 12, color: 'var(--ax-fg-muted)', lineHeight: 1.6, flex: 1 }}>
          <strong style={{ color: 'var(--ax-fg)' }}>Por revisar no es un error.</strong>{' '}
          Es el flujo normal: Piixi extrae lo que puede, tú confirmas el resto. La cohorte aprueba típicamente {' '}
          <span style={{ color: 'var(--ax-fg)' }}>~40s por póliza</span> en estos casos.
        </div>
      </div>
    </div>
  );
}

function SummaryBucket({ tone, count, label, body, onOpen, openLabel, breakdown }) {
  const toneStyles = {
    accent: { border: 'var(--ax-accent-line)', bg: 'rgba(0,255,136,0.04)', color: 'var(--ax-accent)' },
    warm:   { border: 'var(--ax-warm-line)',   bg: 'var(--ax-warm-soft)',   color: 'var(--ax-warm)'   },
    ghost:  { border: 'var(--ax-border-strong)', bg: 'var(--ax-bg-2)',     color: 'var(--ax-fg-muted)' },
  };
  const t = toneStyles[tone] || toneStyles.ghost;
  return (
    <div style={{
      border: '1px solid ' + t.border,
      background: t.bg,
      borderRadius: 10,
      padding: 20,
      display: 'flex', flexDirection: 'column',
    }}>
      <div style={{
        fontFamily: 'var(--font-mono)', fontSize: 48, fontWeight: 700,
        color: t.color, lineHeight: 1, letterSpacing: '-0.02em',
        fontVariantNumeric: 'tabular-nums',
      }}>{count}</div>
      <div style={{ marginTop: 10, fontWeight: 500, color: 'var(--ax-fg-strong)', fontSize: 14 }}>{label}</div>
      <div style={{ marginTop: 4, fontSize: 12, color: 'var(--ax-fg-muted)', lineHeight: 1.5 }}>{body}</div>

      {breakdown && Object.keys(breakdown).length > 0 ? (
        <div style={{ marginTop: 14, paddingTop: 14, borderTop: '1px solid ' + t.border }}>
          <div className="ax-eyebrow" style={{ marginBottom: 8 }}>desglose</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
            {Object.entries(breakdown).slice(0, 6).map(([key, n]) => {
              const [carrier, ramo] = key.split(':');
              const c = AdmixData.carrierById(carrier);
              return (
                <div key={key} style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 12 }}>
                  <AxCarrierAvatar id={carrier} size={18}/>
                  <span style={{ color: 'var(--ax-fg)' }}>{c ? c.name : carrier}</span>
                  <AxRamoTag code={ramo}/>
                  <span style={{ marginLeft: 'auto', fontFamily: 'var(--font-mono)', color: 'var(--ax-fg-muted)' }}>{n}</span>
                </div>
              );
            })}
          </div>
        </div>
      ) : null}

      <div style={{ marginTop: 'auto', paddingTop: 16 }}>
        <AxButton variant="secondary" size="sm" iconRight="arrow-right" onClick={onOpen} style={{ width: '100%' }}>
          {openLabel}
        </AxButton>
      </div>
    </div>
  );
}

// ──────────────────────────────────────────────────────────────
// HISTORY
// ──────────────────────────────────────────────────────────────
function ImportHistory({ history, currentJobId }) {
  if (!history || history.length === 0) return null;
  const items = history.filter((h) => h.id !== currentJobId).slice(0, 4);
  if (items.length === 0) return null;
  return (
    <div style={{ marginTop: 32 }}>
      <AxEyebrow style={{ marginBottom: 10 }}>Importaciones recientes</AxEyebrow>
      <div className="ax-card">
        {items.map((h, i) => (
          <div key={h.id} style={{
            padding: '12px 16px',
            display: 'grid',
            gridTemplateColumns: '24px 1.5fr 1fr 1fr 1fr',
            gap: 14, alignItems: 'center',
            borderTop: i > 0 ? '1px solid var(--ax-border)' : 'none',
            fontSize: 13,
          }}>
            <AxIcon name="folder" size={14} style={{ color: 'var(--ax-fg-muted)' }}/>
            <span className="ax-mono" style={{ fontSize: 12, color: 'var(--ax-fg)' }}>{h.folder}</span>
            <span style={{ color: 'var(--ax-fg-muted)', fontSize: 12 }}>{AdmixData.formatDateES(h.startedAt.slice(0,10))}</span>
            <span style={{ fontSize: 12 }}>
              <span style={{ color: 'var(--ax-accent)' }} className="ax-mono">{h.matched}</span> guardadas ·{' '}
              <span style={{ color: 'var(--ax-warm)' }} className="ax-mono">{h.pending}</span> por revisar
            </span>
            <span style={{ textAlign: 'right' }}>
              <AxPill tone="neutral">{h.total} archivos</AxPill>
            </span>
          </div>
        ))}
      </div>
    </div>
  );
}

window.ImportScreen = ImportScreen;
