Code viewer for World: DALL-E "Hello World"
let open_ai_response;

// Create an input field for the user to enter the image description
const userInput = document.createElement("input");
userInput.type = "text";
userInput.placeholder = "Enter image description";
userInput.style.position = "fixed"; // Fixed position to keep it at the top
userInput.style.top = "0"; // Position at the top
userInput.style.left = "0"; // Position at the left
document.body.appendChild(userInput);

// Create a button to trigger the generation based on the user's input
const generateButton = document.createElement("button");
generateButton.textContent = "Generate Image";
generateButton.style.marginTop = "40px"; // Add margin to separate from the input
generateButton.addEventListener("click", (event) => {
  event.preventDefault(); // Prevent default form submission behavior
  const userDescription = userInput.value;
  openai_test(userDescription);
});
document.body.appendChild(generateButton);

async function openai_test(userDescription) {
  // Replace with your DALL-E 2 API key
  const API_KEY =    "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";

  var url = "https://api.openai.com/v1/images/generations";

  var xhr = new XMLHttpRequest();
  xhr.open("POST", url);

  xhr.setRequestHeader("Content-Type", "application/json");
  xhr.setRequestHeader("Authorization", "Bearer " + API_KEY);

  xhr.onreadystatechange = function () {
    if (xhr.readyState === 4) {
      console.log(xhr.status);
      console.log(xhr.responseText);
      open_ai_response = xhr.responseText;
      console.log(open_ai_response);

      // Parse the JSON response and extract the image URL
      const responseData = JSON.parse(open_ai_response);
      const imageURL = responseData.data[0].url;

      // Display the generated image
      const img = document.createElement("img");
      img.src = imageURL;
      document.body.appendChild(img);
    }
  };

  // Use user's input as the prompt
  var data = `{
    "prompt": "${userDescription}",
    "n": 1
  }`;

  xhr.send(data);
}