Code viewer for World: World_1_Prac_2
//Referenced from : https://ancientbrain.com/world.php?world=2850716357

const openaiURL = "https://api.openai.com/v1/chat/completions";
var themodel = "gpt-3.5-turbo"; //default model
var apikey = "";
var temperature = 0.7; // Default temperature value

$('body').css("margin", "20px");
$('body').css("padding", "20px");

document.write(`
    <h1> Chat with GPT model - World 1 </h1>

    Running World 1:
    <a href='https://ancientbrain.com/world.php?world=5356456453'>Chat with GPT model - World 1</a>.
    <br> 
    Chat with
    <a href="https://platform.openai.com/docs/models/overview">GPT 3.5</a>
    using the
    <a href="https://en.wikipedia.org/wiki/OpenAI">OpenAI</a>  API.
    <br> 
    This is the model
    <a href="https://en.wikipedia.org/wiki/ChatGPT">ChatGPT</a> uses.

    <pre></pre>

    <h3> Enter API key </h3>

    
    You enter your API key below and then chat away.
    Then communications to OpenAI come from your IP address using your API key. 
    <br>
    API key will be stored in the local storage
    

    <div id=enterkey>
        Enter API key: 
        <input style='width:25vw;' maxlength='2000' NAME="apikey" id="apikey" VALUE='${apikey}'>  
        
    </div>

    

    <button onclick="initializeChat();" class=ab-normbutton >Initialize Chat</button>
    
    <div id="them"></div>
    
    <h1>Please select the model and set the required temperature before navigating to world 2</h1>
    
    <h3> Select GPT Model </h3>
    
    <select id="gpt-model" style="width:50vw;">
        <option value="gpt-3.5-turbo-1106">GPT-3.5 Turbo 1106</option>
        <option value="gpt-3.5-turbo-0613">GPT-3.5 Turbo 0613</option>
        <option value="gpt-3.5-turbo">GPT-3.5 Turbo</option>
    </select>
    
    <button onclick='setModel();' class=ab-normbutton >Set Model</button>
    <h3>You can fine tune the output according to the requirement
    <div style="width:60vw; background-color:white;  border: 1px solid black; margin:20; padding: 20px;">
        <h3> Temperature Control </h3>
        <input type="range" min="0" max="1" step="0.1" value="${temperature}" id="temperature-slider" oninput="updateTemperature(this.value)">
        <span id="temperature-value">${temperature}</span>
    </div>
    
    <button id="goToWorld2Button" onclick="navigateToWorld2();" class="ab-normbutton" disabled style="background-color: #ddd; color: #888;">Go to World 2</button>
    
`);


//Sharjil Dhanani - initializing a chat to validate the API key
function initializeChat() {
    // Set a default prompt for testing
    var initialPrompt = "Hello, how are you?";
    
    
    apikey = jQuery("input#apikey").val();
    apikey = apikey.trim();

    
    // mh edit
    console.log ( "apikey = " + apikey ); 
 //   localStorage.setItem("apikey", apikey);


    // Display the initial user prompt
    $("#them").append("<p><b>User:</b> " + initialPrompt + "</p>");

    // Construct the request data
    var thedata = {
        //default model and temperature will be selected
        "model": themodel,
        "temperature": temperature,
        "messages": [
            {
                "role": "system",
                "content": "Write code in three.js using jQuery of famous monuments."
            },
            {
                "role": "user",
                "content": initialPrompt
            }
        ]
    };

    // Make the API request to get a response
    $.ajax({
        type: "POST",
        url: openaiURL,
        data: JSON.stringify(thedata),
        dataType: "json",
        headers: {
            "Content-Type": "application/json",
            "Authorization": "Bearer " + apikey
        },
        success: function (data, rc) { displayResponse(data); },
        error: function () { errorfn(); }
    });
}


//Sharjil Dhanani - display the response to the user and enables world 2 button
function displayResponse(data) {
    var response = data.choices[0].message.content;

    // Display the GPT response
    $("#them").append("<p><b>GPT:</b> " + response + "</p>");
    
    if (response) {
        
        $("#them").append("<p><i>CHAT GPT is working, you are ready to enter world 2</i></p>");
     $("#goToWorld2Button").prop("disabled", false).css("background-color", "").css("color", "");  
    } else {

        // If the response is not valid
        console.log("Invalid response. Please try again.");
    }
}
function errorfn() {
    // Display an error message to the user
    $("#them").append( "<font color=red><b> 401 (Unauthorized) </b></font>" ); 

    
}
//Sharjil Dhanani - storing the model according to user's selection in local storage
function setModel(){
    themodel = jQuery("#gpt-model").val();
    console.log(themodel)
    localStorage.setItem("themodel", themodel);

}
//Sharjil Dhanani - storing the temperature according to user's selection in local storage
function updateTemperature(value) {
    temperature = parseFloat(value).toFixed(1);
    // sharjil Dhanani - storing the temperature in local storage to retrieve in world two
    localStorage.setItem("temperature", temperature);
    $("#temperature-value").text(temperature);
}

//Sharjil Dhanani - User will be navigated to World 2 
function navigateToWorld2() {
    window.location.href = 'https://run.ancientbrain.com/run.php?world=8114498339&userid=sharjil12&dataticket=94111847719786078532913168052441';
}