// Surface — New course · Upload source materials.
// First screen of the new-course flow. User uploads source files and
// kicks off AI ingestion that generates module + layout structure
// (no media yet — layouts are organized but unrendered).

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, onGenerate }) {
  const [name, setName] = React.useState('Difficult Interactions');
  const [topic, setTopic] = React.useState('Leadership · Conversational skills');
  const [files, setFiles] = React.useState([
    { id: 'f1', name: 'Difficult-Interactions_v3-final.docx', size: '847 KB', kind: 'doc', status: 'ok' },
    { id: 'f2', name: 'Priya-Naidu_SME-interview.mp4',        size: '184 MB', kind: 'video', status: 'ok' },
    { id: 'f3', name: 'Customer-escalation-case_audio.mp3',   size: '24 MB',  kind: 'audio', status: 'ok' },
    { id: 'f4', name: 'CLEAR-framework_handbook.docx',        size: '312 KB', kind: 'doc', status: 'ok' },
    { id: 'f5', name: 'Manager-anecdotes-collected.docx',     size: '198 KB', kind: 'doc', status: 'ok' },
  ]);
  const [dragOver, setDragOver] = React.useState(false);

  const totalBytes = '209.4 MB'; // illustrative
  const canGenerate = files.length > 0 && name.trim().length > 0;

  const handleRemove = (id) => setFiles(fs => fs.filter(f => f.id !== id));
  const handleFakeUpload = () => {
    // Prototype: drop simulates adding a new doc
    setFiles(fs => [...fs, {
      id: 'f' + (fs.length + 1),
      name: `New-source-${fs.length + 1}.docx`,
      size: '142 KB', kind: 'doc', status: 'ok',
    }]);
  };

  return (
    <div style={{
      height: '100%', overflowY: 'auto', background: 'var(--bg)',
    }} data-screen-label="New course · Upload sources">
      <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 · Step 1 of 1
          </div>
          <h1 style={{ margin: '0 0 6px', fontSize: 26, fontWeight: 600,
            letterSpacing: '-.015em', color: 'var(--text)' }}>
            Upload your source materials
          </h1>
          <p style={{ margin: 0, fontSize: 14, color: 'var(--text-muted)',
            lineHeight: 1.55, maxWidth: 680 }}>
            Drop in the documents, videos and audio that hold the content for this course.
            Dynamo Authoring will analyse them and propose a module + layout structure for you to review.
          </p>
        </div>

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

          {/* ── Left: meta + drop + files ───────────────────────────── */}
          <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>

            {/* Course meta inputs */}
            <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)}
                  className="field" style={{ width: '100%', fontSize: 13.5, height: 36 }} />
              </NCField>
              <NCField label="Topic" subtitle="Helps the AI frame layout choices">
                <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>
            </div>

            {/* Drop zone */}
            <div
              onDragOver={e => { e.preventDefault(); setDragOver(true); }}
              onDragLeave={() => setDragOver(false)}
              onDrop={e => { e.preventDefault(); setDragOver(false); handleFakeUpload(); }}
              style={{
                padding: '36px 24px',
                background: dragOver ? 'var(--accent-bg)' : 'var(--surface)',
                border: '2px dashed',
                borderColor: dragOver ? 'var(--accent)' : 'var(--border-strong)',
                borderRadius: 'var(--radius-md)',
                textAlign: 'center',
                transition: 'background 120ms, border-color 120ms',
                cursor: 'default',
              }}>
              <div style={{
                width: 44, height: 44, margin: '0 auto 12px',
                borderRadius: 10, background: 'var(--accent-bg)',
                display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                color: 'var(--accent)',
              }}>
                <I.Upload size={20} />
              </div>
              <div style={{ fontSize: 15, fontWeight: 600, color: 'var(--text)',
                marginBottom: 4 }}>
                Drop files or folders here
              </div>
              <div style={{ fontSize: 12, color: 'var(--text-muted)', marginBottom: 14 }}>
                DOCX · PDF · MP4 · MOV · MP3 · WAV — up to 500 MB each
              </div>
              <div style={{ display: 'inline-flex', gap: 8 }}>
                <button className="btn sm" onClick={handleFakeUpload}>Browse files</button>
                <button className="btn sm" onClick={handleFakeUpload}>Browse folder</button>
              </div>
            </div>

            {/* File list */}
            {files.length > 0 && (
              <div style={{
                background: 'var(--surface)', border: '1px solid var(--border)',
                borderRadius: 'var(--radius-md)', overflow: 'hidden',
              }}>
                <div style={{
                  display: 'flex', alignItems: 'center', gap: 8,
                  padding: '12px 16px', borderBottom: '1px solid var(--border)',
                }}>
                  <h3 style={{ margin: 0, fontSize: 13, fontWeight: 600 }}>
                    Uploaded ({files.length})
                  </h3>
                  <div style={{ flex: 1 }} />
                  <span style={{ fontSize: 11.5, color: 'var(--text-faint)',
                    fontFamily: 'var(--font-mono)' }}>{totalBytes} total</span>
                </div>
                <div>
                  {files.map((f, i) => (
                    <UploadedFileRow key={f.id} file={f}
                      last={i === files.length - 1}
                      onRemove={() => handleRemove(f.id)} />
                  ))}
                </div>
              </div>
            )}
          </div>

          {/* ── Right: pipeline card + generate ─────────────────────── */}
          <NCPipelineCard
            files={files}
            canGenerate={canGenerate}
            onGenerate={() => onGenerate({ name, topic, files })} />
        </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>
  );
}

// ── File row ───────────────────────────────────────────────────────────────
function UploadedFileRow({ file, last, onRemove }) {
  const KindIcon = { doc: I.FileText, video: I.Film, audio: I.Mic }[file.kind] || I.FileText;
  const kindTint = { doc: '#2563eb', video: '#dc2626', audio: '#9333ea' }[file.kind] || 'var(--text-muted)';
  return (
    <div style={{
      display: 'grid', gridTemplateColumns: '32px 1fr 80px 60px 28px',
      gap: 12, alignItems: 'center',
      padding: '10px 16px',
      borderBottom: last ? 0 : '1px solid var(--border-faint)',
    }}>
      <span style={{
        width: 28, height: 28, borderRadius: 6,
        background: 'color-mix(in oklab, ' + kindTint + ' 12%, transparent)',
        color: kindTint,
        display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
      }}><KindIcon size={14} /></span>
      <div style={{ minWidth: 0 }}>
        <div className="truncate" style={{ fontSize: 13, fontWeight: 500, color: 'var(--text)' }}>
          {file.name}
        </div>
        <div style={{ fontSize: 11, color: 'var(--text-muted)' }}>
          {file.size} · ready for analysis
        </div>
      </div>
      <span style={{ fontSize: 11, color: 'var(--text-faint)',
        fontFamily: 'var(--font-mono)', textAlign: 'right' }}>{file.size}</span>
      <span className="pill accepted" style={{ fontSize: 10.5, justifySelf: 'center' }}>
        <I.Check size={10} />ok
      </span>
      <button className="btn sm ghost" onClick={onRemove} title="Remove"
        style={{ width: 28, height: 28, padding: 0, justifyContent: 'center' }}>
        <I.X size={13} />
      </button>
    </div>
  );
}

// ── AI pipeline side card ──────────────────────────────────────────────────
function NCPipelineCard({ files, canGenerate, onGenerate }) {
  const estSeconds = Math.max(45, Math.min(180, files.length * 18 + 30));
  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 }}>AI pipeline</div>
          <div style={{ fontSize: 11, color: 'var(--text-muted)' }}>
            What happens after you click Generate
          </div>
        </div>
      </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' }} />

      <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
        <I.Clock size={12} style={{ color: 'var(--text-faint)' }} />
        <span style={{ fontSize: 11.5, color: 'var(--text-muted)' }}>
          Estimated time: <strong style={{ color: 'var(--text)' }}>~{estSeconds}s</strong>
        </span>
      </div>

      <button className="btn primary" onClick={onGenerate} disabled={!canGenerate}
        style={{ width: '100%', height: 40, fontSize: 13, fontWeight: 600,
          opacity: canGenerate ? 1 : 0.5 }}>
        <I.Sparkle size={13} />Generate course structure
      </button>

      <div style={{ fontSize: 11, color: 'var(--text-faint)', lineHeight: 1.5 }}>
        <I.Info size={11} /> Generation produces module organisation and layout placement.
        Images and videos are produced later, per-layout, from Course architecture.
      </div>
    </aside>
  );
}

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