// Video lesson: player, transcript/notes tabs, up-next, ask-a-question.
(function () {
  const NS = window.MineSafeGlobalDesignSystem_760fd2;
  const { Card, IconButton, Button, Icon, ProgressBar, Badge, Input, ModuleListItem } = NS;

  function Player({ poster, src }) {
    const ref = React.useRef(null);
    const [playing, setPlaying] = React.useState(false);
    const [pct, setPct] = React.useState(0);
    const [cur, setCur] = React.useState('00:00');
    const [dur, setDur] = React.useState('00:00');
    const fmt = (s) => `${String(Math.floor(s / 60)).padStart(2, '0')}:${String(Math.floor(s % 60)).padStart(2, '0')}`;
    const toggle = () => { const v = ref.current; if (!v) return; if (v.paused) { v.play(); setPlaying(true); } else { v.pause(); setPlaying(false); } };
    const onTime = () => { const v = ref.current; if (!v || !v.duration) return; setPct(v.currentTime / v.duration * 100); setCur(fmt(v.currentTime)); setDur(fmt(v.duration)); };
    const seek = (e) => { const v = ref.current; if (!v || !v.duration) return; const r = e.currentTarget.getBoundingClientRect(); v.currentTime = ((e.clientX - r.left) / r.width) * v.duration; };
    return (
      <div style={{ position: 'relative', aspectRatio: '16 / 9', borderRadius: 'var(--radius-lg)', overflow: 'hidden', background: 'var(--brand-black)' }}>
        <video ref={ref} src={src} poster={poster} playsInline preload="metadata"
          onTimeUpdate={onTime} onLoadedMetadata={onTime} onEnded={() => setPlaying(false)} onClick={toggle}
          style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover', cursor: 'pointer' }} />
        {!playing && <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(180deg,rgba(0,0,0,0.15),rgba(0,0,0,0.45))', pointerEvents: 'none' }} />}
        {!playing && <button onClick={toggle} style={{
          position: 'absolute', top: '50%', left: '50%', transform: 'translate(-50%,-50%)',
          width: 74, height: 74, borderRadius: '50%', background: 'var(--brand-yellow)', border: 'none',
          cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', boxShadow: 'var(--shadow-lg)',
        }}><Icon name="play" size={30} color="var(--brand-ink)" /></button>}
        <div style={{ position: 'absolute', left: 0, right: 0, bottom: 0, padding: '20px 16px 12px', background: 'linear-gradient(transparent,rgba(0,0,0,0.75))' }}>
          <div onClick={seek} style={{ height: 4, background: 'rgba(255,255,255,0.25)', borderRadius: 999, overflow: 'hidden', cursor: 'pointer' }}>
            <div style={{ width: `${pct}%`, height: '100%', background: 'var(--brand-yellow)' }} />
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginTop: 10, color: '#fff' }}>
            <IconButton icon={playing ? 'pause' : 'play'} variant="solid" size="sm" label="Play/Pause" onClick={toggle} />
            <IconButton icon="rotate-ccw" variant="ghost" size="sm" label="Back 10s" style={{ color: '#fff' }} onClick={() => { if (ref.current) ref.current.currentTime = Math.max(0, ref.current.currentTime - 10); }} />
            <span style={{ fontFamily: 'var(--font-mono)', fontSize: 12 }}>{cur} / {dur}</span>
            <div style={{ flex: 1 }} />
            <IconButton icon="volume-2" variant="ghost" size="sm" label="Volume" style={{ color: '#fff' }} />
            <IconButton icon="captions" variant="ghost" size="sm" label="Captions" style={{ color: '#fff' }} />
            <IconButton icon="maximize" variant="ghost" size="sm" label="Fullscreen" style={{ color: '#fff' }} onClick={() => ref.current && ref.current.requestFullscreen && ref.current.requestFullscreen()} />
          </div>
        </div>
      </div>
    );
  }

  function VideoLesson({ course, onBack, onNext }) {
    const [tab, setTab] = React.useState('transcript');
    const tabs = [['transcript', 'Transcript'], ['notes', 'Notes'], ['resources', 'Resources']];
    return (
      <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
        <button onClick={onBack} style={{ display: 'inline-flex', alignItems: 'center', gap: 6, border: 'none', background: 'none', cursor: 'pointer', color: 'var(--text-muted)', fontSize: 14, alignSelf: 'flex-start', fontFamily: 'var(--font-body)' }}>
          <Icon name="arrow-left" size={17} />{course.title}
        </button>

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 320px', gap: 20, alignItems: 'start' }}>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
            <Player poster={course.cover} src={window.MSA_DATA.sampleVideo} />
            <div>
              <span className="ms-overline">Module 1 · Video</span>
              <h2 style={{ marginTop: 6 }}>What Level 9 intervention does</h2>
              <div style={{ display: 'flex', gap: 14, marginTop: 8, color: 'var(--text-muted)', fontSize: 13.5 }}>
                <span style={{ display: 'inline-flex', gap: 6, alignItems: 'center' }}><Icon name="clock" size={15} />08:12</span>
                <span style={{ display: 'inline-flex', gap: 6, alignItems: 'center' }}><Icon name="users" size={15} />1,240 operators</span>
              </div>
            </div>

            <div style={{ display: 'flex', gap: 4, borderBottom: '1px solid var(--border-subtle)' }}>
              {tabs.map(([id, label]) => (
                <button key={id} onClick={() => setTab(id)} style={{
                  padding: '10px 16px', border: 'none', background: 'none', cursor: 'pointer',
                  fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 13.5, textTransform: 'uppercase', letterSpacing: 'var(--ls-label)',
                  color: tab === id ? 'var(--text-strong)' : 'var(--text-muted)',
                  borderBottom: `2px solid ${tab === id ? 'var(--brand-yellow)' : 'transparent'}`, marginBottom: -1,
                }}>{label}</button>
              ))}
            </div>
            <Card>
              {tab === 'transcript' && <p style={{ fontSize: 14.5, lineHeight: 1.65, color: 'var(--text-body)' }}>The Level 9 CxD continuously scans for pedestrians and machines within its detection field. When a hazard enters the warning zone, the operator is alerted. If no action is taken and the object enters the intervention zone, the system automatically applies a controlled stop — protecting the operator, pedestrians, and the machine. In this module we walk through each zone and what the operator should do at every stage.</p>}
              {tab === 'notes' && <p style={{ fontSize: 14.5, color: 'var(--text-muted)' }}>Your notes for this lesson appear here. Add timestamps and reminders as you watch.</p>}
              {tab === 'resources' && <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                <a href="#" onClick={e => e.preventDefault()} style={{ display: 'inline-flex', gap: 8, alignItems: 'center' }}><Icon name="file-down" size={16} />CxD Level 9 datasheet (PDF)</a>
                <a href="#" onClick={e => e.preventDefault()} style={{ display: 'inline-flex', gap: 8, alignItems: 'center' }}><Icon name="file-down" size={16} />Detection-zone quick reference (PDF)</a>
              </div>}
            </Card>

            <Card style={{ display: 'flex', gap: 14, alignItems: 'center' }}>
              <span style={{ width: 40, height: 40, flex: '0 0 auto', borderRadius: 'var(--radius-md)', background: 'var(--info-surface)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                <Icon name="messages-square" size={20} color="var(--info)" />
              </span>
              <div style={{ flex: 1 }}>
                <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, color: 'var(--text-strong)' }}>Have a question?</div>
                <div style={{ fontSize: 13.5, color: 'var(--text-muted)' }}>Ask a Mine Safe trainer — answered within one working day.</div>
              </div>
              <Button variant="outline" iconLeft="plus">Ask</Button>
            </Card>
          </div>

          <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
            <Card padding="16px">
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 10 }}>
                <h4>Up next</h4><Badge tone="caution">4 left</Badge>
              </div>
              <ProgressBar value={course.progress} size="sm" />
            </Card>
            <Card padding="0" style={{ overflow: 'hidden' }}>
              {(course.modules || []).slice(0, 5).map((m, i) => (
                <ModuleListItem key={i} index={i + 1} title={m.title} type={m.type} duration={m.duration}
                  status={m.status} active={i === 0} onClick={m.status === 'locked' ? undefined : () => {}} />
              ))}
            </Card>
            <Button variant="primary" fullWidth iconRight="arrow-right" onClick={onNext}>Next: Pre-start checklist</Button>
          </div>
        </div>
      </div>
    );
  }

  Object.assign(window, { VideoLesson });
})();
