// Localisation helpers — video collection, sample cues, and the reusable
// cue-list editor. The standalone Subtitles surface was folded into the
// Localisation hub (see surface-localisation.jsx); these pieces are shared by
// its Subtitles panel rather than duplicated.

// ── Helpers ────────────────────────────────────────────────────────────────

// Build a list of every video referenced in the course. Sources:
//   • fullscreen_video / small_video layouts (one video each)
//   • sequence / horizontal_tabs tabs of kind='video'
//   • text_and_image rows with a videoUrl
// Each entry: { id, label, moduleId, layoutId, type, duration, source }
function collectCourseVideos(course) {
  const out = [];
  (course?.modules || []).forEach(m => {
    (m.layouts || []).forEach(l => {
      const base = { moduleId: m.id, layoutId: l.id, type: l.type,
        summary: l.summary };
      if (l.type === 'fullscreen_video' || l.type === 'small_video') {
        out.push({ ...base, id: l.id,
          label: `${m.id}.L${l.n} · ${l.type}`,
          subLabel: locText(l.summary),
          duration: l.type === 'fullscreen_video' ? '04:32' : '02:14',
        });
      }
      // For sequence/horizontal_tabs, surface each video tab as its own item.
      const content = (window.LAYOUT_CONTENT_SAMPLES || {})[l.type] || {};
      const tabs = (l.tabs || content.tabs || []);
      tabs.forEach((t, i) => {
        if (t.kind === 'video') {
          out.push({
            ...base,
            id: `${l.id}-t${i + 1}`,
            label: `${m.id}.L${l.n} · tab ${i + 1}`,
            subLabel: locText(t.tabTitle) || locText(t.mobileText) || 'Video tab',
            duration: '01:24',
          });
        }
      });
      const rows = l.rows || content.rows || [];
      rows.forEach((r, i) => {
        if (r.videoUrl) {
          out.push({
            ...base,
            id: `${l.id}-r${i + 1}`,
            label: `${m.id}.L${l.n} · row ${i + 1}`,
            subLabel: 'Inline video',
            duration: '00:45',
          });
        }
      });
    });
  });
  return out;
}

// Sample English transcript for the prototype. In production this is the
// output of the speech-to-text pass on the source video, authored upstream.
const SAMPLE_CUES_BY_VIDEO = {
  default: [
    { n: 1,  start: '00:00:00.160', end: '00:00:05.839',
      text: "Dear colleagues, it's a privilege to address you as part of this year's Code of Conduct training." },
    { n: 2,  start: '00:00:06.080', end: '00:00:08.240',
      text: 'As your Chief People and Culture Officer,' },
    { n: 3,  start: '00:00:08.320', end: '00:00:12.640',
      text: 'I want to take a moment to remind us all why these conversations matter.' },
    { n: 4,  start: '00:00:13.000', end: '00:00:17.500',
      text: 'Our reputation is built one decision at a time — most of them small, and most of them under pressure.' },
    { n: 5,  start: '00:00:17.840', end: '00:00:22.100',
      text: 'The choices you make in those moments are the company.' },
    { n: 6,  start: '00:00:22.400', end: '00:00:27.150',
      text: 'When you slow down to ask whether something feels right, you protect everyone around you.' },
    { n: 7,  start: '00:00:27.520', end: '00:00:32.840',
      text: "And when you raise something that doesn't feel right, you give us the chance to fix it." },
    { n: 8,  start: '00:00:33.120', end: '00:00:37.560',
      text: "That's the muscle we're strengthening together this year." },
    { n: 9,  start: '00:00:37.880', end: '00:00:41.300',
      text: 'Thank you for the care you bring to your work.' },
    { n: 10, start: '00:00:41.640', end: '00:00:44.000',
      text: "Let's begin." },
  ],
};

// Sample target-language cue text, keyed by langCode then cue number. Where a
// language/cue has no entry, the panel shows an empty (needs-translation) cell.
const SAMPLE_CUE_TRANSLATIONS = {
  it: {
    1: "Cari colleghi, è un privilegio rivolgermi a voi nell'ambito della formazione sul Codice di Condotta di quest'anno.",
    2: 'In qualità di vostro Chief People and Culture Officer,',
    3: 'vorrei ricordare a tutti noi perché queste conversazioni sono importanti.',
  },
  de: {
    1: 'Liebe Kolleginnen und Kollegen, es ist mir eine Ehre, im Rahmen der diesjährigen Verhaltenskodex-Schulung zu Ihnen zu sprechen.',
    2: 'Als Ihr Chief People and Culture Officer',
  },
};

// ── Reusable cue editor ──────────────────────────────────────────────────────
// Read-only when `readOnly` (English source view). Editable cells call onEdit.
function CueRow({ cue, last, readOnly, onEdit }) {
  const [editing, setEditing] = React.useState(false);
  const [draft, setDraft] = React.useState(cue.text);
  React.useEffect(() => { setDraft(cue.text); }, [cue.text]);

  const commit = () => {
    setEditing(false);
    if (draft !== cue.text) onEdit?.({ text: draft });
  };

  return (
    <div style={{
      display: 'grid',
      gridTemplateColumns: '44px 132px 1fr auto',
      gap: 12, alignItems: 'flex-start',
      padding: '11px 14px',
      borderBottom: last ? 0 : '1px solid var(--border)',
      background: editing ? 'var(--surface-2)' : 'transparent',
    }}>
      <span style={{
        fontFamily: 'var(--font-mono)', fontSize: 11, fontWeight: 600,
        color: 'var(--text-faint)',
        background: 'var(--surface-inset)', padding: '2px 6px',
        borderRadius: 3, textAlign: 'center', minWidth: 28,
        display: 'inline-block',
      }}>
        {String(cue.n).padStart(2, '0')}
      </span>
      <span style={{
        fontFamily: 'var(--font-mono)', fontSize: 11,
        color: 'var(--text-muted)', lineHeight: 1.5, whiteSpace: 'nowrap',
      }}>
        {cue.start}<br />
        <span style={{ color: 'var(--text-faint)' }}>→ {cue.end}</span>
      </span>
      <div style={{ minWidth: 0 }}>
        {editing && !readOnly ? (
          <textarea autoFocus value={draft}
            onChange={e => setDraft(e.target.value)}
            onBlur={commit}
            onKeyDown={e => {
              if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) commit();
              if (e.key === 'Escape') { setDraft(cue.text); setEditing(false); }
            }}
            className="field"
            style={{ width: '100%', minHeight: 48, fontSize: 13,
              lineHeight: 1.5, fontFamily: 'inherit', padding: '6px 8px' }} />
        ) : (
          <p onDoubleClick={() => { if (!readOnly) setEditing(true); }}
            style={{ margin: 0, fontSize: 13, lineHeight: 1.55,
              color: cue.text ? 'var(--text)' : 'var(--text-faint)',
              fontStyle: cue.text ? 'normal' : 'italic' }}>
            {cue.text || 'Not translated yet'}
          </p>
        )}
      </div>
      <div style={{ display: 'inline-flex', gap: 4 }}>
        {!readOnly && !editing && (
          <button className="btn sm ghost" title="Edit this cue"
            onClick={() => setEditing(true)}
            style={{ width: 26, height: 26, padding: 0 }}>
            <I.PenLine size={11} />
          </button>
        )}
        {!readOnly && editing && (
          <>
            <button className="btn sm" title="Save (⌘↵)" onClick={commit}
              style={{ height: 26 }}>
              <I.Check size={11} />Save
            </button>
            <button className="btn sm ghost" title="Cancel (Esc)"
              onClick={() => { setDraft(cue.text); setEditing(false); }}
              style={{ width: 26, height: 26, padding: 0 }}>
              <I.X size={11} />
            </button>
          </>
        )}
      </div>
    </div>
  );
}

function CueList({ cues, readOnly, onEdit }) {
  return (
    <div style={{
      border: '1px solid var(--border)', borderRadius: 'var(--radius-md)',
      background: 'var(--surface)', overflow: 'hidden',
    }}>
      {cues.map((c, i) => (
        <CueRow key={c.n} cue={c} last={i === cues.length - 1}
          readOnly={readOnly} onEdit={patch => onEdit?.(i, patch)} />
      ))}
    </div>
  );
}

Object.assign(window, {
  collectCourseVideos, SAMPLE_CUES_BY_VIDEO, SAMPLE_CUE_TRANSLATIONS,
  CueRow, CueList,
});
