// Analyzing screen — animates through extraction steps, then completes.

const ANALYZE_STEPS = [
  { k: "01", label: "Reading the document", note: "" },
  { k: "02", label: "Finding the provider, dates, and totals", note: "" },
  { k: "03", label: "Pulling out each charge", note: "" },
  { k: "04", label: "Looking up what each charge means", note: "" },
  { k: "05", label: "Comparing prices in your area", note: "" },
  { k: "06", label: "Spotting duplicate or bundled charges", note: "" },
  { k: "07", label: "Writing your talking points", note: "" }
];

const Analyzing = ({ onDone, filename, waitingForApi, analysis, analyzeError, onRetry }) => {
  const [step, setStep] = React.useState(0);
  const displayName = filename || "RiverbendER_Statement.pdf";

  React.useEffect(() => {
    if (analyzeError) return; // freeze animation on error
    if (step >= ANALYZE_STEPS.length) {
      // Animation finished. If we're waiting for the API, hold here until analysis lands.
      if (waitingForApi && !analysis) return;
      const t = setTimeout(onDone, 480);
      return () => clearTimeout(t);
    }
    const t = setTimeout(() => setStep(s => s + 1), step === 0 ? 380 : 520);
    return () => clearTimeout(t);
  }, [step, waitingForApi, analysis, analyzeError]);

  // If analysis arrives after animation finished, advance.
  React.useEffect(() => {
    if (analysis && step >= ANALYZE_STEPS.length && !analyzeError) {
      const t = setTimeout(onDone, 200);
      return () => clearTimeout(t);
    }
  }, [analysis, step, analyzeError]);

  const animationDone = step >= ANALYZE_STEPS.length;
  const stillWaiting = waitingForApi && !analysis && !analyzeError && animationDone;

  return (
    <div className="analyzing fade-in">
      <div className="analyze-card">
        <div className="scanline"></div>
        <span className="eyebrow"><span className="pulse"></span> Reading your bill</span>
        <h2>{displayName}</h2>
        <ol className="steplist">
          {ANALYZE_STEPS.map((s, i) => (
            <li
              key={s.k}
              className={i < step ? 'done' : i === step ? 'active' : ''}
            >
              <span className="dot"></span>
              <span>
                <span className="marker">{s.k}</span> &nbsp; {s.label}
                {i <= step && <span style={{color: 'var(--ink-3)', fontSize: 'var(--fz-micro)', marginLeft: 12}}>{s.note}</span>}
              </span>
              <span className="marker">
                {i < step ? '✓' : i === step ? '· · ·' : ''}
              </span>
            </li>
          ))}
        </ol>

        {stillWaiting && (
          <p style={{ marginTop: 22, fontSize: 'var(--fz-small)', color: 'var(--ink-3)' }}>
            Finalizing analysis…
          </p>
        )}

        {analyzeError && (
          <div style={{
            marginTop: 22, padding: '14px 16px',
            border: '1px solid var(--warn)',
            background: 'color-mix(in oklch, var(--warn) 8%, var(--bg))',
            borderRadius: 4
          }}>
            <div style={{ fontSize: 'var(--fz-small)', color: 'var(--ink)', marginBottom: 8 }}>
              <b>We couldn't analyze that file.</b> {analyzeError}
            </div>
            <button className="btn sm" onClick={onRetry}>← Try a different file</button>
          </div>
        )}

        {!analyzeError && (
          <p style={{ marginTop: 22, fontSize: 'var(--fz-small)', color: 'var(--ink-3)' }}>
            Your file is held in memory only for this session. It is not written to disk and is not used to train any model.
            <span className="kbd" style={{ marginLeft: 10 }}>Enter</span> to skip.
          </p>
        )}
      </div>
    </div>
  );
};

Object.assign(window, { Analyzing });
