/* ═══════════════════════════════════════════
   MECHANISM QUIZ v5 — Data layer
   - 8 questions with mixed weights
   - Healthy option also participates in shuffle (mode A)
   - Progressive narrative + final narrative
   ═══════════════════════════════════════════ */

const M = {
  prediction:  { key:"prediction",  label:"預測",     ep:"EP.01", color:"#7B8FB2", url:"https://mechanism.seproject.me/ep1-prediction.html",            short:"大腦用「上一次」預測「下一次」", desc:"你的大腦很擅長用過去推測未來。但「上一次不好」不等於「這一次也不會好」。預測一旦改變，壞心情就像烏雲散去。" },
  emotion:     { key:"emotion",     label:"情緒誤解", ep:"EP.02", color:"#C4897A", url:"https://mechanism.seproject.me/ep2-emotions.html",              short:"壓住情緒，不等於處理了",        desc:"壓抑情緒就像一邊踩煞車一邊踩油門。費力，卻不前進。被忽略的標記，並不會消失。" },
  rumination:  { key:"rumination",  label:"反芻",     ep:"EP.03", color:"#9B89B6", url:"https://mechanism.seproject.me/ep3-rumination.html",            short:"同一首歌，循環播放中",          desc:"不是你意志力不夠。是大腦把煩惱做成了單曲，按下了循環播放。好消息——有暫停鍵。" },
  attribution: { key:"attribution", label:"錯誤歸因", ep:"EP.04", color:"#C4A87A", url:"https://mechanism.seproject.me/ep4-attribution-language.html", short:"原因接錯了，結論就歪了",        desc:"不喜歡一位老師 → 不喜歡一個學科 → 覺得自己不行。每鬆開一個錯誤歸因，就鬆開一串。" },
  language:    { key:"language",    label:"語言模式", ep:"EP.04", color:"#8BAA7E", url:"https://mechanism.seproject.me/ep4-attribution-language.html", short:"「就是」「永遠」「不可能」",     desc:"這些詞聽起來像真理，其實是壓縮過的快捷鍵。壓縮掉了條件、情境、和時間。" },
  // ↑ script color bumped chroma so it sits beside the other 5
  script:      { key:"script",      label:"隱形劇本", ep:"EP.05", color:"#9B8AA8", url:"https://mechanism.seproject.me/ep5-script.html",                short:"照著一個你沒讀過的劇本走",      desc:"「到了這個年紀應該⋯⋯」——劇本有問題，你卻以為自己沒演好。" },
};
const MKEYS = Object.keys(M);

// ─── Combination narratives ───
const NARR = {
  prediction:  { verb:"預測壞的結果",                  link:"這些預測大多來自過去的經驗——但上一次不等於這一次。" },
  emotion:     { verb:"壓住自己的感受",                link:"被壓下去的情緒沒有消失，它們在背景持續運轉。" },
  rumination:  { verb:"把念頭做成單曲循環播放",        link:"播放器一直轉，讓其他齒輪的影響被放大了。" },
  attribution: { verb:"把原因接到自己身上",            link:"原因一接錯，後面的結論就全跟著歪。" },
  language:    { verb:"用「就是」「永遠」這些快捷鍵描述自己", link:"這些詞把複雜的情況壓縮成不可動搖的結論。" },
  script:      { verb:"照著一個沒讀過的劇本走",        link:"劇本在背後運作，影響你怎麼看待眼前的事。" },
};

function buildNarrative(keys) {
  if (keys.length === 0) return "";
  if (keys.length === 1) {
    return `你的煩惱裡，最常出現的是「${M[keys[0]].label}」——${NARR[keys[0]].verb}，${NARR[keys[0]].link}`;
  }
  if (keys.length === 2) {
    return `你的煩惱裡有兩個齒輪特別活躍——一個在${NARR[keys[0]].verb}，另一個在${NARR[keys[1]].verb}，它們互相帶著轉，看見了就不一樣了。`;
  }
  return `你的煩惱裡有幾個齒輪在互相帶動——一個在${NARR[keys[0]].verb}，一個在${NARR[keys[1]].verb}，還有一個在${NARR[keys[2]].verb}，它們一直在轉著，現在你看見了。`;
}

// Mid-quiz progressive feedback — surfaces once enough signal exists
function buildProgressHint(scores) {
  const entries = MKEYS.map(k => ({ k, v: scores[k] || 0 })).filter(e => e.v > 0);
  if (entries.length === 0) return "";
  entries.sort((a,b) => b.v - a.v);
  const top = entries[0];
  if (top.v < 3) return "";
  return `目前看起來，「${M[top.k].label}」這顆齒輪比較活躍。`;
}

// ─── Questions — mixed weights for richer signal ───
const QUESTIONS = [
  {
    situation: "煩惱浮上來的時候，\n你腦中最先出現的——",
    options: [
      { text: "一個還沒發生的畫面",            scores: { prediction: 3 } },
      { text: "同一個念頭，又來了",             scores: { rumination: 3 } },
      { text: "「我不應該有這種感覺」",         scores: { emotion: 2, language: 1 } },
      { text: "還好，通常不會太久",             scores: {} },
    ],
  },
  {
    situation: "有人跟你說「想開一點」。\n你心裡覺得他不懂。\n\n在那個煩躁底下，比較像——",
    options: [
      { text: "我也想，但腦袋停不下來",         scores: { rumination: 3 } },
      { text: "這件事本來就不該是這樣",         scores: { script: 2, language: 1 } },
      { text: "嗯⋯⋯好吧（其實不好）",         scores: { emotion: 3 } },
      { text: "也是，或許沒我想的那麼嚴重",     scores: {} },
    ],
  },
  {
    situation: "半夜突然醒來，\n腦袋裡在轉的是——",
    options: [
      { text: "明天或以後可能出錯的事",                  scores: { prediction: 3 } },
      { text: "「都是因為我⋯⋯」反覆想自己哪裡做錯",     scores: { attribution: 3 } },
      { text: "「我永遠都是這樣，不會變了」",             scores: { language: 2, prediction: 1 } },
      { text: "通常翻個身就睡回去了",                    scores: {} },
    ],
  },
  {
    situation: "有人誇你做得好，\n你心裡的第一個反應——",
    options: [
      { text: "腦袋開始轉那個沒做好的部分",     scores: { rumination: 2, language: 1 } },
      { text: "做得好是應該的吧",                scores: { script: 3 } },
      { text: "「我就是運氣好而已」",            scores: { language: 2, attribution: 1 } },
      { text: "謝謝，蠻開心的",                  scores: {} },
    ],
  },
  {
    situation: "一個新的機會出現了，\n最先冒出的念頭——",
    options: [
      { text: "上次類似的事沒成功⋯⋯",          scores: { prediction: 3 } },
      { text: "到了我這個階段，應該要⋯⋯",       scores: { script: 2, language: 1 } },
      { text: "不敢太高興，怕到時候失望",        scores: { emotion: 2, prediction: 1 } },
      { text: "有意思，可以試試看",              scores: {} },
    ],
  },
  {
    situation: "跟在乎的人起衝突之後——",
    options: [
      { text: "在腦中重播，想著「我應該那樣說」",  scores: { rumination: 3 } },
      { text: "告訴自己算了、不要想了",            scores: { emotion: 3 } },
      { text: "一定是我的問題",                    scores: { attribution: 2, language: 1 } },
      { text: "給彼此一點時間，再找機會談",        scores: {} },
    ],
  },
  {
    situation: "你在意的一件事，\n沒有照計畫走——",
    options: [
      { text: "「我就知道會這樣」",              scores: { prediction: 2, language: 1 } },
      { text: "「果然不行，我就是做不到」",      scores: { language: 2, attribution: 1 } },
      { text: "早就不該抱期待",                  scores: { script: 2, prediction: 1 } },
      { text: "看看哪裡可以調整",                scores: {} },
    ],
  },
  {
    situation: "回想最近一次，\n反覆出現在腦中的煩惱——",
    options: [
      { text: "同一段內心對話，播了很多遍",      scores: { rumination: 3 } },
      { text: "覺得是自己的問題造成的",           scores: { attribution: 2, language: 1 } },
      { text: "「反正不可能改變了」",             scores: { language: 2, script: 1 } },
      { text: "最近沒什麼特別卡的",               scores: {} },
    ],
  },
];

// Per-mechanism max for normalization
const MAX_S = {};
MKEYS.forEach(k => {
  let t = 0;
  QUESTIONS.forEach(q => { t += Math.max(0, ...q.options.map(o => (o.scores && o.scores[k]) || 0)); });
  MAX_S[k] = t || 1;
});

const LOW_T = 5;

// ─── Full shuffle (healthy option also participates) ───
function shuffleOpts(opts){
  const a = [...opts];
  for (let i = a.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [a[i], a[j]] = [a[j], a[i]];
  }
  return a;
}

Object.assign(window, {
  M, MKEYS, NARR, QUESTIONS, MAX_S, LOW_T,
  buildNarrative, buildProgressHint, shuffleOpts,
});
