// Surface — Generating course structure (in-progress screen).
// Phased AI pipeline with streaming terminal log. Auto-advances and
// then routes to Course architecture for review.

function SurfaceGenerating({ courseName, files, onDone, onCancel }) {
  const phases = window.PIPELINE_PHASES || [];
  const [phaseIdx, setPhaseIdx] = React.useState(0);
  const [logs, setLogs] = React.useState([]); // array of { t: 'MM:SS', cmd, text }
  const [done, setDone] = React.useState(false);

  // Phase tick — every ~3.5s advance one step
  React.useEffect(() => {
    if (phaseIdx >= phases.length) {
      setDone(true);
      // No auto-route — user clicks "Open Course architecture" manually.
      return;
    }
    const ms = 3200 + Math.random() * 800;
    const t = setTimeout(() => setPhaseIdx(p => p + 1), ms);
    return () => clearTimeout(t);
  }, [phaseIdx, phases.length, onDone]);

  // Log line streamer — append a new line every ~700ms from the active phase
  React.useEffect(() => {
    if (phaseIdx >= phases.length) return;
    const phase = phases[phaseIdx];
    let i = 0;
    const start = Date.now();
    const id = setInterval(() => {
      if (i >= phase.log.length) { clearInterval(id); return; }
      const ms = Date.now() - start;
      const total = (phaseIdx * 3.5 * 1000) + ms;
      const ss = Math.floor(total / 1000);
      const mm = String(Math.floor(ss / 60)).padStart(2, '0');
      const sx = String(ss % 60).padStart(2, '0');
      const raw = phase.log[i]
        .replace('{file1}', (files && files[0]?.name) || 'source.docx')
        .replace('{file2}', (files && files[1]?.name) || 'source.mp4');
      const [cmd, ...rest] = raw.split(/\s+/);
      setLogs(L => [...L, { t: `${mm}:${sx}`, cmd, text: rest.join(' ') }]);
      i += 1;
    }, 680 + Math.random() * 240);
    return () => clearInterval(id);
  }, [phaseIdx]);

  // Auto-scroll the terminal
  const termRef = React.useRef(null);
  React.useEffect(() => {
    if (termRef.current) termRef.current.scrollTop = termRef.current.scrollHeight;
  }, [logs]);

  return (
    <div style={{
      height: '100%', overflowY: 'auto', background: 'var(--bg)',
    }} data-screen-label="Generating course structure">
      <div style={{ maxWidth: 920, margin: '0 auto', padding: '40px 28px 64px' }}>

        {/* Header */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 14 }}>
          <span style={{
            display: 'inline-flex', alignItems: 'center', gap: 6,
            padding: '3px 10px',
            background: 'color-mix(in oklab, var(--accent) 14%, transparent)',
            color: 'var(--accent)',
            borderRadius: 999, fontSize: 10.5, fontWeight: 700,
            letterSpacing: '.08em', textTransform: 'uppercase',
          }}>
            <span style={{ width: 6, height: 6, borderRadius: '50%',
              background: 'var(--accent)',
              animation: 'gen-pulse 1.2s ease-in-out infinite' }} />
            AI
          </span>
          <span style={{ fontSize: 11, fontWeight: 600, color: 'var(--text-muted)',
            letterSpacing: '.08em', textTransform: 'uppercase' }}>
            {done ? 'Course structure ready' : 'Generation in progress'}
          </span>
        </div>

        <h1 style={{ margin: '0 0 8px', fontSize: 28, fontWeight: 600,
          letterSpacing: '-.015em', color: 'var(--text)' }}>
          {done
            ? 'Your course structure is ready.'
            : 'Analysing your documents…'}
        </h1>
        <div style={{ fontSize: 13.5, color: 'var(--text-muted)', marginBottom: 28 }}>
          {(files?.length || 7)} documents · {courseName ? `“${courseName}”` : 'New course'} · 5-phase pipeline
        </div>

        {/* Phase list */}
        <div style={{
          background: 'var(--surface)', border: '1px solid var(--border)',
          borderRadius: 'var(--radius-md)', overflow: 'hidden',
        }}>
          <div style={{ padding: '20px 22px 8px' }}>
            <ol style={{ margin: 0, padding: 0, listStyle: 'none',
              display: 'flex', flexDirection: 'column', gap: 4 }}>
              {phases.map((p, i) => {
                const state = i < phaseIdx ? 'done' : i === phaseIdx ? 'active' : 'idle';
                return <PhaseRow key={p.id} phase={p} index={i} state={state} />;
              })}
              {/* Trailing 'done' row when finished */}
              {done && (
                <PhaseRow phase={{ title: 'Done', subtitle: 'Routing to Course architecture…' }}
                  index={phases.length} state="done" final />
              )}
            </ol>
          </div>

          {/* Terminal log */}
          <div style={{
            background: '#0f172a', color: '#e2e8f0',
            padding: '14px 18px',
            fontFamily: 'var(--font-mono, ui-monospace, SFMono-Regular, monospace)',
            fontSize: 12, lineHeight: 1.55,
            minHeight: 160, maxHeight: 220, overflowY: 'auto',
          }} ref={termRef}>
            {logs.map((l, i) => (
              <div key={i} style={{ display: 'flex', gap: 10,
                opacity: 1 - Math.min(0.55, (logs.length - i - 1) * 0.04) }}>
                <span style={{ color: '#64748b' }}>[{l.t}]</span>
                <span style={{ color: '#a78bfa', minWidth: 64 }}>{l.cmd}</span>
                <span>{l.text}</span>
              </div>
            ))}
            {!done && (
              <span style={{ display: 'inline-block', width: 7, height: 13,
                background: '#a78bfa', verticalAlign: 'middle', marginTop: 4,
                animation: 'gen-blink 1s steps(2) infinite' }} />
            )}
          </div>
        </div>

        {/* Footer actions */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 10,
          marginTop: 20, justifyContent: 'flex-end' }}>
          {!done && (
            <button className="btn sm ghost" onClick={onCancel}>
              Cancel generation
            </button>
          )}
          {done && (
            <button className="btn primary" onClick={onDone}>
              Open Course architecture<I.ArrowRight size={13} />
            </button>
          )}
        </div>
      </div>

      <style>{`
        @keyframes gen-pulse {
          0%,100% { opacity: 1; transform: scale(1); }
          50% { opacity: 0.4; transform: scale(0.75); }
        }
        @keyframes gen-blink { 50% { opacity: 0; } }
        @keyframes gen-spin { to { transform: rotate(360deg); } }
      `}</style>
    </div>
  );
}

function PhaseRow({ phase, index, state, final }) {
  return (
    <li style={{
      display: 'grid', gridTemplateColumns: '28px 1fr auto',
      gap: 12, alignItems: 'flex-start',
      padding: '10px 0',
      borderBottom: final ? 0 : '1px solid var(--border-faint)',
    }}>
      <span style={{
        width: 26, height: 26, borderRadius: '50%',
        background:
          state === 'done'   ? 'var(--text)' :
          state === 'active' ? 'color-mix(in oklab, var(--accent) 18%, transparent)' :
                               'var(--surface-inset)',
        color:
          state === 'done'   ? 'var(--bg)' :
          state === 'active' ? 'var(--accent)' :
                               'var(--text-muted)',
        display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
        fontSize: 11, fontWeight: 700, fontFamily: 'var(--font-mono)',
        border: state === 'active' ? '1.5px solid var(--accent)' : '1.5px solid transparent',
        marginTop: 1,
      }}>
        {state === 'done' ? <I.Check size={13} /> :
         state === 'active' ? (
            <span style={{ width: 10, height: 10, borderRadius: '50%',
              border: '1.5px solid var(--accent)',
              borderTopColor: 'transparent',
              animation: 'gen-spin 0.9s linear infinite' }} />
         ) : (index + 1)}
      </span>
      <div style={{ minWidth: 0 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <span style={{ fontSize: 14, fontWeight: 600,
            color: state === 'idle' ? 'var(--text-muted)' : 'var(--text)' }}>
            {phase.title}
          </span>
          {state === 'active' && (
            <span style={{ fontSize: 10.5, fontWeight: 700,
              color: 'var(--accent)', letterSpacing: '.06em',
              textTransform: 'uppercase' }}>in progress</span>
          )}
          {state === 'done' && !final && (
            <span style={{ fontSize: 10.5, fontWeight: 600,
              color: 'var(--success-text)', letterSpacing: '.04em',
              textTransform: 'lowercase' }}>completed</span>
          )}
        </div>
        {phase.subtitle && (
          <div style={{ fontSize: 12, color: 'var(--text-muted)', marginTop: 1 }}>
            {phase.subtitle}
          </div>
        )}
      </div>
    </li>
  );
}

Object.assign(window, { SurfaceGenerating });
