// astroparse — upload (folio drop) + animated pipeline screens

function UploadScreen({ onFile, onSample, onImportSession }) {
  const [dragging, setDragging] = React.useState(false);
  const fileRef = React.useRef(null);
  const sessionRef = React.useRef(null);

  const handleDrop = (e) => {
    e.preventDefault();
    setDragging(false);
    const f = e.dataTransfer.files && e.dataTransfer.files[0];
    if (f) onFile(f.name);
  };

  return (
    <div className="ap-screen ap-upload" data-screen-label="Upload">
      <div className="ap-wordmark">astroparse</div>
      <div
        className={'ap-folio-drop' + (dragging ? ' is-dragging' : '')}
        onDragOver={(e) => { e.preventDefault(); setDragging(true); }}
        onDragLeave={() => setDragging(false)}
        onDrop={handleDrop}
        onClick={() => fileRef.current && fileRef.current.click()}
      >
        <div className="ap-folio-pilcrow">&para;</div>
        <div className="ap-folio-title">Place a manuscript here</div>
        <div className="ap-folio-sub">
          drop an astronomy PDF, or click to browse
        </div>
        <div className="ap-folio-meta">
          parsed with pymupdf4llm &middot; annotated against the literature via Pathfinder
        </div>
        <input
          ref={fileRef} type="file" accept="application/pdf" style={{ display: 'none' }}
          onChange={(e) => { const f = e.target.files[0]; if (f) onFile(f.name); }}
        />
      </div>

      <div className="ap-upload-alt">
        <button className="ap-textbtn" onClick={onSample}>
          open Mowla &amp; Iyer (2024) — the Firefly Sparkle
        </button>
        <span className="ap-alt-sep">&middot;</span>
        <button className="ap-textbtn" onClick={() => sessionRef.current && sessionRef.current.click()}>
          reload a saved session (.json)
        </button>
        <input
          ref={sessionRef} type="file" accept="application/json" style={{ display: 'none' }}
          onChange={(e) => {
            const f = e.target.files[0];
            if (!f) return;
            const r = new FileReader();
            r.onload = () => onImportSession(r.result);
            r.readAsText(f);
          }}
        />
      </div>

      <div className="ap-upload-foot">
        prototype &mdash; parsing is simulated; any dropped PDF opens the bundled manuscript (Mowla &amp; Iyer 2024)
      </div>
    </div>
  );
}

function PipelineScreen({ fileName, onDone }) {
  const stages = window.ASTROPARSE_DATA.pipelineStages;
  // progress: index of current stage; logIdx: how many log lines shown in current stage
  const [stageIdx, setStageIdx] = React.useState(0);
  const [logIdx, setLogIdx] = React.useState(0);
  const [finished, setFinished] = React.useState(false);
  const doneRef = React.useRef(false);

  React.useEffect(() => {
    if (finished) {
      const t = setTimeout(() => { if (!doneRef.current) { doneRef.current = true; onDone(); } }, 1100);
      return () => clearTimeout(t);
    }
    const stage = stages[stageIdx];
    if (!stage) { setFinished(true); return; }
    if (logIdx < stage.logs.length) {
      const t = setTimeout(() => setLogIdx(logIdx + 1), 420);
      return () => clearTimeout(t);
    }
    const t = setTimeout(() => { setStageIdx(stageIdx + 1); setLogIdx(0); }, 380);
    return () => clearTimeout(t);
  }, [stageIdx, logIdx, finished]);

  return (
    <div className="ap-screen ap-pipeline" data-screen-label="Pipeline">
      <div className="ap-wordmark">astroparse</div>
      <div className="ap-pipe-card">
        <div className="ap-pipe-head">
          <span className="ap-pipe-file">{fileName}</span>
          <span className="ap-pipe-status">{finished ? 'ready' : 'in preparation'}</span>
        </div>
        <ol className="ap-stages">
          {stages.map((s, i) => {
            const state = i < stageIdx ? 'done' : i === stageIdx && !finished ? 'active' : finished ? 'done' : 'pending';
            const logsShown = state === 'done' ? s.logs.length : state === 'active' ? logIdx : 0;
            return (
              <li key={s.id} className={'ap-stage is-' + state}>
                <div className="ap-stage-row">
                  <span className="ap-stage-num">{s.num}.</span>
                  <span className="ap-stage-name">{s.name}</span>
                  <span className="ap-stage-tool">{s.tool}</span>
                  <span className="ap-stage-mark">{state === 'done' ? '\u2713' : state === 'active' ? '\u2026' : ''}</span>
                </div>
                {state !== 'pending' && (
                  <div className="ap-stage-logs">
                    {s.logs.slice(0, logsShown).map((l, j) => (
                      <div key={j} className="ap-log-line">{l.replace('{file}', fileName)}</div>
                    ))}
                  </div>
                )}
              </li>
            );
          })}
        </ol>
        <div className="ap-pipe-foot">
          <button className="ap-textbtn" onClick={() => { if (!doneRef.current) { doneRef.current = true; onDone(); } }}>
            skip to the manuscript &rarr;
          </button>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { UploadScreen, PipelineScreen });
