// Preference Center — 無障礙偏好管理中心
// 於右上角「偏好」按鈕打開，允許使用者重設/微調 onboarding 結果

const PreferenceCenter = ({ open, onClose, onReopenOnboarding }) => {
  const { profile, applyPreset, toggleFlag, setTheme, resetProfile, presets } = useA11y();
  const [tab, setTab] = React.useState("main");

  if (!open) return null;

  const currentPreset = presets[profile.primary] || presets.none;

  const FLAG_LABELS = {
    tts_default: "預設開啟語音播報 (TTS)",
    captions_default: "影片預設開啟字幕",
    transcript_default: "預設展開逐字稿",
    sign_language_when_available: "有手語版時自動播放",
    visual_alerts: "音效 → 視覺閃爍提示",
    easy_read: "使用易讀版內容",
    simplify_nav: "簡化導覽（減少選項）",
    one_step_at_a_time: "複雜流程逐步引導",
    show_icons_with_text: "所有按鈕顯示大圖示",
    highlight_key_terms: "高亮關鍵詞",
    structured_summary: "結構化重點摘要",
    multi_input: "多感官輸入（語音+文字）",
    screen_reader_hints: "增強螢幕閱讀器提示",
    focus_visible_strong: "焦點框加粗（鍵盤導覽）",
    reduce_motion: "減少動畫效果",
  };

  return (
    <div style={{
      position: "fixed", inset: 0, zIndex: 98,
      background: "rgba(15,26,46,0.55)", backdropFilter: "blur(4px)",
      display: "flex", alignItems: "center", justifyContent: "center", padding: 16,
    }} onClick={onClose}>
      <div onClick={e => e.stopPropagation()} role="dialog" aria-modal="true" style={{
        width: "100%", maxWidth: 720,
        maxHeight: "calc(100vh - 32px)",
        display: "flex", flexDirection: "column",
        background: "var(--paper)", borderRadius: 18,
        boxShadow: "var(--shadow-lg)",
        overflow: "hidden",
      }}>
        <div style={{
          padding: "14px 24px", background: "var(--ink)", color: "#fff",
          display: "flex", alignItems: "center", gap: 12,
          flexShrink: 0,
        }}>
          <div style={{ width: 40, height: 40, borderRadius: 10, background: "rgba(255,255,255,0.15)", display: "flex", alignItems: "center", justifyContent: "center" }}>
            <Icon name="sliders" size={20} color="#fff" />
          </div>
          <div style={{ flex: 1 }}>
            <div style={{ fontWeight: 800, fontSize: 18 }}>無障礙偏好設定</div>
            <div style={{ fontSize: 12, opacity: 0.75 }}>首次設定於 {profile.completed_at ? new Date(profile.completed_at).toLocaleString("zh-TW") : "尚未設定"}</div>
          </div>
          <button onClick={onClose} aria-label="關閉" style={{ width: 36, height: 36, borderRadius: 8, background: "rgba(255,255,255,0.15)", border: "none", color: "#fff", display: "flex", alignItems: "center", justifyContent: "center" }}>
            <Icon name="x" size={18} color="#fff" />
          </button>
        </div>

        {/* Tabs */}
        <div style={{ display: "flex", borderBottom: "1px solid var(--border)", background: "var(--bg)", flexShrink: 0 }}>
          {[
            { k: "main", l: "主要偏好", icon: "user" },
            { k: "flags", l: "功能微調", icon: "sliders" },
            { k: "display", l: "顯示調整", icon: "eye" },
          ].map(t => (
            <button key={t.k} onClick={() => setTab(t.k)} style={{
              flex: 1, padding: "14px 8px",
              background: tab === t.k ? "var(--paper)" : "transparent",
              border: "none", borderBottom: `3px solid ${tab === t.k ? "var(--brand)" : "transparent"}`,
              fontFamily: "inherit", fontWeight: tab === t.k ? 800 : 600,
              color: tab === t.k ? "var(--brand)" : "var(--ink-soft)",
              cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center", gap: 6,
            }}>
              <Icon name={t.icon} size={16} color={tab === t.k ? "var(--brand)" : "var(--ink-soft)"} />
              {t.l}
            </button>
          ))}
        </div>

        <div style={{ padding: 24, flex: 1, overflowY: "auto", minHeight: 0 }}>
          {tab === "main" && (
            <>
              <div style={{ padding: 14, background: "var(--brand-50)", borderRadius: 10, marginBottom: 16, border: "1px solid var(--brand-100)" }}>
                <div style={{ fontSize: 12, color: "var(--muted)", marginBottom: 4 }}>目前套用</div>
                <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                  <Icon name={currentPreset.icon} size={22} color="var(--brand)" />
                  <div>
                    <div style={{ fontWeight: 800, fontSize: 16 }}>{currentPreset.label}</div>
                    <div style={{ fontSize: 12, color: "var(--ink-soft)" }}>{currentPreset.desc}</div>
                  </div>
                </div>
              </div>

              <div style={{ fontSize: 13, fontWeight: 700, color: "var(--ink-soft)", marginBottom: 8, letterSpacing: "0.05em" }}>切換預設</div>
              <div style={{ display: "grid", gridTemplateColumns: "repeat(2, 1fr)", gap: 10 }}>
                {Object.entries(presets).map(([code, p]) => (
                  <button key={code} onClick={() => applyPreset(code)} style={{
                    padding: "12px 14px", textAlign: "left",
                    background: profile.primary === code ? "var(--brand-50)" : "var(--paper)",
                    border: `2px solid ${profile.primary === code ? "var(--brand)" : "var(--border)"}`,
                    borderRadius: 10, cursor: "pointer", fontFamily: "inherit",
                    display: "flex", alignItems: "center", gap: 10,
                  }}>
                    <div style={{ width: 32, height: 32, borderRadius: 8, background: profile.primary === code ? "var(--brand)" : "var(--bg-2)", display: "flex", alignItems: "center", justifyContent: "center" }}>
                      <Icon name={p.icon} size={16} color={profile.primary === code ? "#fff" : "var(--ink-soft)"} />
                    </div>
                    <div>
                      <div style={{ fontWeight: 700, fontSize: 14 }}>{p.label}</div>
                      <div style={{ fontSize: 11, color: "var(--muted)" }}>{p.desc}</div>
                    </div>
                  </button>
                ))}
              </div>

              <div style={{ marginTop: 20, paddingTop: 16, borderTop: "1px solid var(--border)", display: "flex", gap: 8 }}>
                <Button variant="secondary" icon="refresh" onClick={() => { resetProfile(); onReopenOnboarding && onReopenOnboarding(); onClose(); }}>重新完成問卷</Button>
                <Button variant="ghost" onClick={resetProfile}>清除所有偏好</Button>
              </div>
            </>
          )}

          {tab === "flags" && (
            <div>
              <div style={{ fontSize: 13, color: "var(--muted)", lineHeight: 1.6, marginBottom: 14 }}>
                以下為系統根據您的障別預設的功能。勾選方塊可個別覆蓋。
              </div>
              {Object.entries(FLAG_LABELS).map(([k, l]) => {
                const on = !!profile.flags?.[k];
                return (
                  <label key={k} style={{
                    display: "flex", alignItems: "center", gap: 12,
                    padding: "12px 14px", marginBottom: 6,
                    background: on ? "var(--brand-50)" : "var(--bg)",
                    border: `1.5px solid ${on ? "var(--brand)" : "var(--border)"}`,
                    borderRadius: 10, cursor: "pointer",
                  }}>
                    <input type="checkbox" checked={on} onChange={() => toggleFlag(k)} style={{ width: 20, height: 20, accentColor: "var(--brand)" }} />
                    <span style={{ flex: 1, fontSize: 14, fontWeight: on ? 700 : 500, color: on ? "var(--brand-600)" : "var(--ink)" }}>{l}</span>
                    {on && <span style={{ fontSize: 11, fontWeight: 700, color: "var(--ok)", padding: "2px 8px", background: "var(--ok-100)", borderRadius: 999 }}>啟用中</span>}
                  </label>
                );
              })}
            </div>
          )}

          {tab === "display" && (
            <div>
              <div style={{ fontSize: 13, fontWeight: 700, color: "var(--ink-soft)", marginBottom: 8, letterSpacing: "0.05em" }}>字級</div>
              <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 8, marginBottom: 18 }}>
                {[{ v: "sm", l: "小" }, { v: "md", l: "標準" }, { v: "lg", l: "大" }, { v: "xl", l: "特大" }].map(o => {
                  const on = profile.theme?.text_size === o.v;
                  return (
                    <button key={o.v} onClick={() => setTheme({ text_size: o.v })} style={{
                      padding: "14px 8px", background: on ? "var(--brand)" : "var(--paper)",
                      color: on ? "#fff" : "var(--ink)", border: `2px solid ${on ? "var(--brand)" : "var(--border)"}`,
                      borderRadius: 10, fontFamily: "inherit", fontWeight: 700, cursor: "pointer",
                      fontSize: o.v === "sm" ? 13 : o.v === "md" ? 15 : o.v === "lg" ? 17 : 20,
                    }}>{o.l}</button>
                  );
                })}
              </div>

              <div style={{ fontSize: 13, fontWeight: 700, color: "var(--ink-soft)", marginBottom: 8, letterSpacing: "0.05em" }}>對比度</div>
              <div style={{ display: "grid", gridTemplateColumns: "repeat(2, 1fr)", gap: 8, marginBottom: 18 }}>
                {[{ v: "normal", l: "標準對比" }, { v: "high", l: "高對比" }].map(o => {
                  const on = profile.theme?.contrast === o.v;
                  return (
                    <button key={o.v} onClick={() => setTheme({ contrast: o.v })} style={{
                      padding: "12px 14px",
                      background: on ? (o.v === "high" ? "#000" : "var(--brand)") : "var(--paper)",
                      color: on ? "#fff" : "var(--ink)",
                      border: `2px solid ${on ? "var(--ink)" : "var(--border)"}`,
                      borderRadius: 10, fontFamily: "inherit", fontWeight: 700, cursor: "pointer",
                    }}>{o.l}</button>
                  );
                })}
              </div>

              <div style={{ fontSize: 13, fontWeight: 700, color: "var(--ink-soft)", marginBottom: 8, letterSpacing: "0.05em" }}>介面密度</div>
              <div style={{ display: "grid", gridTemplateColumns: "repeat(2, 1fr)", gap: 8 }}>
                {[{ v: "comfortable", l: "標準" }, { v: "relaxed", l: "寬鬆（更好按）" }].map(o => {
                  const on = profile.theme?.density === o.v;
                  return (
                    <button key={o.v} onClick={() => setTheme({ density: o.v })} style={{
                      padding: "12px 14px", background: on ? "var(--brand)" : "var(--paper)",
                      color: on ? "#fff" : "var(--ink)",
                      border: `2px solid ${on ? "var(--brand)" : "var(--border)"}`,
                      borderRadius: 10, fontFamily: "inherit", fontWeight: 700, cursor: "pointer",
                    }}>{o.l}</button>
                  );
                })}
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

// 小型浮動測試列 — 快速切換模擬身份
const DEV_FRIENDLY_LABELS = {
  VI:   "聽覺優先",
  HI:   "視覺閱讀",
  CI:   "逐步引導",
  LD:   "多感官",
  none: "標準",
};

const DevTestBar = () => {
  const { profile, resetProfile, applyPreset, setTheme, toggleFlag } = useA11y();
  const [collapsed, setCollapsed] = React.useState(false);
  const [preferenceOpen, setPreferenceOpen] = React.useState(false);

  // Expose openOnboarding/openPreference via events
  const simulateFirstVisit = () => {
    resetProfile();
    window.dispatchEvent(new CustomEvent("eap:open-onboarding"));
  };

  const quickSwitch = (code) => applyPreset(code);
  const cycleTextSize = () => {
    const order = ["md", "lg", "xl", "sm"];
    const idx = order.indexOf(profile.theme?.text_size || "md");
    setTheme({ text_size: order[(idx + 1) % order.length] });
  };

  if (collapsed) {
    return (
      <button onClick={() => setCollapsed(false)} aria-label="展開測試列" style={{
        position: "fixed", left: 12, bottom: 12, zIndex: 90,
        padding: "6px 10px", background: "#1a1a1a", color: "#fff",
        border: "1px solid #444", borderRadius: 6, fontSize: 11,
        fontFamily: "JetBrains Mono, monospace", cursor: "pointer", opacity: 0.7,
      }}>◉ DEV</button>
    );
  }

  return (
    <>
      <div style={{
        position: "fixed", left: 12, bottom: 12, zIndex: 90,
        background: "#1a1a1a", color: "#fff",
        borderRadius: 8, padding: "8px 10px",
        fontFamily: "JetBrains Mono, monospace", fontSize: 11,
        boxShadow: "0 8px 24px rgba(0,0,0,0.4)",
        border: "1px solid #333", opacity: 0.95,
        display: "flex", alignItems: "center", gap: 6,
        maxWidth: "calc(100vw - 24px)", flexWrap: "wrap",
      }}>
        <span style={{ color: "#ff9", fontWeight: 700, marginRight: 4 }}>◉ DEV</span>
        <span style={{ color: "#8ff", marginRight: 6 }}>
          當前：{DEV_FRIENDLY_LABELS[profile.primary] || "未設定"}
        </span>
        <button onClick={simulateFirstVisit} title="清除 profile 並重新執行首次登入問卷" style={devBtnStyle("#fff3")}>
          🔄 模擬首登
        </button>
        <span style={{ color: "#555", margin: "0 2px" }}>|</span>
        <span style={{ color: "#888" }}>快切模式：</span>
        {["VI", "HI", "CI", "LD", "none"].map(code => (
          <button key={code} onClick={() => quickSwitch(code)} title={DEV_FRIENDLY_LABELS[code]} style={{
            ...devBtnStyle(profile.primary === code ? "#ff9" : "#fff1"),
            color: profile.primary === code ? "#000" : "#fff",
            fontWeight: profile.primary === code ? 700 : 500,
          }}>
            {DEV_FRIENDLY_LABELS[code]}
          </button>
        ))}
        <span style={{ color: "#555", margin: "0 2px" }}>|</span>
        <span style={{ color: "#888" }}>CSS var：</span>
        <button onClick={cycleTextSize} title="字級循環 md→lg→xl→sm" style={devBtnStyle("#fff1")}>
          字:{(profile.theme?.text_size || "md").toUpperCase()}
        </button>
        <button onClick={() => setTheme({ contrast: profile.theme?.contrast === "high" ? "normal" : "high" })}
          style={devBtnStyle(profile.theme?.contrast === "high" ? "#ff9" : "#fff1")}>
          {profile.theme?.contrast === "high" ? "✓ 高對比" : "高對比"}
        </button>
        <button onClick={() => setTheme({ density: profile.theme?.density === "relaxed" ? "comfortable" : "relaxed" })}
          style={devBtnStyle(profile.theme?.density === "relaxed" ? "#ff9" : "#fff1")}>
          {profile.theme?.density === "relaxed" ? "✓ 寬鬆" : "寬鬆"}
        </button>
        <button onClick={() => toggleFlag("easy_read")}
          style={devBtnStyle(profile.flags?.easy_read ? "#ff9" : "#fff1")}>
          {profile.flags?.easy_read ? "✓ 易讀" : "易讀"}
        </button>
        <button onClick={() => toggleFlag("reduce_motion")}
          style={devBtnStyle(profile.flags?.reduce_motion ? "#ff9" : "#fff1")}>
          {profile.flags?.reduce_motion ? "✓ 減動畫" : "減動畫"}
        </button>
        <span style={{ color: "#555", margin: "0 2px" }}>|</span>
        <button onClick={() => setPreferenceOpen(true)} style={devBtnStyle("#fff1")}>⚙ 偏好中心</button>
        <button onClick={() => setCollapsed(true)} style={{ ...devBtnStyle("transparent"), marginLeft: 2, color: "#888" }}>×</button>
      </div>

      <PreferenceCenter
        open={preferenceOpen}
        onClose={() => setPreferenceOpen(false)}
        onReopenOnboarding={() => window.dispatchEvent(new CustomEvent("eap:open-onboarding"))}
      />
    </>
  );
};

const devBtnStyle = (bg) => ({
  background: bg, color: "#fff", border: "none",
  padding: "4px 8px", borderRadius: 4, fontFamily: "inherit",
  fontSize: 11, cursor: "pointer", whiteSpace: "nowrap",
});

Object.assign(window, { PreferenceCenter, DevTestBar });
