// Color Vision Deficiency (CVD) Simulator
// Uses SVG feColorMatrix filters applied to <body> to simulate:
//   - Deuteranopia (綠色盲 ~6% 男性)
//   - Protanopia   (紅色盲 ~1%)
//   - Tritanopia   (藍色盲 <0.01%)
//   - Achromatopsia(全色盲 ~0.003%)
// Values from Machado et al. 2009 / Brettel-Viénot-Mollon approximations.

const CVD_MATRICES = {
  normal:        "1 0 0 0 0  0 1 0 0 0  0 0 1 0 0  0 0 0 1 0",
  deuteranopia:  "0.625 0.375 0 0 0  0.7 0.3 0 0 0  0 0.3 0.7 0 0  0 0 0 1 0",
  protanopia:    "0.567 0.433 0 0 0  0.558 0.442 0 0 0  0 0.242 0.758 0 0  0 0 0 1 0",
  tritanopia:    "0.95 0.05 0 0 0  0 0.433 0.567 0 0  0 0.475 0.525 0 0  0 0 0 1 0",
  achromatopsia: "0.299 0.587 0.114 0 0  0.299 0.587 0.114 0 0  0.299 0.587 0.114 0 0  0 0 0 1 0",
};

const CVD_MODES = [
  { k: "normal",        l: "正常視覺",          sub: "對照組",            pop: "~92%" },
  { k: "deuteranopia",  l: "綠色盲 (Deuteranopia)", sub: "最常見",        pop: "~6%" },
  { k: "protanopia",    l: "紅色盲 (Protanopia)",   sub: "紅綠混淆",       pop: "~1%" },
  { k: "tritanopia",    l: "藍色盲 (Tritanopia)",   sub: "藍黃混淆",       pop: "<0.01%" },
  { k: "achromatopsia", l: "全色盲 (Achromatopsia)",sub: "只看見灰階",     pop: "~0.003%" },
];

const CVDFilterDefs = () => (
  <svg width="0" height="0" style={{ position: "absolute" }} aria-hidden="true">
    <defs>
      {Object.entries(CVD_MATRICES).map(([k, v]) => (
        <filter key={k} id={`cvd-${k}`}>
          <feColorMatrix type="matrix" values={v} />
        </filter>
      ))}
    </defs>
  </svg>
);

const CVDSimulator = () => {
  const [open, setOpen] = React.useState(false);
  const [mode, setMode] = React.useState("normal");
  const [showTest, setShowTest] = React.useState(false);

  React.useEffect(() => {
    // Apply filter to #root, not body (so our own toolbar stays unaffected)
    const root = document.getElementById("root");
    if (!root) return;
    root.style.filter = mode === "normal" ? "none" : `url(#cvd-${mode})`;
    return () => { root.style.filter = "none"; };
  }, [mode]);

  return (
    <>
      <CVDFilterDefs />

      {/* Floating launcher — upper right, below topnav */}
      <button
        onClick={() => setOpen(!open)}
        aria-label="色盲檢測工具"
        style={{
          position: "fixed", top: 84, right: 20, zIndex: 85,
          minWidth: 56, minHeight: 56, padding: "0 18px",
          borderRadius: 14,
          background: mode !== "normal" ? "#8b2555" : "var(--ink)",
          color: "#fff", border: "3px solid #fff",
          display: "flex", alignItems: "center", gap: 8,
          fontFamily: "inherit", fontWeight: 800, fontSize: 14,
          boxShadow: "var(--shadow-lg)", cursor: "pointer",
        }}
      >
        <Icon name="eye" size={20} color="#fff" />
        {mode !== "normal" && <span>CVD: {CVD_MODES.find(m => m.k === mode)?.k}</span>}
      </button>

      {open && (
        <div style={{
          position: "fixed", top: 150, right: 20, zIndex: 85,
          width: 380, maxHeight: "75vh", overflow: "auto",
          background: "#fff", borderRadius: 16,
          boxShadow: "var(--shadow-lg)",
          border: "2px solid var(--border-strong)",
          animation: "popIn 200ms ease",
        }}>
          <style>{`@keyframes popIn{from{transform:translateY(8px);opacity:0}to{transform:none;opacity:1}}`}</style>
          <div style={{ padding: "16px 20px", background: "var(--ink)", color: "#fff", display: "flex", alignItems: "center", gap: 10, borderRadius: "14px 14px 0 0" }}>
            <Icon name="eye" size={20} color="#fff" />
            <div style={{ flex: 1 }}>
              <div style={{ fontWeight: 800 }}>色盲模擬檢測</div>
              <div style={{ fontSize: 11, opacity: 0.75 }}>設計師專用 · 非使用者選項</div>
            </div>
            <button onClick={() => setOpen(false)} aria-label="關閉" style={{
              width: 32, height: 32, borderRadius: 8,
              background: "rgba(255,255,255,0.15)", border: "none", color: "#fff",
              display: "flex", alignItems: "center", justifyContent: "center",
            }}><Icon name="x" size={16} color="#fff" /></button>
          </div>

          <div style={{ padding: 16 }}>
            <div style={{ fontSize: 12, color: "var(--muted)", lineHeight: 1.6, marginBottom: 14, padding: 10, background: "var(--bg)", borderRadius: 8 }}>
              切換以下選項會對全站內容套用即時色彩模擬。用於檢查「是否只靠顏色傳達資訊」。
            </div>

            {CVD_MODES.map(m => (
              <button
                key={m.k}
                onClick={() => setMode(m.k)}
                style={{
                  width: "100%", textAlign: "left",
                  padding: "12px 14px", marginBottom: 6,
                  background: mode === m.k ? "var(--brand-50)" : "#fff",
                  border: `2px solid ${mode === m.k ? "var(--brand)" : "var(--border)"}`,
                  borderRadius: 10,
                  fontFamily: "inherit", cursor: "pointer",
                  display: "flex", alignItems: "center", gap: 12,
                }}
              >
                <span style={{
                  width: 28, height: 28, borderRadius: 6,
                  background: mode === m.k ? "var(--brand)" : "var(--bg-2)",
                  color: mode === m.k ? "#fff" : "var(--ink-soft)",
                  display: "flex", alignItems: "center", justifyContent: "center",
                  fontWeight: 800,
                }}>{mode === m.k ? <Icon name="check" size={16} color="#fff" stroke={3} /> : "·"}</span>
                <span style={{ flex: 1 }}>
                  <span style={{ display: "block", fontWeight: 700, fontSize: 14, color: "var(--ink)" }}>{m.l}</span>
                  <span style={{ fontSize: 11, color: "var(--muted)" }}>{m.sub} · 約 {m.pop} 人口</span>
                </span>
              </button>
            ))}

            <button
              onClick={() => setShowTest(!showTest)}
              style={{
                width: "100%", marginTop: 12, padding: "10px 14px",
                background: showTest ? "var(--accent)" : "var(--bg-2)",
                color: showTest ? "#fff" : "var(--ink-2)",
                border: "none", borderRadius: 8, fontFamily: "inherit", fontWeight: 700,
                cursor: "pointer", fontSize: 13,
              }}
            >
              {showTest ? "隱藏" : "顯示"}色票比對板
            </button>

            {showTest && <CVDTestSwatches />}
          </div>
        </div>
      )}

      {/* Mode badge banner at top when active */}
      {mode !== "normal" && (
        <div style={{
          position: "fixed", top: 72, left: 0, right: 0, zIndex: 84,
          background: "#8b2555", color: "#fff",
          padding: "6px 20px", textAlign: "center",
          fontSize: 12, fontWeight: 700, letterSpacing: "0.05em",
        }}>
          ◉ 正在模擬：{CVD_MODES.find(m => m.k === mode)?.l} · 此為設計檢測畫面
        </div>
      )}
    </>
  );
};

// Swatch panel: shows current design tokens as colorblind sees them
const CVDTestSwatches = () => (
  <div style={{ marginTop: 12, padding: 12, background: "var(--bg)", borderRadius: 10 }}>
    <div style={{ fontSize: 11, fontWeight: 800, color: "var(--ink-soft)", marginBottom: 8, letterSpacing: "0.08em" }}>
      設計系統色票（檢視各狀態是否仍可區辨）
    </div>
    <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 6 }}>
      {[
        { c: "#1a4789", l: "Brand" },
        { c: "#e8743c", l: "Accent" },
        { c: "#2d7a4f", l: "OK 綠" },
        { c: "#b87d0b", l: "Warn 黃" },
        { c: "#b42323", l: "Danger 紅" },
        { c: "#0d6b88", l: "Caption 青" },
      ].map(s => (
        <div key={s.c} style={{ textAlign: "center" }}>
          <div style={{ height: 36, background: s.c, borderRadius: 6, border: "1px solid rgba(0,0,0,0.1)" }} />
          <div style={{ fontSize: 10, color: "var(--muted)", marginTop: 2 }}>{s.l}</div>
          <div style={{ fontFamily: "JetBrains Mono, monospace", fontSize: 9, color: "var(--ink)" }}>{s.c}</div>
        </div>
      ))}
    </div>
    <div style={{ marginTop: 10, fontSize: 11, color: "var(--muted)", lineHeight: 1.6 }}>
      ✓ 每色皆搭配圖示與文字，不單獨依賴顏色
    </div>
  </div>
);

Object.assign(window, { CVDSimulator, CVDFilterDefs });
