Code viewer for World: Trivia
document.write(`
    
     <style>
        h1 {
            text-align: center;
        }
        p {
            text-align: center;
        }
        .table-container {
            display: flex;
            justify-content: center; 
            align-items: center;
        }
        .api-container{
            display: flex;
            justify-content: center;
            align-items: center;
        }
        .topic-container {
            display: flex;
            justify-content: center;
            align-items: center;
        }
        .topic {
        }
        .input-container {
            padding-right: 5px;
            padding-left: 5px;
        }
        .cells {
            cursor: pointer; 
            background-color: #f0f0f0; 
            text-align: center; 
            vertical-align: middle; 
            padding: 10px; 
            border: 1px solid #d0d0d0;
            height:150px;
            width:250px;
        }
        .cells:hover {
            background-color: #e0e0e0;
        }
        .submit-button {
            display: flex;
            justify-content: center;
            align-items: center;
            padding-top: 10px;
        }
        #chosen_answer {
            padding-top: 15px;
            text-align: center;
        }
        #response {
            text-align: center;
            font-weight: bold;
            padding-top: 10px;
        }
        #next_question {
            display: none;
            justify-content: center;
            align-items: center;
            padding-top: 10px;
        }
        .spinner-container {
            display: flex;
            justify-content: center;
            align-items: center;
        }
        #spinner {
            animation: spin 2s linear infinite;
        }
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
    </style>
    
    
    <!-------------------- HEADER -------------------->
    
    <h1>Welcome to Freestlye Trivia!</h1>
    <p> Hi welcome to Trivia! Get quizzed on any topic of your choice. To start make sure you input the API key below! </p>
    <p> <i> Note that the questions are AI generated and inaccurate answers may occur.</i> </p>
    
    
    <!---------------- API KEY INPUT ---------------->

    <div class="api-container" id=enterAPIkey>
        Enter API key:
        <div class="input-container">
            <input type="text" id="apikey" value="">
        </div>
        <button onclick="setKey()">Set API Key</button>
    </div>
    
    <br></br>
     <!-------------- CHOOSE TOPIC ----------------->
    
    <div class="topic-container"> 
        <div class="topic">
         Pick any topic and enter it in!
        </div>
        <div class="input-container">
            <input id=prompt value="">
        </div>
        <button onclick=getChatCompletion()>Enter</button>
    </div>
    
     <!----------- GENERATED QUESTION -------------->
     
    <div id="response">
    </div>
    
    <!---------------- SPINNER --------------------->
    
    <div class="spinner-container">
        <div id="spinner" style="display: none;">
            <img src="/uploads/imago/spinner.png" alt="Description of image" width="50" height="50">
        </div>
    </div>
     
    
    <!--------------- SELECTED ANSWER -------------->
    <div id="chosen_answer">
    </div>
    
    
    <!--------------- ANSWER PANEL ----------------->
    
    <div class="table-container">
        <table>
        <tr>
            <td id="answer_A" class="cells">Answer #1</td>
            <td id="answer_B" class="cells">Answer #2</td>
        </tr>
        <tr>
            <td id="answer_C" class="cells">Answer #3</td>
            <td id="answer_D" class="cells">Answer #4</td>
        </tr>
        </table>
    </div>
    
    <!--------------- SUBMIT ---------------------->
    <div class="submit-button"> 
        <button onclick="checkAnswer()">Submit</button>
    </div>
    
    <!----------------NEXT QUESTION ---------------->
    <div id="next_question">
        <button onclick="getChatCompletion()"> Next Question </button>
    </div>
    
    
    <!--------------- RESULT ---------------------->
    <div id="result"> </div>
     
    
    <!--------------- POINTS ---------------------->
    <div id="points"><b> Points: </b> 0</div>
`);


let apiKey = "";
let correct = "";
let user_answer = "";
let points = 0;
let shouldBeVisible = false;
let spinnerVisible = false;

//Store user input
document.querySelectorAll('.cells').forEach(cell => {
    cell.onclick = function() {
        let cellID = this.id;
        console.log(cellID);
        user_answer = document.getElementById(cellID).textContent;
        console.log(user_answer);
        $("#chosen_answer").html("You have selected: " + user_answer);
    };
});



function setKey() {
    apiKey = document.getElementById('apikey').value;
    console.log('API Key set:', apiKey); 
    $("#enterAPIkey").html ("<b> API key has been set! </b>")
}

function checkAnswer() {
    shouldBeVisible = true;
    updateDisplay();
    if (correct === user_answer) {
        console.log("True")
        console.log(correct + "===" + user_answer);
        $("#result").html("<b> Correct! </b>")
        managePoints();
    } else {
        $("#result").html("<b> Incorrect! The correct answer was </b>" + correct)
    }
    
}

function clearTrivia() {
    $("#result").html("")
    $("#chosen_answer").html("");
    $("#response").html("");
}

function managePoints() {
    points++
    $("#points").html("<b> Points </b>" + points)
}

function updateDisplay() {
  let element = document.getElementById('next_question');
  if (shouldBeVisible) {
    element.style.display = 'flex';
  } else {
    element.style.display = 'none';
  }
}

function updateSpinner() {
  let element = document.getElementById('spinner');
  if (spinnerVisible) {
    element.style.display = 'flex';
  } else {
    element.style.display = 'none';
  }
}

async function getChatCompletion() {
            clearTrivia();
            if (!apiKey) {
                console.log('API Key is not set');
                return;
            }
            const prompt = document.getElementById('prompt').value;

            const data = {
                model: "gpt-3.5-turbo",
                messages: [
                    { "role": "system", "content": "You are a game show host, and when provided a topic, you will generate a hard question and four possible choices in this format 'Choices:'and include the correct answer in the end" },
                    { "role": "user", "content": prompt }
                ]
            };

 // MH edit
console.log ( "MH debug - asking for a single question" );
console.log ( data );


            try {
                spinnerVisible = true;
                updateSpinner();
                const response = await fetch('https://api.openai.com/v1/chat/completions', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${apiKey}`
                    },
                    body: JSON.stringify(data)
                });

                if (!response.ok) {
                    throw new Error(`Error: ${response.status}`);
                }

                const result = await response.json();
                console.log(result);
                
                
                //Trivia Generation
                let trivia = result["choices"][0].message.content;
                let trivia_split = trivia.split("Choices:");
                
                let question = trivia_split[0]
                let answers = trivia_split[1]
                
                let answers_split = answers.split(/\n/);
                
                let answer_A = answers_split[1]
                let answer_B = answers_split[2]
                let answer_C = answers_split[3]
                let answer_D = answers_split[4]
                
                //Store the correct answer
                let correct_phrase = answers_split[6];
                let split_correct = correct_phrase.split(": ");
                console.log(split_correct);
                correct = split_correct[1];
                console.log(correct);
                
                
                $("#answer_A").html(answer_A);
                $("#answer_B").html(answer_B);
                $("#answer_C").html(answer_C);
                $("#answer_D").html(answer_D);
                
                
                console.log(answers_split)
                
                console.log(question)
                console.log(answers)
                
                $("#response").html(question);
                
                spinnerVisible = false;
                updateSpinner();
                
            } catch (error) {
                console.error('Failed to fetch from OpenAI:', error);
            }
}