Code viewer for World: New World
document.write(`
    
    <h1>World 2: Drawing World</h1>

    <div style="width:60vw; background-color:white;  border: 1px solid black; margin:20; padding: 20px;">
        <h3> Select a Historical Place </h3>
        <select id="historical-place" style="width:50vw;">
            <option value="happy?">Happy</option>
            <option value="eiffel-tower">Eiffel Tower</option>
            <option value="great-wall">Great Wall of China</option>
            <!-- Add more historical places as needed -->
        </select>
        <button onclick="sendChatWithHistoricalPlace();" class=ab-normbutton > Send </button> 
    </div>

    <div style="width:60vw; background-color:#ffffcc;  border: 1px solid black; margin:20; padding: 20px;">
        <h3> GPT replies </h3>
        <div id=them> </div>
    </div>

    <button onclick="clearScreen();" class=ab-normbutton >Clear Screen</button>

    <pre></pre>

    <div id="drawing-section" style="width: 60vw; background-color: #ccffff; border: 1px solid black; margin: 20; padding: 20px;">
        <h3> Drawing Section </h3>
        <!-- Add your drawing elements here -->
    </div>
`);

// Continue with the rest of World 2 code...

function sendChatWithHistoricalPlace() {
    var selectedPlace = $("#historical-place").val();
    var apikey = localStorage.getItem("apikey");
    var temperature = localStorage.getItem("temperature");
    console.log(temperature)
    
    // Construct the prompt
    var theprompt = `Could you assist me in creating an HTML code block that includes both Three.js and jQuery to generate a ${selectedPlace} using Three.js?`;
    //var theprompt=`Could you assist me in creating an HTML code block that includes both p5.js and jQuery to generate a ${selectedPlace} using p5.js?`
    // Call the sendchat function with the new prompt
    sendchat(theprompt, apikey, temperature);
}

// Enter will also send chat:
document.getElementById('me').onkeydown = function (event) { if (event.keyCode == 13) sendchat(); };

// --- Send my line of text ----------------------------------------------------------------
function sendchat(theprompt, apikey, temperature) {
    var openaiURL = "https://api.openai.com/v1/chat/completions";

    // Construct the request data
    var thedata = {
        "model": "gpt-3.5-turbo",
        "temperature": parseFloat(temperature),
        "messages": [{
            "role": "user",
            "content": theprompt
        }]
    };

    var thedatastring = JSON.stringify(thedata);

    $.ajaxSetup({
        headers: {
            "Content-Type": "application/json",
            "Authorization": "Bearer " + apikey
        }
    });

    // Make the API request
    $.ajax({
        type: "POST",
        url: openaiURL,
        data: thedatastring,
        dataType: "json",
        success: function (data, rc) { successfn(data, rc); },
        error: function () { errorfn(); }
    });
}

function successfn(data, rc) {
    a = data;
    var answer = a["choices"][0].message.content;
    console.log("answer",answer)
    $("#them").append("<p>" + answer + "</p>");

    // Extract the code from the response
    var codeMatch = answer.match(/```([\s\S]*)```/);
    console.log("codematch",codeMatch)
    var generatedCode = codeMatch;

    // Run the extracted code
    if (generatedCode) {
        runReceivedCode(generatedCode);
    }
}

function errorfn() {
    if (apikey == "") $("#them").html("<font color=red><b> Enter API key to be able to chat. </b></font>");
    else $("#them").html("<font color=red><b> Unknown error. </b></font>");
}

function clearScreen() {
    $("#them").html("");
    $("#drawing-section").html(""); // Clear the drawing section
}

function runReceivedCode(code) {
    
        console.log("run code")
        //? Also, please ensure that the code includes the line <script src="https://threejs.org/build/three.js"></script> for the Three.js library?
        //document.write('<script src="https://threejs.org/build/three.js"></script>');
        // Create a script element for Three.js
        //  var script = document.createElement('script');
        //  script.src = 'https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js';
        //  script.src="https://cdnjs.cloudflare.com/ajax/libs/three.js/110/three.min.js";
        //  script.src='https://threejs.org/build/three.js';
        
        //  script.async = true;
        //  script.crossOrigin = 'anonymous'
        // // // Define a callback for when the script is loaded
        //  script.onload = function () {
        // //     // Now that Three.js is loaded, evaluate the received code
        //      eval(code);
        // //     document.head.appendChild(script);
        //  }
        try {
        // Check if THREE is defined
        if (typeof THREE === 'undefined') {
            // If not defined, dynamically load Three.js
            var threeScript = document.createElement('script');
            threeScript.src = 'https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js';
            threeScript.src="js/Three/three.js";
            threeScript.onload = function () {
                // Once Three.js is loaded, execute the received code
                executeCode(code);
            };
            document.head.appendChild(threeScript);
        } else {
            // If already defined, execute the received code
            executeCode(code);
        }
    } catch (error) {
        console.error("Error executing received code:", error);
    }
}

function executeCode(code) {
    try {
        // Execute the received code
        eval(code);
    } catch (error) {
        console.error("Error executing received code:", error);
    }
}