/* Stage 09 — Export. Bundles the final project package (screenplay, prompts,
   cost approvals, asset manifest, timeline manifest, subtitles) and exposes
   the download URL. Past exports from this session are kept in local state
   so the user can re-grab a previous bundle without re-bundling. */

const ScreenExport = function ScreenExport(props) {
  const data = props.data;
  const projectId = props.projectId;
  const project = data.project;
  const isLive = Boolean(data._live) && Boolean(projectId);

  const [bundling, setBundling] = React.useState(false);
  const [muxing, setMuxing] = React.useState(false);
  const [error, setError] = React.useState(null);
  const [history, setHistory] = React.useState([]); // [{ ts, kind, info }]

  const bundle = async function () {
    if (!isLive) { setError(new Error('Live project required to export.')); return; }
    setBundling(true); setError(null);
    try {
      const info = await window.CinematonAPI.exportProject(projectId);
      setHistory(function (cur) { return [{ ts: Date.now(), kind: 'bundle', info: info }].concat(cur); });
    } catch (err) { setError(err); }
    finally { setBundling(false); }
  };

  const mux = async function () {
    if (!isLive) { setError(new Error('Live project required to mux.')); return; }
    setMuxing(true); setError(null);
    try {
      const info = await window.CinematonAPI.muxFinal(projectId);
      setHistory(function (cur) { return [{ ts: Date.now(), kind: 'mux', info: info }].concat(cur); });
    } catch (err) { setError(err); }
    finally { setMuxing(false); }
  };

  const completed = (data.jobs || []).filter(function (j) { return j.status === 'complete'; }).length;
  const total = (data.jobs || []).length;
  const ready = total > 0 && completed === total;

  return (
    <div className="page" style={{ display: 'grid', gridTemplateRows: 'auto 1fr', height: '100%' }}>
      <PageHeader title="Export" sub={"Stage 09 / 09 - " + (project.title || '')}>
        {isLive && <span className="tag accent">live</span>}
        <button className="btn" onClick={mux} disabled={!isLive || muxing}>
          {muxing ? 'Muxing...' : 'Render final mp4'}
        </button>
        <button className="btn primary" onClick={bundle} disabled={!isLive || bundling}>
          {bundling ? 'Bundling...' : 'Bundle project package'}
        </button>
      </PageHeader>

      <div className="scroll" style={{ padding: 24 }}>
        <div style={{ maxWidth: 820, margin: '0 auto' }}>

          {!isLive && (
            <div className="card" style={{ padding: 18, marginBottom: 18 }}>
              <div className="card-title">Sample mode</div>
              <p className="muted" style={{ margin: '6px 0 0' }}>
                Open or create a live project to bundle a real export.
              </p>
            </div>
          )}

          <div className="card" style={{ padding: 18, marginBottom: 18 }}>
            <div className="card-title">Render readiness</div>
            <div className="row" style={{ gap: 18, marginTop: 8 }}>
              <ExportStat label="Shots complete" v={completed + ' / ' + total}/>
              <ExportStat label="Project" v={project.title || '-'}/>
              <ExportStat label="Provider" v={(data.cost && data.cost.provider) || '-'}/>
            </div>
            {!ready && total > 0 && (
              <div className="dim" style={{ fontSize: 11, marginTop: 10 }}>
                Tip: bundling now will include any rendered clips so far. Wait for all jobs to complete for the full package.
              </div>
            )}
          </div>

          <div className="card" style={{ padding: 18, marginBottom: 18 }}>
            <div className="card-title">Two outputs</div>
            <div style={{ marginTop: 8, fontSize: 13, lineHeight: 1.6, color: 'var(--fg-muted)' }}>
              <p style={{ margin: '6px 0' }}>
                <strong style={{ color: 'var(--fg)' }}>Render final mp4</strong> mixes every video clip with the
                dialogue, music, SFX, and ambience tracks per the timeline manifest. Missing assets become
                placeholders (test pattern + silence) so you always get a watchable file.
              </p>
              <p style={{ margin: '6px 0' }}>
                <strong style={{ color: 'var(--fg)' }}>Bundle project package</strong> ships a zip containing
                screenplay, prompt packets (video/dialogue/music/SFX/ambience), cost approvals, asset manifest,
                timeline manifest, and subtitles.
              </p>
            </div>
          </div>

          {history.length > 0 && (
            <div className="card" style={{ padding: 18, marginBottom: 18 }}>
              <div className="card-title">Outputs ({history.length})</div>
              <div className="col gap-sm" style={{ marginTop: 10 }}>
                {history.map(function (h) {
                  const isMux = h.kind === 'mux';
                  const path = isMux ? h.info.output_path : h.info.zip_path;
                  const subtitle = isMux
                    ? (h.info.duration_seconds + 's · ' + Math.round((h.info.bytes || 0) / 1024) + ' KB')
                    : ('SHA256: ' + (h.info.sha256 || '').slice(0, 24) + '...');
                  return (
                    <div key={h.ts} style={{ display: 'grid', gridTemplateColumns: '1fr auto auto', gap: 12, alignItems: 'center', padding: '10px 0', borderTop: '1px solid var(--line)' }}>
                      <div>
                        <div className="row gap-sm" style={{ alignItems: 'baseline' }}>
                          <span className="tag" style={{ fontSize: 9 }}>{isMux ? 'mp4' : 'zip'}</span>
                          <span className="mono" style={{ fontSize: 11, wordBreak: 'break-all' }}>{path || '-'}</span>
                        </div>
                        <div className="dim mono" style={{ fontSize: 10, marginTop: 2 }}>{subtitle}</div>
                        {isMux && Array.isArray(h.info.warnings) && h.info.warnings.length > 0 && (
                          <div className="dim" style={{ fontSize: 10, marginTop: 4, color: 'var(--bad)' }}>{h.info.warnings.length} placeholder(s)</div>
                        )}
                      </div>
                      <div className="dim mono" style={{ fontSize: 10 }}>{new Date(h.ts).toLocaleTimeString()}</div>
                      <a className="btn primary" href={h.info.download_url}>Download</a>
                    </div>
                  );
                })}
              </div>
            </div>
          )}

          {error && (
            <div className="card" style={{ borderColor: 'oklch(0.4 0.1 25)', color: 'var(--bad)' }}>
              <div className="card-title" style={{ color: 'var(--bad)' }}>Error</div>
              {error.message || String(error)}
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

const ExportStat = function ExportStat(props) {
  return (
    <div style={{ minWidth: 120 }}>
      <div className="card-title">{props.label}</div>
      <div className="serif" style={{ fontSize: 18, marginTop: 4 }}>{props.v}</div>
    </div>
  );
};

window.ScreenExport = ScreenExport;
