// Onboarding — 能力/偏好導向設計（非標籤化）
// 設計原則：
//  1. 文案用能力/偏好語言，不使用「障礙」字眼
//  2. 大圖示為主、文字為輔、字級放大
//  3. 每題右上角提供：朗讀 / 易讀 / 手語(placeholder) / 問AI
//  4. 內部仍記錄 VI/HI/CI/LD 以對應 AI Prompt 矩陣
//  5. data-attr 用中性命名，不揭露醫療分類

// 每個選項的插畫（純 SVG，色彩飽和度低但清楚）
const SceneIllustration = ({ scene, size = 96 }) => {
  const s = size;
  const common = { width: s, height: s, viewBox: "0 0 96 96", fill: "none" };
  switch (scene) {
    case "audio": return (
      <svg {...common} aria-hidden="true">
        <circle cx="48" cy="48" r="44" fill="#e8eef9" />
        <path d="M26 56 V40 a22 22 0 0 1 44 0 v16" stroke="#1a4789" strokeWidth="3.5" fill="none" strokeLinecap="round"/>
        <rect x="22" y="50" width="12" height="20" rx="3" fill="#1a4789"/>
        <rect x="62" y="50" width="12" height="20" rx="3" fill="#1a4789"/>
        <path d="M30 62 q-8 2 -8 12 M66 62 q8 2 8 12" stroke="#e8743c" strokeWidth="3" fill="none" strokeLinecap="round"/>
        <circle cx="14" cy="78" r="3" fill="#e8743c"/><circle cx="82" cy="78" r="3" fill="#e8743c"/>
      </svg>
    );
    case "visual": return (
      <svg {...common} aria-hidden="true">
        <circle cx="48" cy="48" r="44" fill="#fdf0e7"/>
        <rect x="20" y="30" width="56" height="36" rx="5" fill="#fff" stroke="#e8743c" strokeWidth="3"/>
        <rect x="26" y="38" width="22" height="4" rx="2" fill="#1a4789"/>
        <rect x="26" y="46" width="30" height="4" rx="2" fill="#1a4789"/>
        <rect x="26" y="54" width="18" height="4" rx="2" fill="#1a4789"/>
        <rect x="28" y="68" width="40" height="8" rx="3" fill="#1a4789"/>
        <text x="48" y="75" textAnchor="middle" fontSize="7" fill="#fff" fontWeight="700">字幕 CC</text>
      </svg>
    );
    case "step": return (
      <svg {...common} aria-hidden="true">
        <circle cx="48" cy="48" r="44" fill="#e3efe0"/>
        <circle cx="28" cy="48" r="9" fill="#2d7a4f"/>
        <text x="28" y="52" textAnchor="middle" fill="#fff" fontSize="11" fontWeight="800">1</text>
        <circle cx="48" cy="48" r="6" fill="#b7d4b0"/>
        <circle cx="64" cy="48" r="6" fill="#b7d4b0"/>
        <path d="M38 48 h6 M55 48 h4" stroke="#7aa08a" strokeWidth="2.5" strokeLinecap="round"/>
        <path d="M28 60 v6" stroke="#2d7a4f" strokeWidth="2.5"/>
        <path d="M22 68 l6 6 l6 -6" stroke="#2d7a4f" strokeWidth="2.5" fill="none" strokeLinecap="round" strokeLinejoin="round"/>
      </svg>
    );
    case "multi": return (
      <svg {...common} aria-hidden="true">
        <circle cx="48" cy="48" r="44" fill="#ece7f7"/>
        <circle cx="32" cy="36" r="8" fill="#5b3db5"/>
        <path d="M29 35 l2 2 l4 -4" stroke="#fff" strokeWidth="2" fill="none" strokeLinecap="round" strokeLinejoin="round"/>
        <circle cx="64" cy="36" r="8" fill="#5b3db5"/>
        <path d="M60 36 h8 M64 32 v8" stroke="#fff" strokeWidth="2" strokeLinecap="round"/>
        <circle cx="32" cy="62" r="8" fill="#5b3db5"/>
        <path d="M28 62 h8" stroke="#fff" strokeWidth="2.5" strokeLinecap="round"/>
        <circle cx="64" cy="62" r="8" fill="#5b3db5"/>
        <path d="M60 60 l4 4 l4 -4 M64 58 v8" stroke="#fff" strokeWidth="2" fill="none" strokeLinecap="round" strokeLinejoin="round"/>
        <line x1="40" y1="36" x2="56" y2="36" stroke="#9a85d8" strokeWidth="1.5" strokeDasharray="2 2"/>
        <line x1="40" y1="62" x2="56" y2="62" stroke="#9a85d8" strokeWidth="1.5" strokeDasharray="2 2"/>
        <line x1="32" y1="44" x2="32" y2="54" stroke="#9a85d8" strokeWidth="1.5" strokeDasharray="2 2"/>
        <line x1="64" y1="44" x2="64" y2="54" stroke="#9a85d8" strokeWidth="1.5" strokeDasharray="2 2"/>
      </svg>
    );
    case "standard": return (
      <svg {...common} aria-hidden="true">
        <circle cx="48" cy="48" r="44" fill="#eef1f8"/>
        <circle cx="48" cy="38" r="10" fill="#4a5875"/>
        <path d="M28 76 a20 20 0 0 1 40 0" fill="#4a5875"/>
      </svg>
    );
    case "goal-job": return (
      <svg {...common} aria-hidden="true">
        <circle cx="48" cy="48" r="44" fill="#fdf0e7"/>
        <rect x="24" y="38" width="48" height="34" rx="4" fill="#e8743c"/>
        <rect x="38" y="30" width="20" height="10" rx="2" fill="#b75422"/>
        <rect x="38" y="50" width="20" height="8" fill="#fff"/>
      </svg>
    );
    case "goal-skill": return (
      <svg {...common} aria-hidden="true">
        <circle cx="48" cy="48" r="44" fill="#e8eef9"/>
        <rect x="24" y="30" width="48" height="32" rx="3" fill="#1a4789"/>
        <rect x="28" y="34" width="40" height="24" fill="#fff"/>
        <path d="M32 44 h16 M32 50 h12" stroke="#1a4789" strokeWidth="2"/>
        <path d="M36 70 h24" stroke="#1a4789" strokeWidth="3" strokeLinecap="round"/>
      </svg>
    );
    case "goal-grow": return (
      <svg {...common} aria-hidden="true">
        <circle cx="48" cy="48" r="44" fill="#e3efe0"/>
        <path d="M48 70 V40" stroke="#2d7a4f" strokeWidth="3" strokeLinecap="round"/>
        <path d="M48 48 q-10 -6 -12 -18 q10 2 14 10" fill="#4f9666"/>
        <path d="M48 42 q10 -4 14 -14 q-10 0 -16 8" fill="#4f9666"/>
      </svg>
    );
    case "goal-career": return (
      <svg {...common} aria-hidden="true">
        <circle cx="48" cy="48" r="44" fill="#ece7f7"/>
        <path d="M26 58 l14 -14 l10 10 l20 -20" stroke="#5b3db5" strokeWidth="3.5" fill="none" strokeLinecap="round" strokeLinejoin="round"/>
        <circle cx="70" cy="34" r="5" fill="#5b3db5"/>
        <path d="M62 34 h16" stroke="#5b3db5" strokeWidth="2" strokeDasharray="2 2"/>
      </svg>
    );
    default: return <div style={{ width: s, height: s, background: "#eef1f8", borderRadius: "50%" }} />;
  }
};

// 每題右上角工具列：朗讀 / 易讀 / 手語 / 問AI
const QuestionToolbar = ({ onSpeak, onSimplify, onSign, onAskAI, speakText, stepHint }) => {
  const [toast, setToast] = React.useState(null);
  const showToast = (msg) => { setToast(msg); setTimeout(() => setToast(null), 2400); };

  const tools = [
    { icon: "volume", label: "朗讀", onClick: () => { onSpeak && onSpeak(); showToast("🔊 正在朗讀題目…"); } },
    { icon: "book", label: "易讀", onClick: () => { onSimplify && onSimplify(); showToast("📖 已切換至易讀版"); } },
    { icon: "users", label: "手語", onClick: () => showToast("🤟 手語影片版（上線前錄製）") },
    { icon: "help", label: "問 AI", onClick: () => showToast(stepHint || "💬 AI 助教：這題在問你平常比較習慣哪種學習方式。") },
  ];

  return (
    <>
      <div style={{ display: "flex", gap: 6 }}>
        {tools.map(t => (
          <button key={t.label} onClick={t.onClick} aria-label={t.label} title={t.label} style={{
            display: "inline-flex", alignItems: "center", gap: 6,
            padding: "8px 12px", minHeight: 40,
            background: "rgba(255,255,255,0.18)", color: "#fff",
            border: "1.5px solid rgba(255,255,255,0.35)", borderRadius: 10,
            fontFamily: "inherit", fontWeight: 700, fontSize: 13, cursor: "pointer",
          }}>
            <Icon name={t.icon} size={16} color="#fff" />
            {t.label}
          </button>
        ))}
      </div>
      {toast && (
        <div role="status" aria-live="polite" style={{
          position: "fixed", top: 20, left: "50%", transform: "translateX(-50%)",
          zIndex: 200, padding: "12px 20px",
          background: "var(--ink)", color: "#fff",
          borderRadius: 10, fontWeight: 700, boxShadow: "var(--shadow-lg)",
          fontSize: 15,
        }}>{toast}</div>
      )}
    </>
  );
};

const OnboardingModal = ({ onClose, onComplete }) => {
  const { applyPreset } = useA11y();
  const { speak, cancel } = useTTS();
  const [step, setStep] = React.useState(0);
  const [data, setData] = React.useState({ primary: null, secondary: [], goal: null, schedule: null, interests: [] });

  // 能力/偏好導向選項 — 內部 v 值仍保留 VI/HI/CI/LD
  const LEARN_STYLES = [
    { v: "VI",   scene: "audio",    l: "我習慣用耳朵學習",   d: "希望有語音朗讀、鍵盤操作" },
    { v: "HI",   scene: "visual",   l: "我習慣用眼睛閱讀",   d: "希望有字幕、逐字稿、圖示" },
    { v: "CI",   scene: "step",     l: "我喜歡一次一步",     d: "希望步驟清楚、用字簡單" },
    { v: "LD",   scene: "multi",    l: "我喜歡看聽做一起來", d: "多種方式輔助我學習" },
    { v: "none", scene: "standard", l: "我使用標準模式",     d: "不需要特別調整" },
  ];

  const steps = [
    {
      q: "您平常學習時，哪一種方式最輕鬆？",
      sub: "沒有標準答案。選到最接近您日常習慣的那個就好，之後都可以更改。",
      key: "primary", options: LEARN_STYLES, single: true, illustrated: true,
    },
    {
      q: "還有什麼方式對您有幫助嗎？",
      sub: "可以多選，也可以略過。這會讓介面更貼近您。",
      key: "secondary",
      options: LEARN_STYLES.filter(o => o.v !== "none"),
      multi: true, optional: true, illustrated: true,
    },
    {
      q: "您主要想透過這個平台達成什麼？",
      key: "goal", illustrated: true, options: [
        { v: "job",    scene: "goal-job",    l: "找到工作",       d: "提升就業機會" },
        { v: "skill",  scene: "goal-skill",  l: "學會數位技能",   d: "電腦、辦公軟體" },
        { v: "selfup", scene: "goal-grow",   l: "自我成長",       d: "興趣與能力培養" },
        { v: "career", scene: "goal-career", l: "轉換職涯",       d: "探索新方向" },
      ],
    },
    {
      q: "您方便學習的時段？",
      key: "schedule", options: [
        { v: "morning",   l: "上午",   d: "09:00–12:00" },
        { v: "afternoon", l: "下午",   d: "13:00–17:00" },
        { v: "evening",   l: "晚上",   d: "18:00–22:00" },
        { v: "flex",      l: "不固定", d: "依自己節奏" },
      ],
    },
    {
      q: "您對哪些主題有興趣？",
      sub: "可以多選",
      key: "interests", multi: true, optional: true, options: [
        { v: "ai",      l: "AI 工具應用" },
        { v: "office",  l: "辦公軟體" },
        { v: "design",  l: "視覺設計" },
        { v: "program", l: "程式入門" },
        { v: "soft",    l: "溝通表達" },
        { v: "cs",      l: "客戶服務" },
      ],
    },
  ];

  const current = steps[step];
  const isMulti = current.multi;
  const val = data[current.key];

  // 組合本題的朗讀內容（題幹 + 副說 + 選項）
  const speakText = React.useMemo(() => {
    const intro = step === 0 ? "歡迎！讓我們為您調整介面。" : "";
    const opts = current.options.map((o, i) => `第${i + 1}選，${o.l}${o.d ? "。" + o.d : ""}`).join("。");
    return `${intro}${current.q}${current.sub ? "。" + current.sub : ""}。${opts}。`;
  }, [step]);

  // 關鍵：開啟 Onboarding 及每次換題時自動朗讀
  // 本模組不依賴 tts_default flag（Onboarding 本身就是引導場景，所有使用者都需要引導）
  // 延遲拉長至 500ms，並先 cancel 避免佇列被吞
  React.useEffect(() => {
    cancel();
    const t = setTimeout(() => speak(speakText), 500);
    return () => { clearTimeout(t); };
  }, [speakText]);
  const canAdvance = current.optional || (isMulti ? val.length > 0 : val !== null);
  const isLast = step === steps.length - 1;

  const select = (v) => {
    if (isMulti) {
      const arr = data[current.key] || [];
      setData({ ...data, [current.key]: arr.includes(v) ? arr.filter(x => x !== v) : [...arr, v] });
    } else {
      setData({ ...data, [current.key]: v });
      setTimeout(() => { if (!isLast) setStep(s => s + 1); }, 260);
    }
  };

  const finish = () => {
    applyPreset(data.primary || "none", {
      secondary: data.secondary, goal: data.goal, schedule: data.schedule, interests: data.interests,
    });
    onComplete && onComplete(data);
  };

  return (
    <div style={{
      position: "fixed", inset: 0, zIndex: 100,
      background: "rgba(15,26,46,0.6)", backdropFilter: "blur(6px)",
      display: "flex", alignItems: "center", justifyContent: "center",
      padding: 16, animation: "fadeIn 200ms",
    }}>
      <style>{`@keyframes fadeIn{from{opacity:0}to{opacity:1}}@keyframes slideUp{from{transform:translateY(24px);opacity:0}to{transform:none;opacity:1}}`}</style>
      <div role="dialog" aria-modal="true" aria-labelledby="ob-title" style={{
        width: "100%", maxWidth: 860,
        maxHeight: "calc(100vh - 32px)",
        display: "flex", flexDirection: "column",
        background: "var(--paper)", borderRadius: 20,
        boxShadow: "var(--shadow-lg)",
        animation: "slideUp 320ms cubic-bezier(0.2, 0.8, 0.2, 1)",
        overflow: "hidden",
        fontSize: 18,
      }}>
        <div style={{
          padding: "16px 24px",
          background: "linear-gradient(135deg, var(--brand) 0%, var(--brand-600) 100%)",
          color: "#fff", display: "flex", alignItems: "center", gap: 14, flexWrap: "wrap",
          flexShrink: 0,
        }}>
          <div style={{ width: 48, height: 48, borderRadius: 12, background: "rgba(255,255,255,0.2)", display: "flex", alignItems: "center", justifyContent: "center" }}>
            <Icon name="sparkle" size={26} color="#fff" />
          </div>
          <div style={{ flex: 1, minWidth: 220 }}>
            <div id="ob-title" style={{ fontWeight: 800, fontSize: 20 }}>歡迎！讓我們為您調整介面</div>
            <div style={{ fontSize: 13, opacity: 0.9, marginTop: 4 }}>只要回答幾個問題，介面會自動適合您</div>
          </div>
          <QuestionToolbar
            onSpeak={() => speak(speakText)}
            speakText={speakText}
            stepHint={`本題要問您：${current.q}`}
          />
          <button onClick={onClose} aria-label="關閉" style={{
            width: 44, height: 44, borderRadius: 10,
            background: "rgba(255,255,255,0.18)", border: "1.5px solid rgba(255,255,255,0.3)", color: "#fff",
            display: "flex", alignItems: "center", justifyContent: "center",
          }}><Icon name="x" size={20} color="#fff" /></button>
        </div>

        {/* Progress — 文字 + 視覺步驟 */}
        <div style={{ padding: "12px 24px", background: "var(--bg)", borderBottom: "1px solid var(--border)", flexShrink: 0 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 8 }}>
            <span style={{ fontSize: 14, fontWeight: 700, color: "var(--ink-soft)" }}>
              第 {step + 1} 步／共 {steps.length} 步
            </span>
            <span style={{ fontSize: 13, color: "var(--muted)" }}>· 還剩約 {(steps.length - step - 1) * 20} 秒</span>
          </div>
          <div style={{ display: "flex", gap: 4 }}>
            {steps.map((_, i) => (
              <div key={i} style={{
                flex: 1, height: 8, borderRadius: 4,
                background: i < step ? "var(--ok)" : i === step ? "var(--brand)" : "var(--border)",
                transition: "all 300ms",
              }} />
            ))}
          </div>
        </div>

        <div style={{ padding: "clamp(14px, 2vh, 22px) 28px", flex: 1, overflowY: "auto", minHeight: 0 }}>
          <h3 style={{ margin: 0, fontSize: "clamp(20px, 2.6vh, 26px)", fontWeight: 800, letterSpacing: "-0.02em", lineHeight: 1.3, color: "var(--ink)" }}>
            {current.q}
          </h3>
          {current.sub && <p style={{ color: "var(--ink-soft)", fontSize: "clamp(13px, 1.7vh, 16px)", margin: "8px 0 0", lineHeight: 1.5 }}>{current.sub}</p>}
          {isMulti && (
            <p style={{ color: "var(--brand)", fontSize: 14, margin: "8px 0 0", fontWeight: 700 }}>
              已選 {val.length} 項{current.optional ? "（可略過）" : ""}
            </p>
          )}

          <div style={{
            marginTop: 16,
            display: "grid",
            gridTemplateColumns: current.illustrated
              ? `repeat(${current.options.length <= 3 ? current.options.length : Math.ceil(current.options.length / 2)}, minmax(0, 1fr))`
              : (isMulti && current.options.length > 4 ? "repeat(auto-fit, minmax(140px, 1fr))" : "1fr"),
            gap: 10,
          }}>
            {current.options.map(opt => {
              const selected = isMulti ? val.includes(opt.v) : val === opt.v;
              const illustSize = current.options.length <= 3 ? 88 : 64;
              return (
                <button
                  key={opt.v}
                  onClick={() => select(opt.v)}
                  aria-pressed={selected}
                  style={{
                    padding: current.illustrated ? "clamp(10px, 1.6vh, 16px) 14px clamp(12px, 1.8vh, 18px)" : "14px 18px",
                    background: selected ? "var(--brand-50)" : "var(--paper)",
                    border: `3px solid ${selected ? "var(--brand)" : "var(--border)"}`,
                    borderRadius: 14,
                    textAlign: current.illustrated ? "center" : "left",
                    fontFamily: "inherit", cursor: "pointer", transition: "all 150ms",
                    display: "flex", flexDirection: current.illustrated ? "column" : "row",
                    alignItems: "center", gap: current.illustrated ? "clamp(6px, 1vh, 10px)" : 14,
                    minHeight: current.illustrated ? 0 : 60,
                    position: "relative",
                  }}
                >
                  {selected && (
                    <div style={{
                      position: "absolute", top: 10, right: 10,
                      width: 28, height: 28, borderRadius: 999,
                      background: "var(--brand)", color: "#fff",
                      display: "flex", alignItems: "center", justifyContent: "center",
                    }}><Icon name="check" size={16} color="#fff" stroke={3} /></div>
                  )}
                  {current.illustrated && opt.scene && (
                    <div style={{ width: "clamp(56px, 10vh, 88px)", aspectRatio: "1", display: "flex", alignItems: "center", justifyContent: "center" }}>
                      <SceneIllustration scene={opt.scene} size={illustSize} />
                    </div>
                  )}
                  {!current.illustrated && (
                    <div style={{
                      width: 28, height: 28, flexShrink: 0,
                      borderRadius: isMulti ? 6 : "50%",
                      border: `2.5px solid ${selected ? "var(--brand)" : "var(--border-strong)"}`,
                      background: selected ? "var(--brand)" : "transparent",
                      display: "flex", alignItems: "center", justifyContent: "center",
                    }}>{selected && <Icon name="check" size={16} stroke={3} color="#fff" />}</div>
                  )}
                  <div style={{ flex: 1, textAlign: current.illustrated ? "center" : "left" }}>
                    <div style={{ fontWeight: 800, fontSize: current.illustrated ? "clamp(14px, 1.9vh, 17px)" : 17, color: "var(--ink)", lineHeight: 1.3 }}>{opt.l}</div>
                    {opt.d && <div style={{ fontSize: current.illustrated ? "clamp(11px, 1.5vh, 13px)" : 13, color: "var(--ink-soft)", marginTop: 4, lineHeight: 1.45 }}>{opt.d}</div>}
                  </div>
                </button>
              );
            })}
          </div>
        </div>

        <div style={{
          padding: "14px 24px", borderTop: "1px solid var(--border)", background: "var(--bg)",
          display: "flex", justifyContent: "space-between", alignItems: "center", gap: 12, flexWrap: "wrap",
          flexShrink: 0,
        }}>
          <Button variant="ghost" onClick={() => step > 0 ? setStep(step - 1) : onClose()}>
            {step > 0 ? "← 上一步" : "稍後再答"}
          </Button>
          <div style={{ display: "flex", gap: 8 }}>
            {current.optional && !isLast && <Button variant="ghost" onClick={() => setStep(step + 1)}>略過這題</Button>}
            <Button size="lg" onClick={() => { if (isLast) finish(); else setStep(step + 1); }} disabled={!canAdvance}>
              {isLast ? "完成，開始使用 →" : "下一步 →"}
            </Button>
          </div>
        </div>
      </div>
    </div>
  );
};

const OnboardingSuccessToast = ({ profile, onClose }) => {
  React.useEffect(() => {
    const t = setTimeout(onClose, 6000);
    return () => clearTimeout(t);
  }, [onClose]);
  const preset = A11Y_PRESETS[profile.primary] || A11Y_PRESETS.none;
  // Public-friendly label (避免揭露醫療分類)
  const FRIENDLY_LABELS = {
    VI: "聽覺優先模式",
    HI: "視覺閱讀模式",
    CI: "逐步引導模式",
    LD: "多感官輔助模式",
    none: "標準模式",
  };
  return (
    <div style={{
      position: "fixed", top: 90, right: 20, zIndex: 95,
      width: 380, background: "var(--paper)",
      border: "2px solid var(--ok)", borderRadius: 14,
      boxShadow: "var(--shadow-lg)",
      animation: "slideUp 300ms cubic-bezier(0.2,0.8,0.2,1)",
      overflow: "hidden",
    }}>
      <div style={{ background: "var(--ok)", color: "#fff", padding: "12px 16px", display: "flex", alignItems: "center", gap: 8 }}>
        <Icon name="check" size={20} color="#fff" stroke={3} />
        <span style={{ fontWeight: 800, fontSize: 16 }}>已為您調整好介面</span>
      </div>
      <div style={{ padding: 18 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 12 }}>
          <div style={{
            width: 48, height: 48, borderRadius: 12, background: "var(--brand-50)",
            display: "flex", alignItems: "center", justifyContent: "center",
          }}><Icon name={preset.icon} size={24} color="var(--brand)" /></div>
          <div>
            <div style={{ fontSize: 13, color: "var(--muted)" }}>目前使用</div>
            <div style={{ fontWeight: 800, fontSize: 17 }}>{FRIENDLY_LABELS[profile.primary] || "標準模式"}</div>
          </div>
        </div>
        <div style={{ fontSize: 14, color: "var(--ink-2)", lineHeight: 1.6, marginBottom: 12 }}>
          之後都可以在右上角「<b style={{ color: "var(--brand)" }}>偏好設定</b>」裡微調或重新設定。
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { OnboardingModal, OnboardingSuccessToast });
