// ==UserScript==
// @name         Kahoot AI Auto-Answer (Groq Full Support)
// @namespace    http://tampermonkey.net/
// @version      4.0
// @description  Supports MCQ, typing, slider, puzzle. Uses Groq AI to suggest answers or auto-click.
// @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_CLICK_DELAY_MS = 100;

  let pastedScript = '';
  let lastQuestion = '';
  let timerInterval = null;
  let timerSeconds = 0;

  const uiBox = document.createElement('div');
  uiBox.style = `
    position: fixed;
    top: 60px;
    right: 20px;
    width: 320px;
    background: white;
    border: 2px solid black;
    padding: 12px;
    z-index: 99999;
    font-family: sans-serif;
    font-size: 14px;
  `;
  uiBox.innerHTML = `
    <h4 style="margin: 4px 0;">🤖 Kahoot AI Assistant (Groq)</h4>
    <textarea id="scriptBox" rows="6" placeholder="Paste script/video transcript..." style="width: 100%; resize: none;"></textarea><br>
    <button id="loadScript" style="margin-top: 6px;">📥 Load Script</button>
    <div style="margin-top: 8px;"><b>API Status:</b> <span id="apiStatus" style="color: gray;">Idle</span></div>
    <div><b>Timer:</b> <span id="timer">0s</span></div>
    <hr>
    <div id="questionBox"><i>Waiting for question...</i></div>
    <div id="answerBox" style="margin-top: 5px; color: green;"></div>
  `;
  document.body.appendChild(uiBox);

  document.getElementById('loadScript').onclick = () => {
    pastedScript = document.getElementById('scriptBox').value.trim();
    document.getElementById('apiStatus').innerText = pastedScript ? 'Script Loaded ✅' : 'No Script ❌';
    document.getElementById('apiStatus').style.color = pastedScript ? 'green' : 'red';
  };

  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, mode = 'normal') {
    if (!pastedScript || !GROQ_API_KEY) {
      document.getElementById('apiStatus').innerText = '❌ Script or API key missing';
      document.getElementById('apiStatus').style.color = 'red';
      return null;
    }

    document.getElementById('apiStatus').innerText = 'Thinking...';
    document.getElementById('apiStatus').style.color = 'orange';

    const prompt = `You are an AI answering a Kahoot quiz based on this transcript:
"""
${pastedScript}
"""
Question: ${question}
${choices.length ? `Choices:\n${choices.map((c, i) => `${i + 1}. ${c}`).join('\n')}` : ''}
Respond with ONLY:

- For multiple choice: the number (1-4).
- For typing: the exact word or short phrase.
- For slider: a number.
- For puzzle: the correct order as numbers (e.g. "3 1 4 2").`;

    try {
      const response = 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 result = await response.json();
      const content = result?.choices?.[0]?.message?.content?.trim();

      document.getElementById('apiStatus').innerText = '✅ Answered';
      document.getElementById('apiStatus').style.color = 'green';
      document.getElementById('answerBox').innerText = content;

      return content;
    } catch (e) {
      console.error(e);
      document.getElementById('apiStatus').innerText = '❌ Error';
      document.getElementById('apiStatus').style.color = 'red';
      document.getElementById('answerBox').innerText = '❌ Failed to contact Groq API.';
      return null;
    }
  }

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

      // Multiple choice
      const choices = Array.from(document.querySelectorAll("button[class*='choice'] p")).map(c => c.innerText.trim());
      if (choices.length >= 2) {
        lastQuestion = qn;
        startTimer();
        document.getElementById('questionBox').innerHTML = `<b>Q (MCQ):</b> ${qn}<br><b>Choices:</b><br>${choices.map((c, i) => `${i + 1}. ${c}`).join('<br>')}`;
        queryAI(qn, choices).then(content => {
          const match = content?.match(/^\D*(\d{1,2})\D*$/);
          if (match) {
            const answerIndex = parseInt(match[1], 10) - 1;
            const tryClick = setInterval(() => {
              const choiceButtons = document.querySelectorAll("button[class*='choice']");
              if (choiceButtons.length && choiceButtons[answerIndex]) {
                choiceButtons[answerIndex].click();
                clearInterval(tryClick);
                console.log(`✅ Auto-clicked choice ${answerIndex + 1}`);
              }
            }, 300);
            setTimeout(() => clearInterval(tryClick), 5000);
          } else {
            document.getElementById('answerBox').innerText += '\n⚠️ Unrecognized MCQ format.';
          }
        });
        return;
      }

      // Typing question
      const inputBox = document.querySelector("input[type='text']");
      if (inputBox) {
        lastQuestion = qn;
        startTimer();
        document.getElementById('questionBox').innerHTML = `<b>Q (Typing):</b> ${qn}`;
        queryAI(qn, []).then(answer => {
          if (answer) {
            document.getElementById('answerBox').innerHTML = `✍️ Suggested answer: <b>${answer}</b><br>You can copy-paste.`;
          }
        });
        return;
      }

      // Slider question
      const sliderInput = document.querySelector("input[type='range']");
      if (sliderInput) {
        lastQuestion = qn;
        startTimer();
        document.getElementById('questionBox').innerHTML = `<b>Q (Slider):</b> ${qn}`;
        queryAI(qn, []).then(answer => {
          if (answer) {
            document.getElementById('answerBox').innerHTML = `🎯 Suggested value: <b>${answer}</b><br>Adjust slider manually.`;
          }
        });
        return;
      }

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

    } catch (err) {
      console.warn('UI read failed:', err);
    }
  }

  setInterval(detectQuestion, 1500);
})();