// Player — 學習播放器 with AI side panel (核心畫面)

const PlayerPage = ({ course, setPage }) => {
  const [playing, setPlaying] = React.useState(false);
  const [currentTime, setCurrentTime] = React.useState(324); // 5:24
  const duration = 720; // 12:00
  const [showCaption, setShowCaption] = React.useState(true);
  const [aiTab, setAiTab] = React.useState("qa");
  const [chat, setChat] = React.useState([
    { role: "ai", text: "嗨！我是你的 AI 助教。這段在講「RAG 架構的三層檢索」，需要我幫你重述嗎？", sources: ["第 2 單元 · 05:12"] },
  ]);
  const [input, setInput] = React.useState("");

  React.useEffect(() => {
    if (!playing) return;
    const t = setInterval(() => setCurrentTime(s => Math.min(duration, s + 1)), 1000);
    return () => clearInterval(t);
  }, [playing]);

  const fmt = (s) => `${String(Math.floor(s/60)).padStart(2,"0")}:${String(s%60).padStart(2,"0")}`;

  const send = () => {
    if (!input.trim()) return;
    const userMsg = { role: "user", text: input };
    setChat(c => [...c, userMsg]);
    setInput("");
    setTimeout(() => {
      setChat(c => [...c, {
        role: "ai",
        text: "好的，我幫你用更簡單的方式說明：RAG 三層檢索就像「找資料三步驟」—— ① 先查常見問題庫（最快）② 再查單元教材索引 ③ 最後做語意比對。任何步驟找到就回答。",
        sources: ["第 2 單元 · 05:45", "第 3 單元 · 02:10"],
        confidence: 0.89,
      }]);
    }, 800);
  };

  const crumb = course?.title || "AI 工具應用入門";

  return (
    <div data-screen-label="04 學習播放器" style={{ maxWidth: 1400, margin: "0 auto", padding: "20px 24px 48px" }}>
      {/* Breadcrumb */}
      <div style={{ marginBottom: 14, fontSize: "var(--fs-sm)", color: "var(--muted)", display: "flex", gap: 6, alignItems: "center" }}>
        <a onClick={() => setPage("home")} style={{ cursor: "pointer" }}>首頁</a>
        <Icon name="chevronR" size={12} />
        <a onClick={() => setPage("catalog")} style={{ cursor: "pointer" }}>課程總覽</a>
        <Icon name="chevronR" size={12} />
        <span style={{ color: "var(--ink-2)" }}>{crumb}</span>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1fr 380px", gap: 24 }}>
        {/* LEFT: video + units */}
        <div>
          <Card style={{ overflow: "hidden", padding: 0 }}>
            {/* Video */}
            <div style={{
              position: "relative", aspectRatio: "16/9",
              background: "linear-gradient(135deg, #1a2942, #0a1628)",
              display: "flex", alignItems: "center", justifyContent: "center",
            }}>
              <div style={{
                width: 80, height: 80, borderRadius: "50%",
                background: "rgba(255,255,255,0.18)", border: "2px solid rgba(255,255,255,0.5)",
                display: "flex", alignItems: "center", justifyContent: "center",
                cursor: "pointer", color: "#fff",
              }} onClick={() => setPlaying(!playing)}>
                <Icon name={playing ? "pause" : "play"} size={32} color="#fff" />
              </div>
              <div style={{
                position: "absolute", top: 14, left: 14,
                padding: "4px 10px", background: "rgba(0,0,0,0.5)",
                borderRadius: 4, color: "#fff",
                fontSize: "var(--fs-xs)", fontWeight: 600,
              }}>● 第 2 單元｜RAG 三層檢索架構</div>

              {/* Caption */}
              {showCaption && (
                <div style={{
                  position: "absolute", bottom: 60, left: "50%", transform: "translateX(-50%)",
                  padding: "8px 18px",
                  background: "rgba(0,0,0,0.75)", color: "#fff",
                  borderRadius: 6, fontSize: "var(--fs-lg)", fontWeight: 500,
                  maxWidth: "80%", textAlign: "center",
                }}>
                  RAG 架構採用三層式檢索策略，確保 AI 回應都有憑有據
                </div>
              )}

              {/* Controls */}
              <div style={{
                position: "absolute", bottom: 0, left: 0, right: 0,
                padding: "16px 20px",
                background: "linear-gradient(transparent, rgba(0,0,0,0.7))",
                color: "#fff",
              }}>
                <div style={{ height: 4, background: "rgba(255,255,255,0.25)", borderRadius: 2, marginBottom: 10, position: "relative" }}>
                  <div style={{ height: "100%", width: `${(currentTime/duration)*100}%`, background: "var(--accent)", borderRadius: 2 }} />
                  <div style={{
                    position: "absolute", left: `${(currentTime/duration)*100}%`, top: "50%",
                    width: 12, height: 12, borderRadius: "50%",
                    background: "#fff", transform: "translate(-50%, -50%)",
                  }} />
                </div>
                <div style={{ display: "flex", alignItems: "center", gap: 12, fontSize: "var(--fs-sm)" }}>
                  <button onClick={() => setPlaying(!playing)} style={iconBtn}>
                    <Icon name={playing ? "pause" : "play"} size={18} color="#fff" />
                  </button>
                  <button onClick={() => setShowCaption(!showCaption)} style={{...iconBtn, background: showCaption ? "rgba(232,116,60,0.8)" : "rgba(255,255,255,0.1)"}}>
                    <Icon name="cc" size={18} color="#fff" />
                  </button>
                  <button style={iconBtn}><Icon name="volume" size={18} color="#fff" /></button>
                  <span style={{ fontFamily: "JetBrains Mono, monospace", fontSize: "var(--fs-sm)" }}>
                    {fmt(currentTime)} / {fmt(duration)}
                  </span>
                  <div style={{ marginLeft: "auto", display: "flex", gap: 8 }}>
                    <span style={{ padding: "2px 8px", background: "rgba(255,255,255,0.15)", borderRadius: 4, fontSize: "var(--fs-xs)" }}>1.0x</span>
                    <span style={{ padding: "2px 8px", background: "rgba(255,255,255,0.15)", borderRadius: 4, fontSize: "var(--fs-xs)" }}>HD</span>
                  </div>
                </div>
              </div>
            </div>

            {/* Course info strip */}
            <div style={{ padding: "18px 22px", borderTop: "1px solid var(--border)" }}>
              <div style={{ display: "flex", gap: 6, marginBottom: 8 }}>
                <Tag color="brand">資訊技能</Tag>
                <Tag>入門</Tag>
                <DisabilityBadge type="VI" />
                <DisabilityBadge type="HI" />
                <DisabilityBadge type="LD" />
              </div>
              <h1 style={{ margin: 0, fontSize: "var(--fs-xl)", fontWeight: 800, letterSpacing: "-0.01em" }}>
                {crumb}
              </h1>
              <div style={{ display: "flex", gap: 10, marginTop: 14, flexWrap: "wrap" }}>
                <Button size="sm" variant="ghost" icon="download">下載講義</Button>
                <Button size="sm" variant="ghost" icon="text">查看逐字稿</Button>
                <Button size="sm" variant="ghost" icon="mic">語音提問</Button>
                <Button size="sm" variant="ghost" icon="book">切換易讀版</Button>
              </div>
            </div>
          </Card>

          {/* Units list */}
          <Card style={{ marginTop: 20, padding: 0 }}>
            <div style={{ padding: "16px 22px", borderBottom: "1px solid var(--border)", fontWeight: 700 }}>
              課程單元（共 6 單元）
            </div>
            {[
              { n: 1, t: "什麼是 AI 助教？", d: "08:24", done: true },
              { n: 2, t: "RAG 三層檢索架構", d: "12:00", current: true },
              { n: 3, t: "Prompt 工程基礎", d: "10:18", done: false },
              { n: 4, t: "障別適配設計原則", d: "09:52", done: false },
              { n: 5, t: "幻覺抑制與安全過濾", d: "11:30", done: false },
              { n: 6, t: "實作：打造你的第一個 AI 助教", d: "15:42", done: false },
            ].map(u => (
              <div key={u.n} style={{
                padding: "14px 22px",
                display: "flex", alignItems: "center", gap: 14,
                background: u.current ? "var(--brand-50)" : "transparent",
                borderLeft: u.current ? "3px solid var(--brand)" : "3px solid transparent",
                borderBottom: "1px solid var(--border)",
                cursor: "pointer",
              }}>
                <div style={{
                  width: 32, height: 32, borderRadius: "50%", flexShrink: 0,
                  background: u.done ? "var(--ok)" : u.current ? "var(--brand)" : "var(--bg-2)",
                  color: u.done || u.current ? "#fff" : "var(--muted)",
                  display: "flex", alignItems: "center", justifyContent: "center",
                  fontSize: "var(--fs-sm)", fontWeight: 700,
                }}>
                  {u.done ? <Icon name="check" size={16} stroke={3} /> : u.n}
                </div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontWeight: u.current ? 700 : 500, fontSize: "var(--fs-base)" }}>{u.t}</div>
                  <div style={{ fontSize: "var(--fs-xs)", color: "var(--muted)", marginTop: 2 }}>{u.d}</div>
                </div>
                {u.current && <Tag color="accent">播放中</Tag>}
                {u.done && <Tag color="ok">已完成</Tag>}
              </div>
            ))}
          </Card>
        </div>

        {/* RIGHT: AI sidebar */}
        <div style={{ position: "sticky", top: 88, alignSelf: "start", maxHeight: "calc(100vh - 100px)", display: "flex", flexDirection: "column" }}>
          <Card style={{ padding: 0, display: "flex", flexDirection: "column", height: "calc(100vh - 120px)", minHeight: 600 }}>
            {/* Header */}
            <div style={{
              padding: "14px 18px",
              background: "linear-gradient(135deg, var(--accent) 0%, var(--accent-600) 100%)",
              color: "#fff", display: "flex", alignItems: "center", gap: 10,
            }}>
              <Icon name="sparkle" size={20} color="#fff" />
              <div style={{ flex: 1 }}>
                <div style={{ fontWeight: 700 }}>AI 助教</div>
                <div style={{ fontSize: "var(--fs-xs)", opacity: 0.9 }}>
                  ● 本內容由 AI 生成，供參考
                </div>
              </div>
              <button style={{ background: "rgba(255,255,255,0.2)", border: "none", color: "#fff", borderRadius: 6, padding: "4px 10px", fontSize: "var(--fs-xs)", fontFamily: "inherit", fontWeight: 600 }}>
                轉人工
              </button>
            </div>

            {/* Tabs */}
            <div style={{ display: "flex", borderBottom: "1px solid var(--border)", background: "var(--bg)" }}>
              {[{k:"qa",l:"問答"},{k:"summary",l:"重點摘要"},{k:"cards",l:"複習卡"}].map(t => (
                <button key={t.k} onClick={() => setAiTab(t.k)} style={{
                  flex: 1, padding: "12px 0",
                  background: aiTab === t.k ? "var(--paper)" : "transparent",
                  border: "none",
                  borderBottom: aiTab === t.k ? "2px solid var(--accent)" : "2px solid transparent",
                  color: aiTab === t.k ? "var(--ink)" : "var(--ink-soft)",
                  fontWeight: aiTab === t.k ? 700 : 500,
                  fontSize: "var(--fs-sm)", fontFamily: "inherit", cursor: "pointer",
                }}>{t.l}</button>
              ))}
            </div>

            {/* Content */}
            <div style={{ flex: 1, overflow: "auto", padding: 16, background: "var(--bg)" }}>
              {aiTab === "qa" && <AIChatPane chat={chat} />}
              {aiTab === "summary" && <SummaryPane />}
              {aiTab === "cards" && <CardsPane />}
            </div>

            {/* Quick actions */}
            {aiTab === "qa" && (
              <>
                <div style={{ padding: "8px 12px", borderTop: "1px solid var(--border)", background: "var(--paper)", display: "flex", gap: 6, flexWrap: "wrap" }}>
                  {["問這段在說什麼", "整理重點", "下一步建議", "轉人工助教"].map(q => (
                    <button key={q} onClick={() => { setInput(q); }} style={{
                      padding: "6px 10px", borderRadius: 999,
                      background: "var(--bg-2)", border: "1px solid var(--border)",
                      fontSize: "var(--fs-xs)", color: "var(--ink-2)",
                      fontFamily: "inherit", cursor: "pointer",
                    }}>{q}</button>
                  ))}
                </div>
                <div style={{ padding: 12, borderTop: "1px solid var(--border)", background: "var(--paper)", display: "flex", gap: 8 }}>
                  <button aria-label="語音輸入" style={{
                    width: 40, height: 40, borderRadius: 8,
                    background: "var(--bg-2)", border: "1px solid var(--border)",
                    display: "flex", alignItems: "center", justifyContent: "center",
                  }}><Icon name="mic" size={18} color="var(--ink-2)" /></button>
                  <input
                    value={input} onChange={e => setInput(e.target.value)}
                    onKeyDown={e => e.key === "Enter" && send()}
                    placeholder="對 AI 助教提問..."
                    style={{
                      flex: 1, padding: "0 12px", minHeight: 40,
                      border: "1px solid var(--border)", borderRadius: 8,
                      fontFamily: "inherit", fontSize: "var(--fs-sm)",
                    }}
                  />
                  <button onClick={send} style={{
                    width: 40, height: 40, borderRadius: 8,
                    background: "var(--accent)", color: "#fff",
                    border: "none", display: "flex", alignItems: "center", justifyContent: "center",
                  }}><Icon name="send" size={16} color="#fff" /></button>
                </div>
              </>
            )}
          </Card>
        </div>
      </div>
    </div>
  );
};

const iconBtn = {
  width: 34, height: 34, borderRadius: 6,
  background: "rgba(255,255,255,0.1)", border: "none",
  display: "flex", alignItems: "center", justifyContent: "center",
  cursor: "pointer",
};

const AIChatPane = ({ chat }) => (
  <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
    {chat.map((m, i) => (
      <div key={i} style={{ alignSelf: m.role === "user" ? "flex-end" : "flex-start", maxWidth: "92%" }}>
        {m.role === "ai" && (
          <div style={{ display: "flex", alignItems: "center", gap: 6, marginBottom: 4, color: "var(--accent-600)", fontSize: "var(--fs-xs)", fontWeight: 700 }}>
            <Icon name="sparkle" size={12} color="var(--accent)" /> AI 助教
            {m.confidence != null && (
              <span style={{ marginLeft: 6, padding: "1px 6px", background: "var(--ok-100)", color: "var(--ok)", borderRadius: 4, fontSize: 10 }}>
                信心 {Math.round(m.confidence * 100)}%
              </span>
            )}
          </div>
        )}
        <div style={{
          padding: "10px 14px",
          background: m.role === "user" ? "var(--brand)" : "var(--paper)",
          color: m.role === "user" ? "#fff" : "var(--ink-2)",
          border: m.role === "user" ? "none" : "1px solid var(--border)",
          borderRadius: 10,
          fontSize: "var(--fs-sm)", lineHeight: 1.6,
          whiteSpace: "pre-wrap",
        }}>
          {m.text}
        </div>
        {m.sources && (
          <div style={{ marginTop: 6, fontSize: 11, color: "var(--muted)" }}>
            引用：{m.sources.map((s, j) => (
              <span key={j} style={{ display: "inline-block", padding: "1px 6px", background: "var(--bg-2)", border: "1px solid var(--border)", borderRadius: 4, marginRight: 4, color: "var(--ink-soft)" }}>
                {s}
              </span>
            ))}
          </div>
        )}
      </div>
    ))}
  </div>
);

const SummaryPane = () => (
  <div>
    <div style={{ fontWeight: 700, marginBottom: 8, fontSize: "var(--fs-sm)", color: "var(--ink-soft)" }}>本單元重點（AI 自動整理）</div>
    {[
      "RAG = 檢索增強生成，AI 回答都要有教材根據",
      "三層檢索：快取 → Metadata → 向量語意",
      "本地 HNSW 索引延遲低於 20 毫秒",
      "找不到教材時，系統直接轉人工不猜測",
      "所有回答都會標註來源單元與時間碼",
    ].map((t, i) => (
      <div key={i} style={{ display: "flex", gap: 10, padding: "10px 0", borderBottom: "1px dashed var(--border)" }}>
        <span style={{ fontFamily: "JetBrains Mono, monospace", color: "var(--accent-600)", fontWeight: 700, fontSize: "var(--fs-sm)" }}>
          {String(i+1).padStart(2,"0")}
        </span>
        <span style={{ fontSize: "var(--fs-sm)", lineHeight: 1.6 }}>{t}</span>
      </div>
    ))}
  </div>
);

const CardsPane = () => (
  <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
    {[
      { q: "RAG 的三層是指什麼？", a: "① 語義快取 ② Metadata 檢索 ③ 向量語意檢索" },
      { q: "為什麼 AI 要標註來源？", a: "確保可追溯、可審計，避免幻覺（編造事實）" },
      { q: "本地索引為什麼不需要 GPU？", a: "HNSW 演算法用 CPU 即可達到 20 毫秒內延遲" },
    ].map((c, i) => (
      <Card key={i} style={{ padding: 14 }}>
        <div style={{ fontSize: "var(--fs-xs)", color: "var(--accent-600)", fontWeight: 700, marginBottom: 4 }}>
          複習卡 #{i+1}
        </div>
        <div style={{ fontWeight: 600, fontSize: "var(--fs-sm)", marginBottom: 6 }}>Q：{c.q}</div>
        <div style={{ fontSize: "var(--fs-sm)", color: "var(--ink-soft)", lineHeight: 1.6 }}>A：{c.a}</div>
      </Card>
    ))}
  </div>
);

Object.assign(window, { PlayerPage });
