// AI Chat — 全螢幕對話模式（Modal 浮動，可從任意頁面呼叫）

const AIChatModal = ({ open, onClose, onPickCourse }) => {
  const [mode, setMode] = React.useState("picker"); // picker | chat
  const [chat, setChat] = React.useState([]);
  const [input, setInput] = React.useState("");
  const [thinking, setThinking] = React.useState(false);
  const [selSupports, setSelSupports] = React.useState([]);
  const [showCertPanel, setShowCertPanel] = React.useState(false);
  const scrollRef = React.useRef(null);

  React.useEffect(() => {
    if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
  }, [chat, thinking]);

  if (!open) return null;

  // 以「學習情境/目標」為主軸，避免標籤化
  const presets = [
    { ic: "briefcase", t: "我想找工作", p: "我想準備求職，希望從履歷、面試開始學習" },
    { ic: "sparkle", t: "我想學 AI 工具", p: "我想學 AI 工具提升工作效率" },
    { ic: "book", t: "我想進修技能", p: "請推薦能學到實用職場技能的課程" },
    { ic: "clock", t: "我時間有限", p: "請推薦時長較短、可分段學習的課程" },
  ];
  // 可選的輔助資訊（選填、不強制）
  const supports = [
    { k: "tts", ic: "volume", t: "需要語音播報" },
    { k: "caption", ic: "captions", t: "需要完整字幕" },
    { k: "easy", ic: "book-open", t: "需要易讀版" },
    { k: "repeat", ic: "rotate", t: "想重複複習" },
  ];
  const toggleSupport = (k) => setSelSupports(s => s.includes(k) ? s.filter(x => x !== k) : [...s, k]);
  const sendWithSupports = (basePrompt) => {
    const supportText = selSupports.length
      ? `（另外我${selSupports.map(k => supports.find(s => s.k === k)?.t).filter(Boolean).join("、")}）`
      : "";
    send(basePrompt + supportText);
  };

  const send = (text) => {
    const t = text || input;
    if (!t.trim()) return;
    setChat(c => [...c, { role: "user", text: t }]);
    setInput(""); setMode("chat"); setThinking(true);
    setTimeout(() => {
      setThinking(false);
      setChat(c => [...c, {
        role: "ai",
        text: "根據你的需求，我為你推薦以下 3 門課程，都通過 WCAG 2.1 AAA 認證：",
        recommendations: [
          { id: 5, title: "履歷撰寫工作坊", reason: "短時長（60 分）、完整字幕、分段結構", score: 95 },
          { id: 2, title: "易讀版：求職必備技能", reason: "易讀版首選，圖示輔助", score: 92 },
          { id: 1, title: "AI 工具應用入門", reason: "多障別適配，AI 助教陪伴", score: 88 },
        ],
        sources: ["身心障礙者權益保障法", "WCAG 2.1 AAA"],
      }]);
    }, 1400);
  };

  return (
    <div style={{
      position: "fixed", inset: 0, zIndex: 90,
      background: "rgba(15,26,46,0.65)", backdropFilter: "blur(4px)",
      display: "flex", alignItems: "flex-end", justifyContent: "flex-end", padding: 16,
    }} onClick={onClose}>
      <div onClick={e => e.stopPropagation()} style={{
        width: 440, maxWidth: "100%",
        height: "100%", maxHeight: "calc(100vh - 32px)",
        background: "var(--paper)", borderRadius: 18,
        boxShadow: "var(--shadow-lg)",
        display: "flex", flexDirection: "column", overflow: "hidden",
        animation: "slideUp 280ms ease",
      }}>
        <style>{`@keyframes slideUp{from{transform:translateY(24px);opacity:0}to{transform:none;opacity:1}}`}</style>
        {/* Header */}
        <div style={{
          padding: "16px 20px",
          background: "linear-gradient(135deg, var(--accent), var(--accent-600))", color: "#fff",
          display: "flex", alignItems: "center", gap: 10,
        }}>
          <div style={{
            width: 38, height: 38, borderRadius: 10,
            background: "rgba(255,255,255,0.22)",
            display: "flex", alignItems: "center", justifyContent: "center",
          }}>
            <Icon name="sparkle" size={20} color="#fff" />
          </div>
          <div style={{ flex: 1 }}>
            <div style={{ fontWeight: 700 }}>AI 選課助教</div>
            <div style={{ fontSize: 11, opacity: 0.85 }}>● 內容由 AI 生成，僅供參考</div>
          </div>
          <button onClick={onClose} aria-label="關閉" style={{
            width: 34, height: 34, borderRadius: 8,
            background: "rgba(255,255,255,0.2)", border: "none",
            color: "#fff", display: "flex", alignItems: "center", justifyContent: "center",
          }}><Icon name="x" size={18} color="#fff" /></button>
        </div>

        {/* Body */}
        <div ref={scrollRef} style={{ flex: 1, overflow: "auto", padding: 16, background: "var(--bg)" }}>
          {mode === "picker" && (
            <div>
              <div style={{ padding: 14, background: "var(--paper)", borderRadius: 10, border: "1px solid var(--border)", marginBottom: 16 }}>
                <div style={{ fontSize: "var(--fs-sm)", color: "var(--ink-2)", lineHeight: 1.7 }}>
                  嗨，我是 AI 選課助教。告訴我你想學什麼、或你現在的學習目標，我會幫你挑 3 門最適合的課。
                </div>
              </div>

              <div style={{ fontSize: "var(--fs-xs)", fontWeight: 700, color: "var(--ink-soft)", marginBottom: 10, letterSpacing: "0.08em", textTransform: "uppercase" }}>
                你的學習目標
              </div>
              <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
                {presets.map((p, i) => (
                  <button key={i} onClick={() => sendWithSupports(p.p)} style={{
                    display: "flex", alignItems: "center", gap: 12,
                    padding: "12px 14px", background: "var(--paper)",
                    border: "1px solid var(--border)", borderRadius: 10,
                    fontFamily: "inherit", fontSize: "var(--fs-sm)", textAlign: "left",
                    cursor: "pointer", color: "var(--ink-2)",
                  }}>
                    <Icon name={p.ic} size={18} color="var(--brand)" />
                    <span style={{ fontWeight: 600 }}>{p.t}</span>
                    <span style={{ color: "var(--muted)", marginLeft: "auto", fontSize: 11 }}>→</span>
                  </button>
                ))}
              </div>

              {/* 選用的學習支援需求，不強制、無標籤感 */}
              <div style={{ marginTop: 18 }}>
                <div style={{ fontSize: "var(--fs-xs)", fontWeight: 700, color: "var(--ink-soft)", marginBottom: 4, letterSpacing: "0.08em", textTransform: "uppercase" }}>
                  學習支援需求
                  <span style={{ marginLeft: 6, fontWeight: 400, textTransform: "none", letterSpacing: 0, color: "var(--muted)" }}>選用，可複選</span>
                </div>
                <div style={{ fontSize: 11, color: "var(--muted)", lineHeight: 1.6, marginBottom: 10 }}>
                  讓 AI 在推薦時同時把這些無障礙功能納入考量。
                </div>
                <div style={{ display: "flex", flexWrap: "wrap", gap: 6 }}>
                  {supports.map(s => {
                    const on = selSupports.includes(s.k);
                    return (
                      <button key={s.k} onClick={() => toggleSupport(s.k)} aria-pressed={on} style={{
                        display: "inline-flex", alignItems: "center", gap: 6,
                        padding: "6px 10px", borderRadius: 999,
                        border: on ? "1.5px solid var(--brand)" : "1px solid var(--border)",
                        background: on ? "var(--brand-50)" : "var(--paper)",
                        color: on ? "var(--brand-600)" : "var(--ink-2)",
                        fontFamily: "inherit", fontSize: 12, fontWeight: on ? 600 : 500,
                        cursor: "pointer",
                      }}>
                        <Icon name={s.ic} size={13} color={on ? "var(--brand)" : "var(--ink-soft)"} />
                        {s.t}
                      </button>
                    );
                  })}
                </div>
              </div>

              {/* 低調的證明上傳入口 — 可展開的細節 */}
              <div style={{ marginTop: 20, paddingTop: 14, borderTop: "1px dashed var(--border)" }}>
                <button onClick={() => setShowCertPanel(v => !v)} style={{
                  display: "flex", alignItems: "center", gap: 6,
                  padding: 0, background: "transparent", border: "none",
                  fontFamily: "inherit", fontSize: 12, color: "var(--ink-soft)",
                  cursor: "pointer", textDecoration: "underline", textUnderlineOffset: 3,
                }}>
                  <Icon name="shield" size={12} color="var(--ink-soft)" />
                  有身心障礙證明嗎？上傳讓 AI 推薦更精準（選用）
                </button>
                {showCertPanel && (
                  <div style={{ marginTop: 10, padding: 12, background: "var(--bg-2)", borderRadius: 8, fontSize: 12, color: "var(--ink-soft)", lineHeight: 1.7 }}>
                    <div style={{ fontWeight: 600, color: "var(--ink-2)", marginBottom: 6 }}>隱私承諾</div>
                    <ul style={{ margin: 0, paddingLeft: 16 }}>
                      <li>上傳後立即去識別化，僅萃取「障別類型」用於課程推薦。</li>
                      <li>原始檔案不儲存、不外傳、不作為成績或審查依據。</li>
                      <li>所有功能不需要證明也能使用，上傳僅為輔助。</li>
                    </ul>
                    <button style={{
                      marginTop: 10, padding: "8px 14px",
                      background: "var(--paper)", border: "1px solid var(--border)",
                      borderRadius: 8, fontFamily: "inherit", fontSize: 12, fontWeight: 600,
                      color: "var(--ink-2)", cursor: "pointer",
                    }}>
                      <Icon name="upload" size={12} /> 選擇檔案上傳
                    </button>
                  </div>
                )}
              </div>
            </div>
          )}

          {mode === "chat" && (
            <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
              {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", gap: 6, alignItems: "center", marginBottom: 4, color: "var(--accent-600)", fontSize: 11, fontWeight: 700 }}>
                      <Icon name="sparkle" size={12} color="var(--accent)" /> AI 選課助教
                    </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,
                  }}>
                    {m.text}
                  </div>
                  {m.recommendations && (
                    <div style={{ marginTop: 8, display: "flex", flexDirection: "column", gap: 8 }}>
                      {m.recommendations.map(r => (
                        <div key={r.id} onClick={() => onPickCourse(r)} style={{
                          padding: 12, background: "var(--paper)",
                          border: "1.5px solid var(--border)", borderRadius: 10,
                          cursor: "pointer",
                        }}>
                          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
                            <div style={{ fontWeight: 700, fontSize: "var(--fs-sm)" }}>{r.title}</div>
                            <Tag color="ok">{r.score}% 匹配</Tag>
                          </div>
                          <div style={{ fontSize: 11, color: "var(--muted)", marginTop: 4 }}>
                            ✦ {r.reason}
                          </div>
                        </div>
                      ))}
                    </div>
                  )}
                  {m.sources && (
                    <div style={{ marginTop: 6, fontSize: 11, color: "var(--muted)" }}>
                      引用：{m.sources.map((s, j) => (
                        <span key={j} style={{ padding: "1px 6px", background: "var(--bg-2)", borderRadius: 4, marginRight: 4 }}>{s}</span>
                      ))}
                    </div>
                  )}
                </div>
              ))}
              {thinking && (
                <div style={{ alignSelf: "flex-start", display: "flex", gap: 4, padding: "10px 14px", background: "var(--paper)", borderRadius: 10, border: "1px solid var(--border)" }}>
                  <Dot /><Dot d={0.15} /><Dot d={0.3} />
                </div>
              )}
            </div>
          )}
        </div>

        {/* Input */}
        <div style={{ padding: 12, borderTop: "1px solid var(--border)", 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} /></button>
          <input
            value={input} onChange={e => setInput(e.target.value)}
            onKeyDown={e => e.key === "Enter" && send()}
            placeholder="告訴我你的學習需求..."
            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>
      </div>
    </div>
  );
};

const Dot = ({ d = 0 }) => (
  <>
    <style>{`@keyframes dbop{0%,80%,100%{opacity:0.3}40%{opacity:1}}`}</style>
    <span style={{
      width: 6, height: 6, borderRadius: "50%",
      background: "var(--muted)", display: "inline-block",
      animation: `dbop 1.2s infinite`, animationDelay: `${d}s`,
    }} />
  </>
);

Object.assign(window, { AIChatModal });
