// Accessibility Entry Points — 視障友善啟動機制
// 1. Skip-to-content（Tab 第一個焦點）
// 2. 鍵盤捷徑偵測（Alt+1 開啟 AI 語音、Alt+0 開啟無障礙工具）
// 3. 首次進站 3 秒鐘無互動 → 自動 TTS 播報「按空白鍵啟動語音助教」

const SkipLinks = ({ onOpenVoice, onOpenA11y }) => {
  const links = [
    { href: "#main", l: "跳至主要內容" },
    { href: "#nav", l: "跳至主選單" },
    { action: onOpenVoice, l: "啟動語音助教（Alt+1）" },
    { action: onOpenA11y, l: "開啟無障礙工具（Alt+0）" },
  ];
  return (
    <>
      <style>{`
        .skip-links a, .skip-links button {
          position: absolute; left: -9999px;
          padding: 12px 20px;
          background: #000; color: #ffef5a;
          font-weight: 700; text-decoration: underline;
          border: 3px solid #ffef5a;
          font-family: inherit; font-size: 16px;
          z-index: 200;
        }
        .skip-links a:focus, .skip-links button:focus {
          left: 12px; top: 12px;
        }
      `}</style>
      <div className="skip-links">
        {links.map((l, i) =>
          l.href ? <a key={i} href={l.href} style={{ top: 12 + i * 52 + "px" }}>{l.l}</a>
                 : <button key={i} onClick={l.action} style={{ top: 12 + i * 52 + "px" }}>{l.l}</button>
        )}
      </div>
    </>
  );
};

// Voice Assistant — 全螢幕語音模式
const VoiceAssistantOverlay = ({ open, onClose, onCommand }) => {
  const [listening, setListening] = React.useState(false);
  const [heard, setHeard] = React.useState("");
  const [spoken, setSpoken] = React.useState("");

  React.useEffect(() => {
    if (!open) return;
    // Auto-greet on open
    const greeting = "您好，我是語音助教。請說出「選課」、「繼續學習」、「我的進度」，或按數字鍵 1 到 4 選擇。按 Esc 離開。";
    speak(greeting);
    setSpoken(greeting);
    setListening(true);

    const onKey = (e) => {
      if (e.key === "Escape") { onClose(); }
      if (e.key === "1") onCommand("catalog");
      if (e.key === "2") onCommand("player");
      if (e.key === "3") onCommand("dashboard");
      if (e.key === "4") onCommand("events");
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [open]);

  const speak = (text) => {
    try {
      if ("speechSynthesis" in window) {
        const u = new SpeechSynthesisUtterance(text);
        u.lang = "zh-TW"; u.rate = 0.95;
        window.speechSynthesis.cancel();
        window.speechSynthesis.speak(u);
      }
    } catch (e) {}
  };

  if (!open) return null;

  const menu = [
    { k: "1", l: "課程總覽", cmd: "catalog" },
    { k: "2", l: "繼續學習", cmd: "player" },
    { k: "3", l: "我的進度", cmd: "dashboard" },
    { k: "4", l: "活動與同步教學", cmd: "events" },
  ];

  return (
    <div role="dialog" aria-live="assertive" aria-label="語音助教" style={{
      position: "fixed", inset: 0, zIndex: 200,
      background: "#000", color: "#fff",
      display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center",
      padding: 40,
    }}>
      <div style={{
        width: 180, height: 180, borderRadius: "50%",
        background: "radial-gradient(circle, var(--accent), var(--accent-600))",
        display: "flex", alignItems: "center", justifyContent: "center",
        marginBottom: 32, position: "relative",
      }}>
        <style>{`@keyframes voicePulse{0%,100%{transform:scale(1);opacity:0.4}50%{transform:scale(1.3);opacity:0}}`}</style>
        <div style={{
          position: "absolute", inset: 0, borderRadius: "50%",
          border: "4px solid var(--accent)",
          animation: listening ? "voicePulse 1.6s ease-out infinite" : "none",
        }} />
        <Icon name="mic" size={72} color="#fff" stroke={2.5} />
      </div>

      <h1 style={{ fontSize: 42, fontWeight: 900, margin: 0, letterSpacing: "-0.02em" }}>
        語音助教已啟動
      </h1>
      <div aria-live="polite" style={{
        marginTop: 18, fontSize: 22, color: "#ffd7a8", maxWidth: 720, textAlign: "center", lineHeight: 1.6,
      }}>
        {spoken}
      </div>

      <div style={{
        marginTop: 36, padding: 28,
        background: "rgba(255,255,255,0.08)", borderRadius: 20,
        width: "100%", maxWidth: 720,
      }}>
        <div style={{ fontSize: 18, color: "#ffef5a", fontWeight: 700, marginBottom: 18, letterSpacing: "0.08em" }}>
          按數字鍵快速選擇
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
          {menu.map(m => (
            <button key={m.k} onClick={() => onCommand(m.cmd)} style={{
              padding: "22px 24px",
              background: "#fff", color: "#000",
              border: "3px solid #ffef5a", borderRadius: 14,
              fontSize: 24, fontWeight: 800, fontFamily: "inherit",
              display: "flex", alignItems: "center", gap: 18, textAlign: "left", cursor: "pointer",
            }}>
              <span style={{
                width: 48, height: 48, borderRadius: 10,
                background: "#000", color: "#ffef5a",
                display: "flex", alignItems: "center", justifyContent: "center",
                fontSize: 28, fontWeight: 900,
              }}>{m.k}</span>
              <span>{m.l}</span>
            </button>
          ))}
        </div>
      </div>

      <div style={{ marginTop: 28, fontSize: 16, color: "#cfd7e5" }}>
        按 <kbd style={kbdStyle}>Esc</kbd> 離開 ·
        按 <kbd style={kbdStyle}>空白鍵</kbd> 重新朗讀 ·
        按 <kbd style={kbdStyle}>Alt + 0</kbd> 開啟無障礙工具
      </div>
      <button onClick={onClose} style={{
        marginTop: 18, padding: "14px 32px",
        background: "transparent", color: "#fff",
        border: "2px solid #fff", borderRadius: 8,
        fontSize: 16, fontFamily: "inherit", fontWeight: 600, cursor: "pointer",
      }}>關閉語音助教 (Esc)</button>
    </div>
  );
};

const kbdStyle = {
  display: "inline-block", padding: "2px 10px", margin: "0 2px",
  background: "#fff", color: "#000", borderRadius: 4,
  fontFamily: "monospace", fontWeight: 700, fontSize: 14,
};

// First-visit audio hint — 首次進站若 3 秒無互動，右上出現「按空白鍵啟動語音助教」
const FirstVisitHint = ({ onOpenVoice }) => {
  const [show, setShow] = React.useState(false);
  const [dismissed, setDismissed] = React.useState(() => localStorage.getItem("eap_hint_dismissed") === "1");

  React.useEffect(() => {
    if (dismissed) return;
    let interacted = false;
    const onInt = () => { interacted = true; };
    window.addEventListener("click", onInt, { once: true });
    window.addEventListener("keydown", onInt, { once: true });
    const t = setTimeout(() => { if (!interacted) setShow(true); }, 3000);
    return () => { clearTimeout(t); window.removeEventListener("click", onInt); window.removeEventListener("keydown", onInt); };
  }, [dismissed]);

  const dismiss = () => { setShow(false); setDismissed(true); localStorage.setItem("eap_hint_dismissed", "1"); };

  if (!show || dismissed) return null;

  return (
    <div role="alert" style={{
      position: "fixed", top: 100, right: 20, zIndex: 70,
      maxWidth: 340, padding: 18,
      background: "#000", color: "#fff",
      border: "3px solid var(--accent)", borderRadius: 14,
      boxShadow: "var(--shadow-lg)",
      animation: "slideInR 320ms ease",
    }}>
      <style>{`@keyframes slideInR{from{transform:translateX(24px);opacity:0}to{transform:none;opacity:1}}`}</style>
      <div style={{ display: "flex", gap: 10, alignItems: "center", marginBottom: 8 }}>
        <Icon name="volume" size={20} color="var(--accent)" />
        <div style={{ fontWeight: 700, color: "#ffef5a" }}>無障礙提示</div>
      </div>
      <div style={{ fontSize: 15, lineHeight: 1.7 }}>
        視障朋友請按下 <kbd style={kbdStyle}>空白鍵</kbd> 或 <kbd style={kbdStyle}>Alt + 1</kbd> 啟動語音助教，<br/>
        也可按 <kbd style={kbdStyle}>Tab</kbd> 顯示跳頁連結。
      </div>
      <div style={{ display: "flex", gap: 8, marginTop: 12 }}>
        <button onClick={onOpenVoice} style={{
          flex: 1, padding: "10px", background: "var(--accent)", color: "#fff",
          border: "none", borderRadius: 6, fontWeight: 700, cursor: "pointer", fontFamily: "inherit",
        }}>立即啟動</button>
        <button onClick={dismiss} style={{
          padding: "10px 14px", background: "transparent", color: "#fff",
          border: "1px solid #fff", borderRadius: 6, cursor: "pointer", fontFamily: "inherit",
        }}>關閉</button>
      </div>
    </div>
  );
};

Object.assign(window, { SkipLinks, VoiceAssistantOverlay, FirstVisitHint });
