// A11y Profile — 使用者無障礙偏好資料模型 + Context + Hook
// 依建議書 1.2.2.2 + 1.2.2.5 設計：首次登入問卷 → 儲存 profile → 自動套用

const A11Y_PRESETS = {
  VI: {
    label: "視覺障礙",
    icon: "eye",
    desc: "語音優先、鍵盤導覽、高對比",
    flags: {
      tts_default: true,         // 自動開啟 TTS 播報
      screen_reader_hints: true, // aria-live 增強提示
      focus_visible_strong: true,// 焦點框加粗
      captions_default: false,
      easy_read: false,
      multi_input: false,
      reduce_motion: true,       // 減少動畫干擾螢幕閱讀器
    },
    theme: { text_size: "xl", contrast: "high", density: "relaxed" },
  },
  HI: {
    label: "聽覺障礙",
    icon: "ear",
    desc: "字幕、逐字稿、視覺提示取代音效",
    flags: {
      tts_default: false,
      captions_default: true,        // 預設開啟字幕
      visual_alerts: true,           // 音效 → 閃爍/圖示
      transcript_default: true,      // 逐字稿預設展開
      sign_language_when_available: true,
      easy_read: false,
      multi_input: false,
      reduce_motion: false,
    },
    theme: { text_size: "lg", contrast: "normal", density: "comfortable" },
  },
  CI: {
    label: "認知障礙",
    icon: "puzzle",
    desc: "易讀版、簡化介面、一次一步",
    flags: {
      tts_default: true,            // 易讀+語音雙軌
      captions_default: true,
      easy_read: true,              // 開啟易讀版
      simplify_nav: true,           // 導覽簡化、減少選項
      one_step_at_a_time: true,     // 複雜流程拆步驟
      show_icons_with_text: true,   // 所有按鈕加大圖示
      reduce_motion: true,
    },
    theme: { text_size: "xl", contrast: "normal", density: "relaxed" },
  },
  LD: {
    label: "學習障礙",
    icon: "brain",
    desc: "多感官、結構化、重複提示",
    flags: {
      tts_default: true,
      captions_default: true,
      multi_input: true,            // 語音 + 文字並行輸入
      structured_summary: true,     // AI 摘要預設結構化
      show_icons_with_text: true,
      highlight_key_terms: true,    // 關鍵詞高亮
      easy_read: false,
      reduce_motion: false,
    },
    theme: { text_size: "lg", contrast: "normal", density: "comfortable" },
  },
  none: {
    label: "不指定 / 標準",
    icon: "user",
    desc: "標準介面",
    flags: {
      tts_default: false,
      captions_default: false,
      easy_read: false,
      multi_input: false,
      reduce_motion: false,
    },
    theme: { text_size: "md", contrast: "normal", density: "comfortable" },
  },
};

const DEFAULT_PROFILE = {
  first_visit: true,           // false 表示已完成 Onboarding
  primary: null,               // 主要障別代碼 VI/HI/CI/LD/none
  secondary: [],               // 次要（複選）
  goal: null,
  schedule: null,
  interests: [],
  // 以下是實際套用到 UI 的 flags — 可由使用者在偏好中心微調覆蓋
  flags: {},
  theme: { text_size: "md", contrast: "normal", density: "comfortable" },
  completed_at: null,
};

const A11yContext = React.createContext(null);

const A11yProvider = ({ children }) => {
  const [profile, setProfileState] = React.useState(() => {
    try {
      const raw = localStorage.getItem("eap_a11y_profile");
      if (raw) return { ...DEFAULT_PROFILE, ...JSON.parse(raw) };
    } catch (e) {}
    return DEFAULT_PROFILE;
  });

  // 套用到 document root
  React.useEffect(() => {
    const html = document.documentElement;
    // 外部 data-attribute 使用中性命名，避免揭露醫療分類
    const PUBLIC_MAP = { VI: "audio-first", HI: "visual-first", CI: "step-by-step", LD: "multi-modal", none: "standard" };
    html.setAttribute("data-profile", PUBLIC_MAP[profile.primary] || "standard");
    html.setAttribute("data-text-size", profile.theme?.text_size || "md");
    html.setAttribute("data-hc", profile.theme?.contrast === "high" ? "1" : "0");
    html.setAttribute("data-density", profile.theme?.density || "comfortable");
    // expose flags as data-attrs for CSS hooks
    Object.entries(profile.flags || {}).forEach(([k, v]) => {
      if (v) html.setAttribute(`data-flag-${k.replace(/_/g, "-")}`, "1");
      else html.removeAttribute(`data-flag-${k.replace(/_/g, "-")}`);
    });
    localStorage.setItem("eap_a11y_profile", JSON.stringify(profile));
  }, [profile]);

  const setProfile = (next) => setProfileState(prev => ({ ...prev, ...next }));

  // Apply a preset — 根據建議書 1.2.2.5 的四障別預設
  const applyPreset = (code, extras = {}) => {
    const preset = A11Y_PRESETS[code] || A11Y_PRESETS.none;
    setProfileState(prev => ({
      ...prev,
      first_visit: false,
      primary: code,
      flags: { ...preset.flags },
      theme: { ...preset.theme },
      completed_at: new Date().toISOString(),
      ...extras,
    }));
  };

  const resetProfile = () => {
    localStorage.removeItem("eap_a11y_profile");
    setProfileState({ ...DEFAULT_PROFILE });
  };

  // Toggle a single flag (用於偏好管理中心的微調)
  const toggleFlag = (key) => {
    setProfileState(prev => ({
      ...prev,
      flags: { ...prev.flags, [key]: !prev.flags?.[key] },
    }));
  };

  const setTheme = (patch) => {
    setProfileState(prev => ({
      ...prev,
      theme: { ...prev.theme, ...patch },
    }));
  };

  return (
    <A11yContext.Provider value={{ profile, setProfile, applyPreset, resetProfile, toggleFlag, setTheme, presets: A11Y_PRESETS }}>
      {children}
    </A11yContext.Provider>
  );
};

const useA11y = () => {
  const ctx = React.useContext(A11yContext);
  if (!ctx) return { profile: DEFAULT_PROFILE, presets: A11Y_PRESETS };
  return ctx;
};

const useFlag = (key) => {
  const { profile } = useA11y();
  return !!profile.flags?.[key];
};

// -----------------------------------------------------------
// TTS — 全站共用語音朗讀 hook / helper
// -----------------------------------------------------------

// 瀏覽器政策：speechSynthesis 需要使用者手勢 (click/keydown) 才能初始化。
// 我們在全域監聽任一互動事件後標記 unlock，並在此之前 queue 住的 speak 任務會在 unlock 後補播。
let __ttsUnlocked = false;
let __ttsPending = null; // { text, opts } — 僅保留最後一筆
const __flushPending = () => {
  if (!__ttsPending) return;
  const { text, opts } = __ttsPending;
  __ttsPending = null;
  ttsSpeak(text, opts);
};
if (typeof window !== "undefined" && !window.__tts_unlock_bound) {
  window.__tts_unlock_bound = true;
  const onInteract = () => {
    __ttsUnlocked = true;
    // 觸發一次無聲 utterance 以「啟動」engine（某些瀏覽器需要）
    try {
      if ("speechSynthesis" in window) {
        const warm = new SpeechSynthesisUtterance("");
        warm.volume = 0;
        window.speechSynthesis.speak(warm);
      }
    } catch (e) {}
    __flushPending();
    window.removeEventListener("pointerdown", onInteract, true);
    window.removeEventListener("keydown", onInteract, true);
    window.removeEventListener("touchstart", onInteract, true);
  };
  window.addEventListener("pointerdown", onInteract, true);
  window.addEventListener("keydown", onInteract, true);
  window.addEventListener("touchstart", onInteract, true);
}

const ttsSpeak = (text, opts = {}) => {
  try {
    if (!("speechSynthesis" in window) || !text) return;
    // 尚未獲得使用者手勢 — 暫存，等解鎖後補播
    if (!__ttsUnlocked) {
      __ttsPending = { text, opts };
      return;
    }
    const synth = window.speechSynthesis;
    synth.cancel();
    // 延遲一拍再 speak，避免 cancel 後立即 speak 被吞掉（Chrome bug）
    setTimeout(() => {
      try {
        const u = new SpeechSynthesisUtterance(String(text));
        u.lang = opts.lang || "zh-TW";
        u.rate = opts.rate || 0.95;
        u.pitch = opts.pitch || 1;
        synth.speak(u);
      } catch (e) {}
    }, 60);
  } catch (e) {}
};
const ttsCancel = () => { try { window.speechSynthesis?.cancel(); } catch (e) {} };

// 全站：根據 profile.flags.tts_default 決定是否自動朗讀
// 使用方式：const { speak, speakIfAuto, cancel, autoOn } = useTTS();
//   - speak(text)       主動朗讀（忽略設定）
//   - speakIfAuto(text) 僅在自動朗讀開啟時朗讀
//   - autoOn            bool，當前是否為「自動朗讀」狀態
const useTTS = () => {
  const { profile } = useA11y();
  const autoOn = !!profile.flags?.tts_default;
  return {
    speak: ttsSpeak,
    cancel: ttsCancel,
    speakIfAuto: (text, opts) => { if (autoOn) ttsSpeak(text, opts); },
    autoOn,
  };
};

// 頁面進入時自動朗讀 — 僅當 tts_default flag 開啟
// 用在每個 Page 元件 mount 時，傳入 title + (可選) summary
const usePageAutoAnnounce = (title, summary) => {
  const { speakIfAuto, cancel } = useTTS();
  React.useEffect(() => {
    if (!title) return;
    // 先 cancel 之前的朗讀，再延遲播放。延遲拉到 450ms —
    // 避免 cancel 後的 queue 還沒清空就 speak（某些瀏覽器會吞掉新 utterance）
    cancel();
    const t = setTimeout(() => {
      const text = summary ? `${title}。${summary}` : title;
      speakIfAuto(text);
    }, 450);
    return () => { clearTimeout(t); };
    // eslint-disable-next-line
  }, [title, summary]);
};

Object.assign(window, {
  A11Y_PRESETS, A11yContext, A11yProvider, useA11y, useFlag, DEFAULT_PROFILE,
  useTTS, ttsSpeak, ttsCancel, usePageAutoAnnounce,
});
