// Public sample videos (CC, widely-used for CDN testing)
const SAMPLE_VIDEOS = [
  '/assets/video/oceans.mp4',
  '/assets/video/mov_bbb.mp4',
  '/assets/video/sample-5s.mp4',
  '/assets/video/bbb-360-10s.mp4',
  '/assets/video/oceans.mp4',
  '/assets/video/mov_bbb.mp4',
];

// Lecture / video player page
function LecturePage({ go, params }) {
  const c = COURSES.find(x => x.id === params.id) || COURSES[0];
  const [activeId, setActiveId] = React.useState(params.lec || 'L1');
  const [note, setNote] = React.useState('');
  const [notes, setNotes] = React.useState([]);
  const [noteBusy, setNoteBusy] = React.useState(false);
  const [lectures, setLectures] = React.useState([]);

  React.useEffect(() => {
    if (!c) return;
    let cancelled = false;
    Promise.all([
      window.api.lectures(c.id),
      window.api.progress(c.id).catch(() => []),
    ]).then(([rows, progress]) => {
      if (cancelled) return;
      const progMap = Object.fromEntries(progress.map(p => [p.lecture, !!p.done]));
      const merged = rows.map(r => ({ ...window.normalizeLecture(r), done: progMap[r.lid] ?? false }));
      setLectures(merged);
      if (!params.lec && merged.length) setActiveId(merged[0].id);
    });
    return () => { cancelled = true; };
  }, [c?.id]);

  const active = lectures.find(l => l.id === activeId) || lectures[0] || { id: '', name: '', wk: 0, dur: '', kind: 'video' };
  const videoUrl = SAMPLE_VIDEOS[Math.max(0, lectures.findIndex(l => l.id === active.id)) % SAMPLE_VIDEOS.length];

  React.useEffect(() => {
    if (!c || !active.id) { setNotes([]); return; }
    let cancelled = false;
    window.api.notes(c.id, active.id).then(rows => {
      if (!cancelled) setNotes(rows);
    }).catch(() => setNotes([]));
    return () => { cancelled = true; };
  }, [c && c.id, active.id]);

  async function markDone() {
    if (!active.id) return;
    try {
      await window.api.setProgress(c.id, active.id, !active.done);
      setLectures(ls => ls.map(l => l.id === active.id ? { ...l, done: !l.done } : l));
    } catch (err) {
      if (err.status === 401) go('login');
    }
  }

  async function addNote(e){
    e.preventDefault();
    if (!note.trim() || !active.id) return;
    const ts = new Date().toLocaleTimeString('th-TH', { hour: '2-digit', minute: '2-digit' });
    setNoteBusy(true);
    try {
      const saved = await window.api.addNote(c.id, active.id, ts, note.trim());
      setNotes(n => [...n, saved]);
      setNote('');
    } catch (err) {
      if (err.status === 401) go('login');
    } finally {
      setNoteBusy(false);
    }
  }

  return (
    <div style={{background:'#0a0d18', color:'var(--bg)', minHeight:'calc(100vh - 88px)'}}>
      <div className="wrap" style={{padding:'20px 32px'}}>
        <div className="row" style={{gap:14, marginBottom:14, color:'rgba(245,239,226,.7)', fontSize:13}}>
          <button className="btn link" style={{color:'var(--accent)', borderColor:'transparent'}} onClick={()=>go('course',{id:c.id})}>
            <Ic.arrowL size={14}/> กลับสู่หน้ารายวิชา
          </button>
          <span style={{color:'rgba(245,239,226,.3)'}}>·</span>
          <span className="mono">{c.code}</span>
          <span style={{color:'rgba(245,239,226,.3)'}}>·</span>
          <span>{c.name}</span>
        </div>

        <div style={{display:'grid', gridTemplateColumns:'1fr 360px', gap:24, alignItems:'flex-start'}}>
          {/* Video + content */}
          <div>
            {/* Player */}
            <div style={{position:'relative', background:'#000', borderRadius:'var(--r-lg)', overflow:'hidden', aspectRatio:'16/9'}}>
              <video
                key={active.id}
                src={videoUrl}
                poster={`/assets/img/picsum/lecture-${active.id}_1280x720.jpg`}
                controls
                playsInline
                preload="metadata"
                data-test="HLS / MP4 · cacheable media"
                style={{width:'100%', height:'100%', display:'block', background:'#000'}}/>
              <div style={{position:'absolute', top:14, right:14, display:'flex', gap:6, alignItems:'center', background:'rgba(0,0,0,.6)', backdropFilter:'blur(8px)', padding:'5px 10px', borderRadius:99, fontSize:11, color:'rgba(255,255,255,.85)', fontFamily:'JetBrains Mono, monospace', pointerEvents:'none'}}>
                <span style={{width:6, height:6, borderRadius:99, background:'var(--ok)'}}/>
                TCP_HIT · edge BKK-3
              </div>
            </div>
            <div className="row" style={{marginTop:8, gap:14, fontSize:11.5, color:'rgba(245,239,226,.4)', fontFamily:'JetBrains Mono, monospace', flexWrap:'wrap'}}>
              <span>video/mp4 · {active.dur}</span>
              <span>·</span>
              <span>cache-control: public, max-age=604800</span>
              <span>·</span>
              <span style={{wordBreak:'break-all'}}>{videoUrl.replace('https://','').slice(0,60)}…</span>
            </div>

            {/* Below video */}
            <div className="row" style={{justifyContent:'space-between', marginTop:24, flexWrap:'wrap', gap:14}}>
              <div>
                <div style={{fontSize:12, color:'rgba(245,239,226,.5)', letterSpacing:'.08em'}}>สัปดาห์ที่ {active.wk} · บทเรียนที่ {active.id}</div>
                <h1 className="serif" style={{margin:'6px 0 0', fontSize:28, fontWeight:600, color:'var(--paper)'}}>{active.name}</h1>
              </div>
              <div className="row" style={{gap:8}}>
                <button className="btn alt sm" onClick={markDone} style={{background:active.done?'rgba(58,115,80,.25)':'rgba(255,255,255,.06)', borderColor: active.done?'var(--ok)':'rgba(255,255,255,.2)', color:'var(--paper)'}}>
                  <Ic.check size={14}/> {active.done ? 'เรียนแล้ว' : 'ทำเครื่องหมายว่าเรียนแล้ว'}
                </button>
                <button className="btn alt sm" style={{background:'rgba(255,255,255,.06)', borderColor:'rgba(255,255,255,.2)', color:'var(--paper)'}}><Ic.download size={14}/> ดาวน์โหลด</button>
                <button className="btn acc sm">บทถัดไป <Ic.arrow size={14}/></button>
              </div>
            </div>

            {/* Tabs */}
            <div style={{display:'flex', borderBottom:'1px solid rgba(255,255,255,.1)', marginTop:24}}>
              {['คำบรรยาย', 'เอกสารประกอบ', 'จดบันทึก', 'ถามอาจารย์'].map((l,i) => (
                <button key={l} style={{appearance:'none', border:0, background:'transparent',
                  padding:'12px 16px', fontSize:13.5, color: i===2?'var(--paper)':'rgba(245,239,226,.5)',
                  cursor:'default', borderBottom: '2px solid '+(i===2?'var(--accent)':'transparent'),
                  marginBottom:-1, fontWeight: i===2?600:400}}>{l}</button>
              ))}
            </div>

            {/* Notes */}
            <div style={{padding:'24px 0'}}>
              <form className="panel" style={{padding:16, marginBottom:20, background:'rgba(255,255,255,.04)', borderColor:'rgba(255,255,255,.1)'}} onSubmit={addNote}>
                <div className="row" style={{gap:10}}>
                  <input
                    value={note} onChange={e=>setNote(e.target.value)}
                    placeholder="พิมพ์บันทึกของคุณสำหรับบทเรียนนี้…"
                    style={{flex:1, background:'transparent', border:0, color:'var(--paper)', outline:0, fontSize:14, padding:'4px 0'}}/>
                  <button className="btn acc sm" type="submit" disabled={noteBusy}>{noteBusy ? '…' : 'เพิ่ม'}</button>
                </div>
              </form>
              {notes.length === 0 && (
                <p style={{color:'rgba(245,239,226,.4)', fontSize:13.5, padding:'4px 0'}}>ยังไม่มีบันทึกสำหรับบทเรียนนี้ · บันทึกของคุณเป็นแบบส่วนตัว</p>
              )}
              {notes.map(n => (
                <div key={n._id} className="row" style={{gap:14, padding:'14px 0', borderBottom:'1px solid rgba(255,255,255,.08)', alignItems:'flex-start'}}>
                  <button className="mono" style={{background:'rgba(184,133,50,.2)', color:'var(--accent)', padding:'4px 10px', borderRadius:3, fontSize:12, border:'1px solid rgba(184,133,50,.4)', flexShrink:0, marginTop:2, cursor:'default'}}>{n.ts || '—'}</button>
                  <p style={{margin:0, color:'rgba(245,239,226,.85)', fontSize:14.5, lineHeight:1.7, flex:1, whiteSpace:'pre-wrap'}}>{n.body}</p>
                </div>
              ))}
            </div>
          </div>

          {/* Sidebar — lecture list */}
          <aside style={{position:'sticky', top:120, background:'rgba(255,255,255,.03)', border:'1px solid rgba(255,255,255,.08)', borderRadius:'var(--r-lg)', maxHeight:'calc(100vh - 140px)', overflow:'hidden', display:'flex', flexDirection:'column'}}>
            <div style={{padding:'18px 20px 14px', borderBottom:'1px solid rgba(255,255,255,.08)'}}>
              <h3 className="serif" style={{margin:0, fontSize:18, fontWeight:600, color:'var(--paper)'}}>เนื้อหารายวิชา</h3>
              <div style={{display:'flex', justifyContent:'space-between', marginTop:8, fontSize:12, color:'rgba(245,239,226,.5)'}}>
                <span>คืบหน้า {Math.round(lectures.filter(l=>l.done).length/lectures.length*100)}%</span>
                <span>{lectures.filter(l=>l.done).length} / {lectures.length} บทเรียน</span>
              </div>
              <div style={{height:4, background:'rgba(255,255,255,.1)', borderRadius:99, overflow:'hidden', marginTop:8}}>
                <div style={{width: (lectures.filter(l=>l.done).length/lectures.length*100)+'%', height:'100%', background:'var(--accent)'}}/>
              </div>
            </div>
            <div style={{overflow:'auto', flex:1, padding:'4px 8px'}}>
              {lectures.map(l => {
                const isActive = l.id === activeId;
                return (
                  <button key={l.id} onClick={()=>setActiveId(l.id)}
                    style={{
                      width:'100%', textAlign:'left', appearance:'none', cursor:'default',
                      display:'grid', gridTemplateColumns:'24px 1fr', gap:10,
                      padding:'10px 12px', borderRadius:'var(--r)', border:0,
                      background: isActive?'rgba(184,133,50,.12)':'transparent',
                      color: isActive?'var(--paper)':'rgba(245,239,226,.7)',
                      marginBottom:2
                    }}>
                    <span style={{width:24, height:24, borderRadius:99, display:'grid', placeItems:'center',
                      background: l.done?'var(--ok)':'rgba(255,255,255,.08)',
                      color: l.done?'#fff':'rgba(245,239,226,.5)',
                      marginTop:1}}>
                      {l.done ? <Ic.check size={12}/> : l.kind==='video' ? <Ic.play size={10}/> : l.kind==='quiz' ? <Ic.doc size={10}/> : l.kind==='assn' ? <Ic.bookmk size={10}/> : <Ic.book size={10}/>}
                    </span>
                    <div style={{minWidth:0}}>
                      <div style={{fontSize:13, fontWeight: isActive?600:400, lineHeight:1.4, color: isActive?'var(--paper)':'inherit'}}>{l.name}</div>
                      <div className="mono" style={{fontSize:10.5, color:'rgba(245,239,226,.4)', marginTop:3}}>สัปดาห์ {l.wk} · {l.dur}</div>
                    </div>
                  </button>
                );
              })}
            </div>
          </aside>
        </div>
      </div>
    </div>
  );
}
window.LecturePage = LecturePage;
