// RunsTimeline — V1.12.1 (Janik 2026-04-26).
// Inspiriert vom Design-Bundle scheduler-screens.jsx ScheduleDetailScreen
// (RunItem-Liste mit run-dot + tl-rail).
//
// Zeigt die letzten N Runs einer LeadQuery (ODER eines Profiles wenn keine
// LeadQuery-Filterung). Pro Run: Status-Dot (success/empty/live/failed) +
// Zeit + delivered-Counter + Justification.
//
// Datenquelle: window.CortexAPI.listRuns(profileId) — wir filtern dann
// optional auf leadQueryId.

function RunsTimeline({ profileId, leadQueryId, limit = 10 }) {
  const [runs, setRuns] = React.useState(null);
  const [error, setError] = React.useState(null);

  React.useEffect(() => {
    if (!profileId) return;
    let cancelled = false;
    window.CortexAPI.listRuns(profileId)
      .then((res) => {
        if (cancelled) return;
        const list = Array.isArray(res?.runs) ? res.runs : [];
        // Filter auf leadQueryId wenn übergeben — aktuell wird leadQueryId
        // nicht in jedem run-doc persistiert (V1.12.2-Item). Vorerst zeigen
        // wir alle runs des profiles wenn leadQueryId nicht matched.
        const filtered = leadQueryId
          ? list.filter((r) => r.leadQueryId === leadQueryId || !r.leadQueryId)
          : list;
        setRuns(filtered.slice(0, limit));
      })
      .catch((err) => {
        console.warn('[runs-timeline] listRuns failed', err);
        setError(err?.message || 'Fehler beim Laden');
      });
    return () => { cancelled = true; };
  }, [profileId, leadQueryId, limit]);

  if (error) {
    return <div className="text-[12.5px] text-ink-soft italic">Konnte Verlauf nicht laden: {error}</div>;
  }
  if (!runs) {
    return <div className="text-[12.5px] text-ink-soft italic">Lade Verlauf…</div>;
  }
  if (runs.length === 0) {
    return (
      <div className="text-center py-6 px-4 border border-line border-dashed rounded-lg">
        <div className="text-[12.5px] text-ink-soft">Noch keine Läufe für diese Suche.</div>
      </div>
    );
  }

  return (
    <div className="relative">
      {/* Rail (vertikal links) */}
      <div className="absolute left-[6px] top-2 bottom-4 w-[2px] bg-line"/>
      <ul className="space-y-3">
        {runs.map((r, i) => <RunsTimelineItem key={r.runId || i} run={r} isFirst={i === 0}/>)}
      </ul>
    </div>
  );
}

function RunsTimelineItem({ run, isFirst }) {
  const status = run.status || 'completed';
  const delivered = run.candidatesDelivered ?? 0;
  const reasoned = run.candidatesReasoned ?? 0;
  const dotClass =
    status === 'running' ? 'live' :
    status === 'failed' ? 'paused' :
    delivered === 0 ? 'empty' :
    'success';
  const time = run.startedAt ? new Date(run.startedAt) : null;
  const timeLabel = time
    ? time.toLocaleString('de-DE', { dateStyle: 'short', timeStyle: 'short' })
    : '—';
  const isLive = status === 'running';
  const isFailed = status === 'failed' || status === 'unfeasible';

  // Status-Label
  const statusLabel =
    status === 'running' ? 'läuft jetzt' :
    status === 'failed' ? 'fehlgeschlagen' :
    status === 'unfeasible' ? 'nicht erfüllbar' :
    delivered === 0 ? 'keine Treffer' :
    `${delivered} Lead${delivered === 1 ? '' : 's'} geliefert`;

  return (
    <li className="flex items-start gap-3 relative">
      <span className={`run-dot run-dot-${dotClass} flex-shrink-0 relative z-10 mt-1.5`}/>
      <div className="flex-1 min-w-0">
        <div className="flex items-center gap-2 flex-wrap">
          <span className="text-[12.5px] font-medium text-ink tabular-nums">{timeLabel}</span>
          {isLive && (
            <span className="inline-flex items-center gap-1 px-1.5 py-0.5 rounded-full text-[10px] font-medium bg-blue-50 text-blue-700">
              <span className="w-1 h-1 rounded-full bg-blue-500 pulse-dot"/>
              läuft jetzt
            </span>
          )}
          {isFirst && !isLive && (
            <span className="text-[10px] text-ink-soft uppercase tracking-[0.06em]">letzter</span>
          )}
        </div>
        <div className={`text-[12px] mt-0.5 ${isFailed ? 'text-amber-700' : 'text-ink-muted'}`}>
          {statusLabel}
          {!isFailed && reasoned > 0 && delivered > 0 && (
            <span className="text-ink-soft"> · {reasoned} bewertet</span>
          )}
          {/* V1.12.4 (Janik 2026-04-26): KEINE costUsd auf User-Seite — gehört
              ins Admin-Panel (cortex_product_invariants.md). Vorher stand hier
              "$0.000" sichtbar in der RunsTimeline der LeadQuery-Detail. */}
        </div>
        {isFailed && run.errorMessage && (
          <div className="text-[11.5px] text-amber-700 mt-0.5 leading-snug truncate">
            {run.errorMessage}
          </div>
        )}
      </div>
    </li>
  );
}

// Inline-Style (im Prototyp keine echte Tailwind-Build) — die run-dot-Klassen
// als CSS damit sie konsistent aussehen ohne extra Setup. Wird beim ersten
// Mount in den DOM injected.
(function injectRunDotCSS() {
  if (typeof document === 'undefined') return;
  if (document.getElementById('runs-timeline-style')) return;
  const style = document.createElement('style');
  style.id = 'runs-timeline-style';
  style.textContent = `
    .run-dot { width:14px; height:14px; border-radius:999px; border:3px solid #fff; box-shadow:0 0 0 1px #E6ECF5; }
    .run-dot-success { background:#10B981; box-shadow:0 0 0 1px rgba(16,185,129,0.25); }
    .run-dot-empty   { background:#94A3B8; }
    .run-dot-live    { background: linear-gradient(135deg, #1479FC, #B880FC); box-shadow:0 0 0 4px rgba(20,121,252,0.18); }
    .run-dot-paused  { background:#F59E0B; }
    .run-dot-future  { background:#fff; box-shadow: inset 0 0 0 2px #E6ECF5; }
  `;
  document.head.appendChild(style);
})();

Object.assign(window, { RunsTimeline });
