// ==UserScript==
// @name         Kahoot AI Auto-Answer (Groq Improved v4.8) - Multi-Select Fix + Enhanced Slider
// @namespace    http://tampermonkey.net/
// @version      4.8
// @description  AI answers MCQ (incl. multi-select), typing, slider, puzzle on Kahoot using Groq LLaMA-4 with smart detection and better response handling
// @match        https://kahoot.it/instructions
// @grant        none
// ==/UserScript==

(function () {
  'use strict';

  const GROQ_API_KEY = '<TRUFFLEHOG_REDACTED_GROQ>';
  const MODEL = 'meta-llama/llama-4-scout-17b-16e-instruct';
  const AUTO_SUBMIT_TYPING = true;
  const AUTO_SET_SLIDER = true;

  let pastedScript = localStorage.getItem('kahootTranscript') || '';
  let lastQuestion = '', timerInterval = null, timerSeconds = 0;

  const uiBox = document.createElement('div');
  Object.assign(uiBox.style, {
    position: 'fixed',
    top: '60px',
    right: '20px',
    width: '340px',
    maxHeight: '480px',
    backgroundColor: '#1e1e2f',
    color: '#eee',
    borderRadius: '10px',
    border: '2px solid #4caf50',
    padding: '16px 20px',
    zIndex: 99999,
    fontFamily: "'Segoe UI', Tahoma, Geneva, Verdana, sans-serif",
    fontSize: '14px',
    boxShadow: '0 4px 15px rgba(0, 0, 0, 0.3)',
    overflowY: 'auto',
    userSelect: 'none',
  });

  uiBox.innerHTML = `
    <h3 style="margin:0 0 12px 0; text-align:center; color:#4caf50; font-weight:700;">🤖 Kahoot AI Assistant</h3>
    <textarea id="scriptBox" rows="6" placeholder="Paste transcript here..." style="
      width: 100%;
      resize: vertical;
      border-radius: 6px;
      border: 1px solid #444;
      background-color: #2c2c3f;
      color: #ddd;
      padding: 8px 10px;
      font-size: 13px;
      font-family: monospace;
      box-sizing: border-box;
      outline: none;
      transition: border-color 0.3s ease;
    ">${pastedScript}</textarea>
    <button id="loadScript" style="
      margin-top: 12px;
      width: 100%;
      padding: 10px 0;
      background-color: #4caf50;
      border: none;
      border-radius: 6px;
      font-size: 15px;
      font-weight: 600;
      color: #fff;
      cursor: pointer;
      transition: background-color 0.25s ease;
    ">📥 Load Transcript</button>
    <div style="margin-top: 14px; display: flex; justify-content: space-between; align-items: center;">
      <div><strong>API Status:</strong> <span id="apiStatus" style="color: #aaa;">Idle</span></div>
      <div><strong>Timer:</strong> <span id="timer">0s</span></div>
    </div>
    <hr style="margin: 14px 0; border-color: #333;" />
    <div id="questionBox" style="
      min-height: 60px;
      font-weight: 600;
      color: #81c784;
      line-height: 1.3;
      max-height: 140px;
      overflow-y: auto;
      padding-right: 6px;
      font-size: 14px;
    "><i>Waiting for next question...</i></div>
    <div id="answerBox" style="
      margin-top: 10px;
      color: #aed581;
      font-size: 14px;
      white-space: pre-wrap;
      min-height: 40px;
      max-height: 120px;
      overflow-y: auto;
    "></div>
  `;

  document.body.appendChild(uiBox);

  document.getElementById('loadScript').onclick = () => {
    pastedScript = document.getElementById('scriptBox').value.trim();
    localStorage.setItem('kahootTranscript', pastedScript);
    const status = document.getElementById('apiStatus');
    if (pastedScript) {
      status.innerText = 'Transcript Loaded ✅';
      status.style.color = '#4caf50';
    } else {
      status.innerText = 'No Transcript ❌';
      status.style.color = '#e53935';
    }
  };

  function startTimer() {
    clearInterval(timerInterval);
    timerSeconds = 0;
    document.getElementById('timer').innerText = `0s`;
    timerInterval = setInterval(() => {
      timerSeconds++;
      document.getElementById('timer').innerText = `${timerSeconds}s`;
    }, 1000);
  }

  async function queryAI(question, choices = [], type = "MCQ", retry = false) {
    const status = document.getElementById('apiStatus');
    if (!pastedScript || !GROQ_API_KEY) {
      status.innerText = '❌ Transcript/API key missing';
      status.style.color = '#e53935';
      return null;
    }

    status.innerText = 'Thinking... 🤔';
    status.style.color = '#fbc02d';

    const prompt = `You are an AI answering a Kahoot quiz using the following transcript:
"""
${pastedScript}
"""
Question: ${question}
Type: ${type}
${choices.length ? `Choices:\n${choices.map((c, i) => `${i + 1}. ${c}`).join('\n')}` : ''}

Respond ONLY with:
- For single or multi-select MCQ: space-separated numbers (e.g. "2" or "1 3").
- For typing: the exact word or phrase.
- For slider: a number.
- For puzzle: correct order like "3 1 4 2".
Answer:
`;

    try {
      const res = await fetch('https://api.groq.com/openai/v1/chat/completions', {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${GROQ_API_KEY}`,
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          model: MODEL,
          messages: [{ role: 'user', content: prompt }]
        })
      });

      const data = await res.json();
      const content = data?.choices?.[0]?.message?.content?.trim();
      if (!content) throw new Error('No content from Groq');

      status.innerText = '✅ Answered';
      status.style.color = '#4caf50';
      document.getElementById('answerBox').innerText = content;
      return content;
    } catch (e) {
      console.warn('❌ API error:', e);
      if (!retry) return await queryAI(question, choices, type, true);
      status.innerText = '❌ API Failed';
      status.style.color = '#e53935';
      document.getElementById('answerBox').innerText = '❌ Failed to reach Groq.';
      return null;
    }
  }

  function sortChoicesVisually(buttons) {
    return Array.from(buttons).sort((a, b) =>
      a.getBoundingClientRect().top - b.getBoundingClientRect().top ||
      a.getBoundingClientRect().left - b.getBoundingClientRect().left
    );
  }

  function detectQuestion() {
    try {
      const qnEl = document.querySelector("div[class*='question-title'] span");
      const qn = qnEl?.innerText?.trim();
      if (!qn || qn === lastQuestion) return;

      const choicesText = Array.from(document.querySelectorAll("button[class*='choice'] p"))
        .map(c => c.innerText.trim())
        .filter(text => text.length > 0);

      const buttons = sortChoicesVisually(document.querySelectorAll("button[class*='choice']"));
      const isMultiSelect = document.querySelectorAll("button[class*='choice'][aria-pressed]").length > 0;

      if (choicesText.length >= 2 && buttons.length >= 2) {
        lastQuestion = qn;
        startTimer();
        const typeLabel = isMultiSelect ? "Multi-Select MCQ" : "Single-Select MCQ";

        document.getElementById('questionBox').innerHTML = `<b>Q (${typeLabel}):</b> ${qn}<br><b>Choices:</b><ol style="padding-left:20px; margin:6px 0 0 0;">${choicesText.map(c => `<li>${c}</li>`).join('')}</ol>`;

        queryAI(qn, choicesText, typeLabel).then(answer => {
          if (!answer) return;
          const matches = [...new Set((answer.match(/\b\d{1,2}\b/g) || []).filter(n => parseInt(n) <= choicesText.length))];

          if (matches.length > 0) {
            matches.forEach((num, index) => {
              const idx = parseInt(num) - 1;
              const btn = buttons[idx];
              if (btn) {
                setTimeout(() => {
                  btn.click();
                  console.log(`✅ Auto-clicked choice ${idx + 1}`);
                }, index * 300); // delay between clicks
              }
            });
          } else {
            document.getElementById('answerBox').innerText += '\n⚠️ Could not detect any valid number.';
          }
        });
        return;
      }

      const input = document.querySelector("input[type='text']");
      if (input) {
        lastQuestion = qn;
        startTimer();
        document.getElementById('questionBox').innerHTML = `<b>Q (Typing):</b> ${qn}`;
        queryAI(qn, [], 'Typing').then(answer => {
          if (answer) {
            document.getElementById('answerBox').innerHTML = `✍️ Suggested: <b>${answer}</b>`;
            if (AUTO_SUBMIT_TYPING) {
              input.value = answer;
              input.dispatchEvent(new Event('input', { bubbles: true }));
              console.log("✅ Typing auto-filled");
            }
          }
        });
        return;
      }

      const slider = document.querySelector("input[type='range']");
      if (slider) {
        lastQuestion = qn;
        startTimer();
        document.getElementById('questionBox').innerHTML = `<b>Q (Slider):</b> ${qn}`;
        queryAI(qn, [], 'Slider').then(answer => {
          if (answer && AUTO_SET_SLIDER) {
            const min = parseFloat(slider.min || '0');
            const max = parseFloat(slider.max || '100');
            let val = parseFloat(answer);
            if (!isNaN(val)) {
              val = Math.max(min, Math.min(val, max));
              slider.value = val;
              slider.dispatchEvent(new Event('input', { bubbles: true }));
              document.getElementById('answerBox').innerHTML = `🎯 Auto-set to: <b>${val}</b>`;
            }
          }
        });
        return;
      }

      const puzzleItems = document.querySelectorAll("div[class*='draggable-option']");
      if (puzzleItems.length >= 2) {
        lastQuestion = qn;
        startTimer();
        const labels = Array.from(puzzleItems).map(p => p.innerText.trim());
        document.getElementById('questionBox').innerHTML = `<b>Q (Puzzle):</b> ${qn}<br>${labels.map((l, i) => `${i + 1}. ${l}`).join('<br>')}`;
        queryAI(qn, labels, 'Puzzle').then(answer => {
          document.getElementById('answerBox').innerHTML = `🧩 Suggested order: <b>${answer}</b><br>(Manual drag required)`;
        });
        return;
      }

    } catch (err) {
      console.warn("❌ Error detecting question:", err);
    }
  }

  setInterval(detectQuestion, 800);
})();