// Analysis Progress Screen connected to async /api/discovery/jobs
function AnalysisScreen({ payload, onRun, onComplete, onBack }) {
  const STEPS = [
    { phase: 'validating_configuration', label: 'Konfiguration validieren', detail: 'Backend prüft bestätigten Payload und Run-Modus.' },
    { phase: 'gemini_campaign_analysis', label: 'Kampagne analysieren', detail: 'Gemini extrahiert Produkt, Zielgruppe, Region und Follower-Bounds.' },
    { phase: 'pre_scrape_planning', label: 'Suchstrategie vorbereiten', detail: 'Keywords und Suchstrategie werden erzeugt.' },
    { phase: 'scrapecreators_and_scoring', label: 'Creator suchen & scoren', detail: 'ScrapeCreators-Kandidaten und Gemini-Scoring laufen.' },
    { phase: 'scrapecreators_scoring_and_socialblade', label: 'Creator + Health prüfen', detail: 'Vollständiger Lauf inklusive SocialBlade-Healthchecks.' },
    { phase: 'writing_report', label: 'Report speichern', detail: 'Run-ID-Report wird im Backend persistiert.' },
    { phase: 'complete', label: 'Abgeschlossen', detail: 'Der echte Backend-Report ist bereit.' },
  ];
  const phaseIndex = (phase) => {
    if (!phase) return 0;
    const idx = STEPS.findIndex((step) => step.phase === phase);
    if (idx >= 0) return idx;
    if (phase === 'queued' || phase === 'starting_pipeline' || phase === 'platform_detection') return phase === 'platform_detection' ? 1 : 0;
    if (phase === 'failed') return 0;
    return 0;
  };

  const [currentStep, setCurrentStep] = React.useState(0);
  const [done, setDone] = React.useState(false);
  const [error, setError] = React.useState('');
  const [job, setJob] = React.useState(null);

  React.useEffect(() => {
    let cancelled = false;
    setCurrentStep(0);
    setDone(false);
    setError('');
    setJob(null);
    if (!payload) return;

    Promise.resolve(onRun(payload, (status) => {
      if (cancelled) return;
      setJob(status);
      setCurrentStep(phaseIndex(status.phase || status.status));
    }))
      .then(() => {
        if (cancelled) return;
        setCurrentStep(STEPS.length - 1);
        setDone(true);
      })
      .catch((err) => {
        if (cancelled) return;
        setJob(err.job || null);
        setError(err.message || 'Analyse fehlgeschlagen');
      });

    return () => { cancelled = true; };
  }, [JSON.stringify(payload)]);

  const activeStep = STEPS[Math.min(currentStep, STEPS.length - 1)];
  const progressPct = error ? 100 : done ? 100 : Math.round((Math.max(0, currentStep) / (STEPS.length - 1)) * 100);
  return (
    <div style={{ flex: 1, display: 'flex', flexDirection: 'column', background: 'var(--surface-app)' }}>
      <div style={{ padding: '20px 32px', borderBottom: '1px solid var(--border)', background: 'var(--surface-card)', display: 'flex', alignItems: 'center', gap: 14 }}>
        <div>
          <div style={{ font: 'var(--type-h3)', color: 'var(--text-strong)' }}>{error ? 'Analyse gestoppt' : done ? 'Analyse abgeschlossen' : job?.runId ? 'Analyse läuft' : 'Job wird gestartet'}</div>
          <div style={{ font: 'var(--type-body-sm)', color: 'var(--text-secondary)', marginTop: 3 }}>{job?.runId ? `Run-ID: ${job.runId}` : payload?.input || 'Kampagne'}</div>
        </div>
        {done && <div style={{ marginLeft: 'auto' }}><Btn variant="accent" size="md" onClick={onComplete} iconRight={<I s={16} d={<><path d="M5 12h14"/><path d="m12 5 7 7-7 7"/></>} />}>Report ansehen</Btn></div>}
        {error && <div style={{ marginLeft: 'auto', display: 'flex', gap: 8 }}><Btn variant="secondary" size="md" onClick={onBack}>Zurück</Btn></div>}
      </div>

      <div style={{ flex: 1, display: 'flex', alignItems: 'flex-start', justifyContent: 'center', padding: '48px 32px' }}>
        <div style={{ width: '100%', maxWidth: 760 }}>
          <div style={{ marginBottom: 36, textAlign: 'center' }}>
            {error ? (
              <div>
                <div style={{ width: 56, height: 56, borderRadius: '50%', background: 'var(--reject-bg)', border: '1px solid var(--reject-solid)', display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 16px', color: 'var(--reject-solid)' }}>{Icons.warn}</div>
                <div style={{ font: 'var(--type-h2)', color: 'var(--text-strong)' }}>Analyse fehlgeschlagen</div>
                <div style={{ font: 'var(--type-body)', color: 'var(--text-secondary)', marginTop: 8 }}>{error}</div>
              </div>
            ) : done ? (
              <div>
                <div style={{ width: 56, height: 56, borderRadius: '50%', background: 'var(--approve-bg)', border: '1px solid var(--approve-solid)', display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 16px' }}>{Icons.check}</div>
                <div style={{ font: 'var(--type-h2)', color: 'var(--text-strong)' }}>Report bereit</div>
                <div style={{ font: 'var(--type-body)', color: 'var(--text-secondary)', marginTop: 8 }}>Die Backend-Pipeline hat ein echtes Ergebnis geliefert.</div>
              </div>
            ) : (
              <div>
                <div style={{ width: 56, height: 56, borderRadius: '50%', background: 'var(--brand-tint)', border: '1px solid var(--lime-400)', display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 16px' }}>
                  <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="var(--lime-700)" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M21 12a9 9 0 1 1-6.219-8.56" style={{ strokeDasharray:50, strokeDashoffset:50, animation:'spin-dash 1.5s linear infinite' }} /></svg>
                </div>
                <div style={{ font: 'var(--type-h2)', color: 'var(--text-strong)' }}>{activeStep.label}</div>
                <div style={{ font: 'var(--type-body)', color: 'var(--text-secondary)', marginTop: 8 }}>{activeStep.detail}</div>
              </div>
            )}
          </div>

          <ol style={{ listStyle: 'none', margin: 0, padding: 0, display: 'flex', flexDirection: 'column', gap: 2 }}>
            {STEPS.map((step, i) => {
              const isDone = done || i < currentStep;
              const isActive = !done && !error && i === currentStep;
              const isPending = !done && i > currentStep;
              return (
                <li key={step.phase} style={{ display: 'flex', gap: 16, alignItems: 'flex-start' }}>
                  <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', flexShrink: 0 }}>
                    <div style={{ width: 28, height: 28, borderRadius: '50%', display: 'flex', alignItems: 'center', justifyContent: 'center', font: 'var(--weight-bold) var(--text-xs)/1 var(--font-mono)', background: isDone ? 'var(--ink-950)' : isActive ? 'var(--lime-500)' : 'var(--surface-card)', color: isDone ? 'var(--lime-500)' : isActive ? 'var(--ink-950)' : 'var(--text-muted)', border: isDone ? '1px solid var(--ink-950)' : isActive ? '1px solid var(--lime-500)' : '1px solid var(--border-strong)', boxShadow: isActive ? '0 0 0 5px var(--brand-tint)' : 'none' }}>{isDone ? '✓' : i + 1}</div>
                    {i < STEPS.length - 1 && <div style={{ width: 2, minHeight: 24, marginTop: 4, marginBottom: 4, background: isDone ? 'var(--ink-950)' : 'var(--border-strong)' }} />}
                  </div>
                  <div style={{ paddingBottom: i < STEPS.length - 1 ? 20 : 0, paddingTop: 3 }}>
                    <div style={{ font: isPending ? 'var(--type-body)' : 'var(--type-label)', color: isPending ? 'var(--text-muted)' : 'var(--text-strong)' }}>{step.label}</div>
                    {(isDone || isActive) && <div style={{ font: 'var(--type-caption)', color: isActive ? 'var(--text-accent)' : 'var(--text-muted)', marginTop: 3 }}>{step.detail}</div>}
                  </div>
                </li>
              );
            })}
          </ol>

          <div style={{ marginTop: 32, display: 'flex', flexDirection: 'column', gap: 8 }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', font: 'var(--type-caption)', color: 'var(--text-muted)' }}>
              <span>{done ? 'Report bereit' : error ? 'Analyse gestoppt' : 'Analyse läuft'}</span><span className="tnum">{error ? 'Fehler' : `${progressPct}%`}</span>
            </div>
            <div style={{ height: 8, borderRadius: 'var(--radius-pill)', background: 'var(--surface-muted)', overflow: 'hidden' }}>
              <div style={{ height: '100%', borderRadius: 'var(--radius-pill)', background: error ? 'var(--reject-solid)' : done ? 'var(--approve-solid)' : 'var(--brand)', width: `${progressPct}%`, transition: 'width var(--dur-slow) var(--ease-out)' }} />
            </div>
          </div>
        </div>
      </div>
      <style>{`@keyframes spin-dash { to { stroke-dashoffset: -50; } }`}</style>
    </div>
  );
}

Object.assign(window, { AnalysisScreen });
