// FirstWinScreen.jsx
// Day-1 "wow moment" — student's handwritten work becomes typeset LaTeX.
// Calls POST /api/firstwin/compose with the current session id and renders
// the returned LaTeX via MathJax beside the real captured handwriting.

function FirstWinScreen({ submission, onContinue }) {
  const [stage, setStage] = React.useState("processing");
  const [progress, setProgress] = React.useState(0);
  const [result, setResult] = React.useState(null);
  const [error, setError] = React.useState(null);
  const latexRef = React.useRef(null);

  const sessionId = submission?.session_id;
  const title = submission?.title;

  // Progress crawler — runs until the backend resolves.
  React.useEffect(() => {
    if (stage !== "processing") return;
    const steps = [
      { pct: 22, label: "Reading your handwriting…" },
      { pct: 48, label: "Parsing derivation steps…" },
      { pct: 74, label: "Typesetting equations…" },
      { pct: 92, label: "Composing workbook…" },
    ];
    let i = 0;
    const tick = () => {
      if (i >= steps.length) return;
      setProgress(steps[i].pct);
      i++;
      setTimeout(tick, 1100);
    };
    tick();
  }, [stage]);

  // Fire the compose call on mount.
  React.useEffect(() => {
    let cancelled = false;
    if (!sessionId) {
      // No live session (e.g. user navigated to /firstwin directly).
      // Fall back to a placeholder reveal after a beat.
      setTimeout(() => !cancelled && setStage("reveal"), 3500);
      return () => { cancelled = true; };
    }
    (async () => {
      try {
        const r = await window.API.postFirstWinCompose({ session_id: sessionId, title });
        if (cancelled) return;
        if (r.error || !r.latex) setError(r.error || "no LaTeX returned");
        setResult(r);
        setProgress(100);
        setTimeout(() => !cancelled && setStage("reveal"), 400);
      } catch (e) {
        if (cancelled) return;
        setError(String(e));
        setStage("reveal");
      }
    })();
    return () => { cancelled = true; };
  }, [sessionId, title]);

  // Typeset LaTeX whenever it lands.
  React.useEffect(() => {
    if (stage !== "reveal" || !result?.latex || !latexRef.current) return;
    if (window.MathJax && window.MathJax.typesetPromise) {
      window.MathJax.typesetPromise([latexRef.current]).catch(() => {});
    }
  }, [stage, result]);

  if (stage === "processing") {
    return (
      <section className="firstwin firstwin-processing">
        <div className="fw-eyebrow">Day one</div>
        <h1 className="fw-serif-big">Turning your work into something you can keep.</h1>
        <div className="fw-progress">
          <div className="fw-bar"><div className="fw-bar-fill" style={{width: progress + "%"}}/></div>
          <div className="fw-progress-label">{progress}%</div>
        </div>
        <div className="fw-body">No grading. No scoring. Just your derivation, typeset.</div>
      </section>
    );
  }

  const hasReal = !!(result && result.latex);
  const downloadHref = result?.session_id ? `/workbooks/${result.session_id}.tex` : null;

  return (
    <section className="firstwin firstwin-reveal">
      <div className="fw-head">
        <div className="fw-eyebrow">Your first artifact</div>
        <h1 className="fw-serif">You solved it. Here's what you made.</h1>
      </div>

      <div className="fw-split">
        <figure className="fw-side fw-hand">
          <div className="fw-side-label">Your paper · just now</div>
          <div className="fw-paper">
            {result?.handwriting_url ? (
              <img src={result.handwriting_url} alt="your handwritten derivation" className="fw-hand-img"/>
            ) : (
              <div className="fw-hand-placeholder">No captured frames yet — draw a derivation in Study to produce a workbook.</div>
            )}
          </div>
        </figure>

        <div className="fw-arrow">
          <svg viewBox="0 0 40 40" width="28" height="28" fill="none" stroke="currentColor" strokeWidth="1.4">
            <path d="M6 20h28M24 10l10 10-10 10"/>
          </svg>
        </div>

        <figure className="fw-side fw-latex">
          <div className="fw-side-label">Your workbook{title ? ` · ${title}` : ""}</div>
          <div className="fw-document">
            <div className="fw-doc-head">
              <div className="fw-doc-title">{title || "Derivation"}</div>
              <div className="fw-doc-meta">Session {result?.session_id?.slice(0, 8) || "—"}</div>
            </div>
            <div className="fw-doc-body" ref={latexRef}>
              {hasReal ? (
                <pre className="fw-latex-raw">{result.latex}</pre>
              ) : (
                <div className="fw-note">
                  {error ? `Couldn't compose this session: ${error}.` :
                    "Start a Study session, draw a derivation, submit, and return here to see the typeset result."}
                </div>
              )}
            </div>
          </div>
        </figure>
      </div>

      <div className="fw-foot">
        <div className="fw-foot-body">This is yours. It'll stack up — one per session — into a workbook you can print the night before the exam.</div>
        <div className="fw-foot-actions">
          {downloadHref && hasReal && (
            <a className="btn-ghost" href={downloadHref} download>
              <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="1.5" style={{marginRight:6,verticalAlign:-2}}><path d="M12 3v12M7 10l5 5 5-5M4 21h16"/></svg>
              Download .tex
            </a>
          )}
          <button className="btn-primary" onClick={onContinue}>See my plan →</button>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { FirstWinScreen });
