// Lumen — Course player (video + transcript + notes)
function CoursePlayer({ courseId, onBack, onOpenQuiz }) {
  const D = window.LUMEN_DATA;
  const course = D.COURSES.find(c => c.id === courseId) || D.COURSES[0];
  const [activeLessonId, setActiveLessonId] = React.useState("l7");
  const [playing, setPlaying] = React.useState(false);
  const [pos, setPos] = React.useState(() => parseFloat(localStorage.getItem("lumen_player_pos")) || 0.18);
  const [tab, setTab] = React.useState("transcript");
  const [note, setNote] = React.useState("");
  const [notes, setNotes] = React.useState([
    { t: "02:14", text: "Mara: positioning > production quality. Worth re-watching." },
    { t: "08:42", text: "TODO: write down my own niche statement using the framework." },
  ]);
  const [speed, setSpeed] = React.useState(1);
  const heatmap = React.useMemo(() => D.genWatchHeat(160), []);

  // simulate playback
  React.useEffect(() => {
    if (!playing) return;
    const id = setInterval(() => setPos(p => Math.min(1, p + 0.0015 * speed)), 100);
    return () => clearInterval(id);
  }, [playing, speed]);
  React.useEffect(() => {
    localStorage.setItem("lumen_player_pos", pos);
  }, [pos]);

  const lesson = course.modules?.flatMap(m => m.lessons).find(l => l.id === activeLessonId) || { title: "Office hours #1 (replay)", duration: "58:21", type: "video" };
  const totalSec = 58 * 60 + 21;
  const curSec = Math.floor(totalSec * pos);
  const fmt = (s) => `${Math.floor(s/60).toString().padStart(2,"0")}:${(s%60).toString().padStart(2,"0")}`;

  const transcript = [
    { t: 0, text: "Welcome back everyone. Today's office hours we're going to talk about positioning — but specifically about why most positioning advice fails creators." },
    { t: 22, text: "I want to start with a story from one of our students, Marcus, who came in last cohort with a course called \"Better writing for everyone\"." },
    { t: 58, text: "If your positioning could plausibly fit on a banner ad in 2008, it's not positioning. It's a category." },
    { t: 134, text: "Here's the framework I want you to memorize: specific buyer + specific outcome + specific time-frame. Three constraints. Each one cuts your TAM and triples your conversion." },
    { t: 215, text: "Question from chat: \"What if my niche feels too small?\" That's the right feeling. If it doesn't feel uncomfortably small, you haven't niched enough." },
    { t: 312, text: "I want to do a live exercise. In your workbook, write your current positioning statement. Now strike out every word that could apply to a competitor." },
    { t: 421, text: "Sara, do you want to share yours? Great. \"I help writers find their voice.\" Okay — every writing course on earth says that. Let's tear it down." },
  ];

  const currentLine = transcript.findLastIndex(l => l.t <= curSec);

  return (
    <div className="page" style={{ background: "var(--bg)" }}>
      {/* Player topbar */}
      <div style={{ display: "flex", alignItems: "center", padding: "12px 24px", borderBottom: "1px solid var(--border)", gap: 16 }}>
        <button className="btn btn--ghost btn--sm" onClick={onBack}>← My courses</button>
        <div style={{ width: 1, height: 20, background: "var(--border)" }}/>
        <div>
          <div style={{ fontSize: 13, fontWeight: 500 }}>{course.title}</div>
          <div className="muted" style={{ fontSize: 11 }}>Module 2 · Audience & positioning · Lesson 4</div>
        </div>
        <div className="spacer"/>
        <div className="row" style={{ fontSize: 12, color: "var(--ink-3)" }}>
          <I.bookmark size={14}/> Saved
        </div>
        <button className="btn btn--secondary btn--sm">Next lesson <I.arrowRight size={12}/></button>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1fr 360px", height: "calc(100vh - 56px)" }}>
        {/* Player area */}
        <div style={{ overflowY: "auto", borderRight: "1px solid var(--border)" }}>
          <div style={{ padding: 24 }}>
            {/* Video */}
            <div style={{
              background: "var(--ink)",
              borderRadius: "var(--r-lg)",
              aspectRatio: "16/9",
              position: "relative",
              overflow: "hidden",
              cursor: "pointer",
            }} onClick={() => setPlaying(!playing)}>
              {/* Fake video: gradient + speaker mock */}
              <div style={{ position: "absolute", inset: 0, background: "radial-gradient(ellipse at 30% 50%, #44403C 0%, #0A0A0A 70%)" }}/>
              <div style={{ position: "absolute", left: "20%", top: "50%", transform: "translateY(-50%)", width: 140, height: 140, borderRadius: "50%", background: "linear-gradient(135deg, #FF5C28, #B91C1C)", display: "flex", alignItems: "center", justifyContent: "center", color: "white", fontSize: 56, fontWeight: 600, fontFamily: "var(--font-display)", letterSpacing: "-0.02em" }}>MK</div>
              <div style={{ position: "absolute", right: 24, bottom: 24, padding: "8px 14px", background: "rgba(0,0,0,.6)", borderRadius: 6, color: "white", fontSize: 12, backdropFilter: "blur(8px)" }}>
                <div className="row"><span className="live-dot"></span> Mara Klein speaking</div>
              </div>
              {!playing && (
                <div style={{ position: "absolute", inset: 0, display: "flex", alignItems: "center", justifyContent: "center" }}>
                  <div style={{ width: 80, height: 80, borderRadius: "50%", background: "rgba(255,255,255,.95)", color: "var(--ink)", display: "flex", alignItems: "center", justifyContent: "center" }}>
                    <I.play size={32}/>
                  </div>
                </div>
              )}
              {/* Captions */}
              {playing && currentLine >= 0 && (
                <div style={{ position: "absolute", left: "50%", bottom: 80, transform: "translateX(-50%)", padding: "8px 16px", background: "rgba(0,0,0,.75)", color: "white", fontSize: 16, borderRadius: 6, maxWidth: "80%", textAlign: "center", lineHeight: 1.4 }}>
                  {transcript[currentLine].text.slice(0, 100)}{transcript[currentLine].text.length > 100 ? "…" : ""}
                </div>
              )}
              {/* Controls */}
              <div onClick={e => e.stopPropagation()} style={{ position: "absolute", left: 0, right: 0, bottom: 0, padding: 16, background: "linear-gradient(to top, rgba(0,0,0,.9), transparent)" }}>
                {/* Heatmap-aware scrubber */}
                <div style={{ position: "relative", marginBottom: 12 }}>
                  <div style={{ display: "flex", gap: 1, height: 4, marginBottom: 6, opacity: 0.6 }}>
                    {heatmap.map((v, i) => (
                      <div key={i} style={{ flex: 1, background: `rgba(255,92,40,${v.toFixed(2)})`, borderRadius: 1 }}/>
                    ))}
                  </div>
                  <div style={{ height: 4, background: "rgba(255,255,255,.2)", borderRadius: 999, position: "relative", cursor: "pointer" }}
                       onClick={e => {
                         const rect = e.currentTarget.getBoundingClientRect();
                         setPos(Math.max(0, Math.min(1, (e.clientX - rect.left) / rect.width)));
                       }}>
                    <div style={{ width: `${pos*100}%`, height: "100%", background: "var(--accent)", borderRadius: 999 }}/>
                    <div style={{ position: "absolute", left: `${pos*100}%`, top: "50%", transform: "translate(-50%, -50%)", width: 12, height: 12, borderRadius: "50%", background: "white", boxShadow: "0 1px 3px rgba(0,0,0,.4)" }}/>
                  </div>
                </div>
                <div className="row" style={{ color: "white" }}>
                  <button className="btn btn--icon btn--sm" style={{ color: "white" }} onClick={() => setPlaying(!playing)}>
                    {playing ? <I.pause size={18}/> : <I.play size={18}/>}
                  </button>
                  <span className="mono" style={{ fontSize: 12, color: "rgba(255,255,255,.85)" }}>{fmt(curSec)} / {lesson.duration}</span>
                  <div className="spacer"/>
                  <button className="btn btn--ghost btn--sm" style={{ color: "white", fontSize: 11 }} onClick={() => setSpeed(s => s >= 2 ? 0.75 : s + 0.25)}>{speed}×</button>
                  <button className="btn btn--ghost btn--sm" style={{ color: "white" }}><I.fullscreen size={14}/></button>
                </div>
              </div>
            </div>

            <h1 style={{ fontSize: 26, marginTop: 24, marginBottom: 6, letterSpacing: "-0.025em" }}>{lesson.title}</h1>
            <div className="row" style={{ color: "var(--ink-3)", fontSize: 13, marginBottom: 20 }}>
              <span>Mara Klein</span>
              <span>·</span>
              <span>{lesson.duration}</span>
              <span>·</span>
              <span>Recorded Apr 4, 2026</span>
              <div className="spacer"/>
              <button className="btn btn--ghost btn--sm"><I.download size={13}/> Resources</button>
            </div>

            {/* Tabs */}
            <div className="tabs">
              {[
                ["transcript", "Transcript", I.text],
                ["notes", `Notes (${notes.length})`, I.edit],
                ["resources", "Resources", I.download],
                ["discuss", "Discussion", I.chat],
              ].map(([k, l, Ic]) => (
                <div key={k} className={`tab ${tab === k ? "tab--active" : ""}`} onClick={() => setTab(k)}>
                  <Ic size={13}/> {l}
                </div>
              ))}
            </div>

            {tab === "transcript" && (
              <div className="col" style={{ gap: 0 }}>
                {transcript.map((line, i) => (
                  <div key={i}
                       onClick={() => setPos(line.t / totalSec)}
                       style={{
                         display: "grid", gridTemplateColumns: "60px 1fr",
                         gap: 16, padding: "10px 12px", borderRadius: 6,
                         cursor: "pointer",
                         background: i === currentLine ? "var(--bg-elev)" : "transparent",
                         transition: "background 100ms",
                       }}>
                    <span className="mono" style={{ fontSize: 11, color: "var(--ink-3)", paddingTop: 3 }}>{fmt(line.t)}</span>
                    <span style={{
                      fontSize: 14, lineHeight: 1.6,
                      color: i === currentLine ? "var(--ink)" : "var(--ink-2)",
                      fontWeight: i === currentLine ? 500 : 400
                    }}>{line.text}</span>
                  </div>
                ))}
              </div>
            )}

            {tab === "notes" && (
              <div>
                <div style={{ display: "flex", gap: 8, marginBottom: 16 }}>
                  <textarea className="textarea" placeholder={`Note at ${fmt(curSec)}…`} value={note} onChange={e => setNote(e.target.value)} style={{ minHeight: 60 }}/>
                  <button className="btn btn--primary" onClick={() => {
                    if (note.trim()) {
                      setNotes([{ t: fmt(curSec), text: note }, ...notes]);
                      setNote("");
                    }
                  }}>Save</button>
                </div>
                <div className="col" style={{ gap: 0 }}>
                  {notes.map((n, i) => (
                    <div key={i} style={{ padding: "12px 0", borderBottom: i < notes.length - 1 ? "1px solid var(--border)" : "none", display: "grid", gridTemplateColumns: "60px 1fr auto", gap: 12, alignItems: "start" }}>
                      <span className="mono" style={{ fontSize: 11, color: "var(--accent)", paddingTop: 2, cursor: "pointer", fontWeight: 600 }}>{n.t}</span>
                      <div style={{ fontSize: 14, lineHeight: 1.5 }}>{n.text}</div>
                      <button className="btn btn--ghost btn--sm btn--icon"><I.more size={14}/></button>
                    </div>
                  ))}
                </div>
              </div>
            )}

            {tab === "resources" && (
              <div className="col" style={{ gap: 8 }}>
                {[
                  { name: "Positioning workbook.pdf", size: "1.4 MB" },
                  { name: "Niche-finder template.notion", size: "Notion" },
                  { name: "Slides — Office hours #1.key", size: "8.2 MB" },
                ].map(r => (
                  <div key={r.name} className="row" style={{ padding: 14, border: "1px solid var(--border)", borderRadius: 8 }}>
                    <I.download size={16}/>
                    <div style={{ flex: 1 }}>
                      <div style={{ fontSize: 13, fontWeight: 500 }}>{r.name}</div>
                      <div className="muted" style={{ fontSize: 11 }}>{r.size}</div>
                    </div>
                    <button className="btn btn--secondary btn--sm">Download</button>
                  </div>
                ))}
              </div>
            )}

            {tab === "discuss" && (
              <div>
                <div style={{ padding: 24, background: "var(--bg-elev)", borderRadius: 8, textAlign: "center", color: "var(--ink-3)", fontSize: 13 }}>
                  Discussions are quiet on this lesson. Be the first to ask Mara something.
                </div>
              </div>
            )}
          </div>
        </div>

        {/* Right: course outline */}
        <div style={{ overflowY: "auto", background: "var(--bg-elev)" }}>
          <div style={{ padding: "20px 20px 12px" }}>
            <div style={{ fontSize: 12, color: "var(--ink-3)", fontWeight: 600, textTransform: "uppercase", letterSpacing: "0.08em", marginBottom: 8 }}>Course outline</div>
            <div className="row" style={{ marginBottom: 8, justifyContent: "space-between" }}>
              <div className="mono" style={{ fontSize: 12, fontWeight: 600 }}>{course.lessonsCompleted}/{course.lessonsTotal} complete</div>
              <span className="badge badge--green badge--dot">On track</span>
            </div>
            <div className="progress progress--green"><div className="progress__fill" style={{ width: `${course.progress}%` }}/></div>
          </div>

          {course.modules?.map((m, mi) => (
            <div key={m.id} style={{ padding: "8px 0", borderTop: "1px solid var(--border)" }}>
              <div style={{ padding: "10px 20px", display: "flex", alignItems: "center", gap: 8 }}>
                <span className="mono" style={{ fontSize: 11, color: "var(--ink-3)", fontWeight: 600 }}>0{mi+1}</span>
                <div style={{ fontSize: 13, fontWeight: 600 }}>{m.title}</div>
                <div className="spacer"/>
                <span className="muted" style={{ fontSize: 11 }}>{m.lessons.filter(l => l.done).length}/{m.lessons.length}</span>
              </div>
              {m.lessons.map(l => {
                const isActive = l.id === activeLessonId;
                const Ic = l.type === "video" ? I.play : l.type === "quiz" ? I.quiz : I.text;
                return (
                  <div key={l.id}
                       onClick={() => {
                         if (l.locked) return;
                         if (l.type === "quiz") onOpenQuiz();
                         else setActiveLessonId(l.id);
                       }}
                       style={{
                         padding: "10px 20px 10px 36px",
                         display: "flex", alignItems: "center", gap: 10,
                         cursor: l.locked ? "default" : "pointer",
                         background: isActive ? "var(--bg)" : "transparent",
                         borderLeft: isActive ? "2px solid var(--ink)" : "2px solid transparent",
                         opacity: l.locked ? 0.5 : 1,
                       }}>
                    <div style={{
                      width: 18, height: 18, borderRadius: "50%",
                      border: l.done ? "none" : "1.5px solid var(--border-strong)",
                      background: l.done ? "var(--green)" : "var(--bg)",
                      color: "white",
                      display: "flex", alignItems: "center", justifyContent: "center",
                      flexShrink: 0,
                    }}>
                      {l.done ? <I.check size={11} stroke={2.6}/> : l.locked ? <I.lock size={9}/> : null}
                    </div>
                    <Ic size={12}/>
                    <div style={{ flex: 1, fontSize: 13, fontWeight: isActive ? 500 : 400, color: isActive ? "var(--ink)" : "var(--ink-2)" }}>
                      {l.title}
                    </div>
                    <span className="mono" style={{ fontSize: 11, color: "var(--ink-3)" }}>{l.duration}</span>
                  </div>
                );
              })}
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

window.CoursePlayer = CoursePlayer;
