// Surface — New course.
// REAL create flow: course details → POST /v1/courses + POST /:id/draft →
// open the new (blank) course in the editor. The AI source-ingestion pipeline
// is previewed in the side card but not wired yet; PIPELINE_PHASES below also
// drives the SurfaceGenerating demo screen (Tweaks-panel jump only).

const PIPELINE_PHASES = [
  { id: 'ingest',  title: 'Reading sources',
    subtitle: 'Parse documents · transcribe video & audio',
    log: [
      'parse  Open: {file1}',
      'parse  Extracted 142 paragraphs, 8 anecdote candidates',
      'transcribe  Open: {file2}',
      'transcribe  1842 words · 11:42 runtime',
    ] },
  { id: 'classify', title: 'Classifying content',
    subtitle: 'Expository vs narrative · tag anecdotes',
    log: [
      'classify  Difficult-Interactions_v3-final.docx → Expository',
      'classify  Priya-Naidu_SME-interview.mp4 → Narrative · 4 anecdotes',
      'classify  Confidence avg 0.91',
    ] },
  { id: 'modules', title: 'Proposing modules',
    subtitle: 'Cluster claims · sequence the arc',
    log: [
      'cluster  Identified 4 thematic clusters',
      'sequence  M1 Recognising tension early',
      'sequence  M2 Frameworks for tough talks',
      'sequence  M3 The conversation itself',
      'sequence  M4 Repair & follow-through',
    ] },
  { id: 'layouts', title: 'Picking layout types',
    subtitle: 'Match content shape to the right interaction',
    log: [
      'layout  M2-L3 sequence · 6 tabs · score 0.91',
      'layout  M2-L5 small video · score 0.82',
      'layout  M3-L2 mandatory question · score 0.88',
      'layout  24 layouts placed across 4 modules',
    ] },
  { id: 'validate', title: 'Final checks',
    subtitle: 'Coverage · duplicates · validation flags',
    log: [
      'validate  Coverage 94% of source claims mapped',
      'validate  3 warnings raised — see issues panel',
      'done    Ready for review',
    ] },
];

function SurfaceNewCourse({ onCancel, onCreated }) {
  const [name, setName] = React.useState('');
  const [topic, setTopic] = React.useState('');
  const [busy, setBusy] = React.useState(false);
  const [error, setError] = React.useState(null);
  // If POST /courses succeeded but the draft POST failed, remember the row so
  // "try again" completes the SAME course instead of creating a duplicate.
  const createdRef = React.useRef(null);

  const canCreate = name.trim().length > 0 && !busy;

  // REAL create: POST /v1/courses → POST /v1/courses/:id/draft → open the new
  // course in the editor (blank content mode). The AI source-ingestion flow on
  // the right is a PREVIEW — creation always starts from an empty course.
  const handleCreate = async () => {
    if (!canCreate) return;
    setBusy(true);
    setError(null);
    try {
      const token = await window.dynamoGetAccessToken();
      const headers = {
        'Content-Type': 'application/json',
        Authorization: 'Bearer ' + token,
      };
      let row = createdRef.current;
      if (!row) {
        const res = await fetch(window.DYNAMO_ENV.gatewayBase + '/v1/courses', {
          method: 'POST', headers,
          body: JSON.stringify({
            title: name.trim(),
            topic: topic.trim() || 'General',
            brand: 'default',
            // v1 authors in English; more base languages arrive with the
            // Localisation flow (translate adds them post-authoring).
            enabledLangs: ['en'],
            defaultLang: 'en',
          }),
        });
        if (!res.ok) {
          let msg = '';
          try { msg = (await res.json()).message || ''; } catch { /* not JSON */ }
          throw new Error(`HTTP ${res.status}${msg ? `: ${msg}` : ''}`);
        }
        row = await res.json();
        createdRef.current = row;
      }
      // Give the course its (empty) draft so the first save/export has a home.
      // NOTE: this POST carries NO body, so it must NOT declare
      // `Content-Type: application/json` — Fastify's JSON parser rejects an
      // empty body (FST_ERR_CTP_EMPTY_JSON_BODY) and the client sees a 500.
      // That failure left the course row created but draft-less, which made
      // every later save 404 and every media upload fail at upload-complete.
      const draftRes = await fetch(
        `${window.DYNAMO_ENV.gatewayBase}/v1/courses/${row.id}/draft`,
        { method: 'POST', headers: { Authorization: 'Bearer ' + token } });
      if (!draftRes.ok && draftRes.status !== 409) { // 409 = already has one
        throw new Error(`draft HTTP ${draftRes.status}`);
      }
      onCreated(row);
    } catch (e) {
      setError(String((e && e.message) || e));
      setBusy(false);
    }
  };

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

        {/* Header */}
        <div style={{ marginBottom: 28 }}>
          <button onClick={onCancel} className="btn sm ghost"
            style={{ marginBottom: 18, marginLeft: -8 }}>
            <I.ArrowLeft size={13} />Cancel
          </button>
          <div style={{ fontSize: 11, fontWeight: 600, color: 'var(--text-faint)',
            letterSpacing: '.08em', textTransform: 'uppercase', marginBottom: 6 }}>
            New course
          </div>
          <h1 style={{ margin: '0 0 6px', fontSize: 26, fontWeight: 600,
            letterSpacing: '-.015em', color: 'var(--text)' }}>
            Create a course
          </h1>
          <p style={{ margin: 0, fontSize: 14, color: 'var(--text-muted)',
            lineHeight: 1.55, maxWidth: 680 }}>
            Name your course and start authoring from an empty structure. You add
            modules, layouts, media and translations yourself — AI generation from
            uploaded sources is coming later.
          </p>
        </div>

        {/* Two columns */}
        <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0, 1fr) 360px', gap: 20,
          alignItems: 'flex-start' }}>

          {/* ── Left: course details + create ───────────────────────── */}
          <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
            <div style={{
              padding: 16, background: 'var(--surface)',
              border: '1px solid var(--border)', borderRadius: 'var(--radius-md)',
              display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14,
            }}>
              <NCField label="Course name" required>
                <input value={name} onChange={e => setName(e.target.value)}
                  autoFocus placeholder="e.g. Fire Awareness"
                  className="field" style={{ width: '100%', fontSize: 13.5, height: 36 }} />
              </NCField>
              <NCField label="Topic" subtitle="Shown on the course card">
                <input value={topic} onChange={e => setTopic(e.target.value)}
                  className="field" style={{ width: '100%', fontSize: 13.5, height: 36 }}
                  placeholder="e.g. Leadership · Compliance · Safety" />
              </NCField>
              <NCField label="Authoring language"
                subtitle="Courses are authored in English for now — add more languages later in Localisation">
                <select value="en" disabled title="More base languages coming later"
                  className="field" style={{ width: '100%', fontSize: 13.5, height: 36, opacity: 0.7 }}>
                  <option value="en">English</option>
                </select>
              </NCField>
            </div>

            {error && (
              <div style={{
                padding: '12px 14px', background: 'var(--error-bg)',
                border: '1px solid var(--error)', borderRadius: 'var(--radius-md)',
                display: 'flex', alignItems: 'center', gap: 10, fontSize: 12.5,
                color: 'var(--error-text)',
              }}>
                <I.AlertCircle size={14} />
                <span>Couldn’t create the course ({error}). Try again.</span>
              </div>
            )}

            <button className="btn primary" onClick={handleCreate} disabled={!canCreate}
              style={{ height: 42, fontSize: 13.5, fontWeight: 600,
                opacity: canCreate ? 1 : 0.5, justifyContent: 'center' }}>
              {busy ? 'Creating…' : <><I.Plus size={13} />Create course</>}
            </button>
          </div>

          {/* ── Right: AI pipeline preview (not wired yet) ───────────── */}
          <NCPipelineCard />
        </div>
      </div>
    </div>
  );
}

// ── Field wrapper ──────────────────────────────────────────────────────────
function NCField({ label, subtitle, required, children }) {
  return (
    <label style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
      <span style={{ fontSize: 11.5, fontWeight: 600, color: 'var(--text-muted)',
        letterSpacing: '.02em' }}>
        {label}{required && <span style={{ color: 'var(--accent)', marginLeft: 2 }}>*</span>}
      </span>
      {children}
      {subtitle && (
        <span style={{ fontSize: 11, color: 'var(--text-faint)' }}>{subtitle}</span>
      )}
    </label>
  );
}

// ── AI pipeline side card (PREVIEW — not wired) ────────────────────────────
// The source-ingestion pipeline (upload .docx/.mp4/.mp3 → AI proposes the
// course structure) is a future feature. This card previews it honestly:
// permanently badged, its action disabled. Course creation is the REAL flow
// on the left — it starts from an empty course.
function NCPipelineCard() {
  return (
    <aside style={{
      position: 'sticky', top: 20,
      padding: 18, background: 'var(--surface)',
      border: '1px solid var(--border)', borderRadius: 'var(--radius-md)',
      display: 'flex', flexDirection: 'column', gap: 14,
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
        <span style={{
          width: 26, height: 26, borderRadius: 7,
          background: 'color-mix(in oklab, var(--accent) 14%, transparent)',
          color: 'var(--accent)',
          display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
        }}>
          <I.Sparkle size={13} />
        </span>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 13, fontWeight: 600 }}>Generate from sources</div>
          <div style={{ fontSize: 11, color: 'var(--text-muted)' }}>
            Upload documents & media, AI proposes the course
          </div>
        </div>
        <span className="pill" style={{ fontSize: 10 }}>Preview</span>
      </div>

      <div style={{
        padding: '8px 10px', fontSize: 11.5, lineHeight: 1.5,
        background: 'var(--surface-inset)', borderRadius: 'var(--radius)',
        color: 'var(--text-muted)',
      }}>
        This flow isn’t wired yet — courses currently start empty and you author
        the structure yourself. Here’s what generation will do:
      </div>

      {/* Steps */}
      <ol style={{ margin: 0, padding: 0, listStyle: 'none',
        display: 'flex', flexDirection: 'column', gap: 12 }}>
        {PIPELINE_PHASES.map((p, i) => (
          <li key={p.id} style={{ display: 'grid',
            gridTemplateColumns: '22px 1fr', gap: 10, alignItems: 'flex-start' }}>
            <span style={{
              width: 22, height: 22, borderRadius: '50%',
              background: 'var(--surface-inset)',
              color: 'var(--text-muted)',
              fontSize: 11, fontWeight: 600,
              display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
              fontFamily: 'var(--font-mono)',
            }}>{i + 1}</span>
            <div style={{ minWidth: 0 }}>
              <div style={{ fontSize: 12.5, fontWeight: 600, color: 'var(--text)' }}>
                {p.title}
              </div>
              <div style={{ fontSize: 11, color: 'var(--text-muted)', lineHeight: 1.4 }}>
                {p.subtitle}
              </div>
            </div>
          </li>
        ))}
      </ol>

      <div style={{ height: 1, background: 'var(--border)', margin: '2px 0' }} />

      <button className="btn" disabled title="Coming soon"
        style={{ width: '100%', height: 40, fontSize: 13, fontWeight: 600, opacity: 0.5 }}>
        <I.Sparkle size={13} />Generate course structure — coming soon
      </button>
    </aside>
  );
}

Object.assign(window, { SurfaceNewCourse, PIPELINE_PHASES });
