<!-- ui.html -->
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>AdCentral TV Templates Code Generator 🚀</title>
  <!-- Include Your Existing CSS Styles -->
  <style>
    /* Your existing CSS styles */
    @import url('https://fonts.googleapis.com/css2?family=Poppins:wght@400;600&display=swap');
    body {
      font-family: 'Poppins', sans-serif;
      margin: 0;
      padding: 20px;
      background-color: #2c2c2c;
      color: #fff;
      display: flex;
      justify-content: center;
      align-items: center;
      height: 100vh;
      overflow: hidden;
    }
    .container {
      display: flex;
      flex-direction: column;
      align-items: center;
      width: 100%;
      max-width: 600px;
      padding: 20px;
      box-sizing: border-box;
    }
    h1 {
      font-size: 24px;
      font-weight: 600;
      text-align: center;
      margin-bottom: 20px;
    }
    .button {
      width: 170px;
      height: 45px;
      margin: 10px;
      border: none;
      border-radius: 30px;
      background: linear-gradient(90deg, rgba(28,88,255,1) 0%, rgba(118,55,166,1) 100%);
      color: #fff;
      font-size: 16px;
      font-weight: 400;
      cursor: pointer;
      transition: background-color 0.3s ease;
    }
    .button:hover {
      opacity: 0.9;
    }
    .input-field-wrapper {
      position: relative;
      width: 355px;
    }
    .input-field {
      width: 100%;
      padding: 10px;
      margin: 10px 0;
      border: none;
      border-radius: 5px;
      background-color: #3c3c3c;
      color: #fff;
      text-align: center;
      font-size: 14px;
      height: 40px;
      box-sizing: border-box;
    }
    .flex-row {
      display: flex;
      width: 100%;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 10px;
    }
    .label {
      font-size: 12px;
      color: rgba(255,255,255,0.3);
      text-align: center;
      width: 100%;
    }
    .color-field-wrapper {
      position: relative;
      width: 30%;
      display: flex;
      align-items: center;
    }
    .color-field {
      width: 100%;
      padding: 0 10px;
      border: none;
      border-radius: 5px;
      background-color: #3c3c3c;
      color: #fff;
      text-align: center;
      font-size: 14px;
      height: 40px;
      box-sizing: border-box;
    }
    .color-overlay {
      position: absolute;
      bottom: 0;
      left: 0;
      width: 100%;
      height: 5px;
      border-radius: 0 0 5px 5px;
      background-color: #00A3FF;
    }
    .text-area {
      width: 100%;
      height: 150px;
      padding: 10px;
      margin: 10px 0;
      border: none;
      border-radius: 5px;
      background-color: #3c3c3c;
      color: #fff;
      overflow: auto;
      font-size: 14px;
      resize: none;
      font-family: 'Poppins', sans-serif;
    }
    .text-area::-webkit-scrollbar {
      width: 10px;
    }
    .text-area::-webkit-scrollbar-thumb {
      background: linear-gradient(90deg, rgba(28,88,255,1) 0%, rgba(118,55,166,1) 100%);
      border-radius: 5px;
    }
    .text-area::-webkit-scrollbar-track {
      background: #2c2c2c;
    }
    .notification {
      margin-top: 10px;
      font-size: 14px;
      text-align: center;
      color: #28a745;
      display: none;
    }
    .notification.error {
      color: #dc3545;
    }
    .notification.warning {
      color: #ffc107;
    }
    .copy-button {
      width: 20px;
      height: 20px;
      border: none;
      border-radius: 5px;
      background-color: #444;
      display: flex;
      justify-content: center;
      align-items: center;
      cursor: pointer;
      position: absolute;
      right: 5px;
      top: 10px;
    }
    .color-copy-button {
      top: 10px;
    }
    .copy-button svg {
      stroke: rgba(255,255,255,0.3);
    }
    .link-valid {
      background-color: #006400;
    }
    .link-warning {
      background-color: #FF8C00;
    }
    /* Password Modal Styles */
    #passwordModal {
      position: fixed;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background: rgba(44, 44, 44, 0.95);
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      z-index: 1000;
    }
    #passwordModal h2 {
      color: #fff;
      margin-bottom: 20px;
    }
    #passwordInput {
      width: 250px;
      padding: 10px;
      border-radius: 5px;
      border: none;
      text-align: center;
      font-size: 16px;
      margin-bottom: 20px;
    }
    #submitPassword {
      padding: 10px 20px;
      border: none;
      border-radius: 5px;
      background: linear-gradient(90deg, rgba(28,88,255,1) 0%, rgba(118,55,166,1) 100%);
      color: #fff;
      font-size: 16px;
      cursor: pointer;
      transition: opacity 0.3s ease;
    }
    #submitPassword:hover {
      opacity: 0.9;
    }
  </style>
</head>
<body>
  <!-- Password Modal -->
  <div id="passwordModal">
    <h2>Enter Password</h2>
    <input type="password" id="passwordInput" placeholder="Password">
    <button id="submitPassword">Submit</button>
  </div>

  <!-- Main Plugin UI (Initially Hidden) -->
  <div id="mainUI" style="display:none; width: 100%; height: 100%; flex-direction: column;">
    <h1>Welcome to<br>AdCentral TV Templates Code Generator 🚀</h1>
    <div class="flex-row">
      <div class="input-field-wrapper">
        <input type="text" id="frameName" class="input-field" placeholder="Current Frame Name">
        <button id="copyFrameName" class="copy-button">
          <!-- SVG Icon -->
          <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" width="14px" height="14px" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <rect x="9" y="9" width="13" height="13" rx="2" ry="2"></rect>
            <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"></path>
          </svg>
        </button>
      </div>
      <div class="color-field-wrapper">
        <input type="text" id="hexColor" class="color-field" placeholder="#000000" readonly>
        <div class="color-overlay" id="colorOverlay"></div>
        <button id="copyHexColor" class="copy-button color-copy-button">
          <!-- SVG Icon -->
          <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" width="14px" height="14px" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <rect x="9" y="9" width="13" height="13" rx="2" ry="2"></rect>
            <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"></path>
          </svg>
        </button>
      </div>
    </div>
    <div class="flex-row">
      <div class="label" style="width: 355px;">Template Name</div>
      <div class="label" style="width: 30%;">Change Color Hexcode</div>
    </div>
    <input type="text" id="bgUrl" class="input-field" style="width: 100%;" placeholder="Paste here the background image link">
    <div class="flex-row" style="justify-content: center;">
      <button id="applyFrameName" class="button">Apply Frame Name</button>
      <button id="generateFrames" class="button">Generate Frames</button>
      <button id="generateCode" class="button">Generate Code</button>
    </div>
    <textarea id="outputCode" class="text-area" placeholder="HERE WILL BE THE GENERATED OUTPUT FROM THE CONSOLE"></textarea>
    <button id="copyCode" class="button">Copy Code 🚀</button>
    <div id="notification" class="notification"></div>
  </div>

  <!-- Include CodeMirror JS -->
  <script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.10/codemirror.min.js"></script>
  <!-- Include XML Mode for HTML Syntax Highlighting -->
  <script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.10/mode/xml/xml.min.js"></script>
  <!-- Include Font Awesome JS for Icons -->
  <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/js/all.min.js"></script>

  <!-- Main JavaScript -->
  <script>
    (function(){
      // References to modal and main UI
      const passwordModal = document.getElementById("passwordModal");
      const passwordInput = document.getElementById("passwordInput");
      const submitPasswordButton = document.getElementById("submitPassword");
      const mainUI = document.getElementById("mainUI");

      // Handle password submission
      submitPasswordButton.onclick = function() {
        const enteredPassword = passwordInput.value.trim();
        const correctPassword = "W!@JktD_NZjvvbCta8aE@ujj_9dCCGu8TwAJF2iPZhBkmVWeMZxg6X3d!_PP";
        if (enteredPassword === correctPassword) {
          // Password is correct, hide modal and show main UI
          passwordModal.style.display = "none";
          mainUI.style.display = "flex";
          // Notify the backend that authentication was successful
          parent.postMessage({ pluginMessage: { type: "auth-success" } }, "*");
        } else {
          // Password is incorrect, show error and optionally close the plugin
          showNotification("Incorrect password. Plugin will close.", "error");
          // Close the plugin after a short delay
          setTimeout(() => {
            parent.postMessage({ pluginMessage: { type: "close-plugin" } }, "*");
          }, 2000);
        }
      };

      // Allow pressing "Enter" to submit the password
      passwordInput.addEventListener("keypress", function(e) {
        if (e.key === "Enter") {
          submitPasswordButton.click();
        }
      });

      // Listen for messages from the backend
      window.onmessage = (event) => {
        const msg = event.data.pluginMessage;

        if (msg.type === "auth-status") {
          if (msg.status === "success") {
            // Authentication confirmed
            showNotification("Authentication successful!", "success");
          }
        }

        if (msg.type === "export-success") {
          // Handle export success
          showNotification("HTML exported successfully!", "success");
          // Update the outputCode textarea
          document.getElementById("outputCode").value = msg.html;
        }

        if (msg.type === "generate-frames-success") {
          // Handle frame generation success
          showNotification(msg.message, "success");
        }

        if (msg.type === "generate-code-success") {
          // Update the CodeMirror editor with the generated code
          const editor = CodeMirror.fromTextArea(document.getElementById("codeEditor"), {
            lineNumbers: true,
            mode: "xml",
            theme: "default",
            readOnly: true,
            viewportMargin: Infinity
          });
          editor.setValue(msg.code);
          showNotification("Code generated successfully!", "success");
        }

        if (msg.type === "copy-code-success") {
          // Handle copy code success
          showNotification(msg.message, "success");
        }

        if (msg.type === "error") {
          // Display error message
          showNotification(msg.message, "error");
        }

        // Add more handlers as needed
      };

      /**
       * Displays a notification message to the user.
       * @param {string} message - The message to display.
       * @param {string} type - The type of message ('success', 'error', 'warning').
       */
      function showNotification(message, type) {
        const notification = document.getElementById("notification");
        notification.textContent = message;
        notification.classList.remove("success", "error", "warning");
        notification.classList.add(type);
        notification.style.display = "block";
        // Hide the notification after 3 seconds
        setTimeout(() => {
          notification.style.display = "none";
        }, 3000);
      }

      // Initialize CodeMirror editor
      const codeEditor = CodeMirror.fromTextArea(document.getElementById("codeEditor"), {
        lineNumbers: true,
        mode: "xml",
        theme: "default",
        readOnly: true,
        viewportMargin: Infinity
      });

      // Handle Generate Code Button Click
      const generateCodeButton = document.getElementById("generateCode");
      generateCodeButton.onclick = () => {
        // Collect necessary data
        const frameName = document.getElementById("frameName").value.trim();
        const backgroundUrl = document.getElementById("bgUrl").value.trim();
        const splitTextLines = document.getElementById("splitTextToggle").checked;
        const backgroundEnabled = document.getElementById("backgroundSwitch").checked;

        // Basic validation
        if (backgroundEnabled && backgroundUrl === "") {
          showNotification("Please enter a background image URL or disable the Add Background toggle.", "error");
          return;
        }

        // Send message to backend to generate code
        parent.postMessage({
          pluginMessage: {
            type: "generate-code",
            codeParameters: {
              title: frameName || "Default Title",
              backgroundColor: "#FFFFFF",
              heading: "Sample Heading",
              paragraph: "Sample paragraph text."
              // Add more parameters as needed
            }
          }
        }, "*");
      };

      // Handle Generate Frames Button Click
      const generateFramesButton = document.getElementById("generateFrames");
      generateFramesButton.onclick = () => {
        // Collect necessary data
        const frameName = document.getElementById("frameName").value.trim();
        const backgroundUrl = document.getElementById("bgUrl").value.trim();
        const splitTextLines = document.getElementById("splitTextToggle").checked;
        const backgroundEnabled = document.getElementById("backgroundSwitch").checked;

        // Basic validation
        if (backgroundEnabled && backgroundUrl === "") {
          showNotification("Please enter a background image URL or disable the Add Background toggle.", "error");
          return;
        }

        // Send message to backend to generate frames
        parent.postMessage({
          pluginMessage: {
            type: "generate-frames",
            frameData: {
              name: frameName || "Default Frame",
              backgroundUrl: backgroundEnabled ? backgroundUrl : null,
              // Add more frame data as needed
            }
          }
        }, "*");
      };

      // Handle Export HTML Button Click
      const exportHtmlButton = document.getElementById("generateCode"); // Assuming it's the Generate Code button
      exportHtmlButton.onclick = () => {
        // Collect necessary data
        const frameName = document.getElementById("frameName").value.trim();
        const backgroundUrl = document.getElementById("bgUrl").value.trim();
        const splitTextLines = document.getElementById("splitTextToggle").checked;
        const backgroundEnabled = document.getElementById("backgroundSwitch").checked;

        // Basic validation
        if (backgroundEnabled && backgroundUrl === "") {
          showNotification("Please enter a background image URL or disable the Add Background toggle.", "error");
          return;
        }

        // Send message to backend to export HTML
        parent.postMessage({
          pluginMessage: {
            type: "export-html",
            splitTextLines,
            backgroundEnabled,
            backgroundUrl
          }
        }, "*");
      };

      // Handle Copy Code Button Click
      const copyCodeButton = document.getElementById("copyCode");
      copyCodeButton.onclick = () => {
        const code = codeEditor.getValue();
        if (!code) {
          showNotification("No code to copy. Please generate the code first.", "error");
          return;
        }

        // Copy code to clipboard
        navigator.clipboard.writeText(code).then(() => {
          parent.postMessage({ pluginMessage: { type: "copy-code" } }, "*");
          showNotification("Code copied to clipboard 🚀!", "success");
        }).catch((err) => {
          console.error("Failed to copy code:", err);
          showNotification("Failed to copy code.", "error");
        });
      };

      // Handle Copy Frame Name Button Click
      const copyFrameNameButton = document.getElementById("copyFrameName");
      copyFrameNameButton.onclick = () => {
        const frameName = document.getElementById("frameName").value.trim();
        if (!frameName) {
          showNotification("No frame name to copy.", "error");
          return;
        }

        // Copy frame name to clipboard
        navigator.clipboard.writeText(frameName).then(() => {
          showNotification("Frame name copied to clipboard 🚀!", "success");
        }).catch((err) => {
          console.error("Failed to copy frame name:", err);
          showNotification("Failed to copy frame name.", "error");
        });
      };

      // Handle Apply Frame Name Button Click
      const applyFrameNameButton = document.getElementById("applyFrameName");
      applyFrameNameButton.onclick = () => {
        const frameName = document.getElementById("frameName").value.trim();
        if (!frameName) {
          showNotification("Please enter a frame name to apply.", "error");
          return;
        }

        // Send message to backend to apply frame name
        parent.postMessage({
          pluginMessage: {
            type: "apply-frame-name",
            name: frameName
          }
        }, "*");
      };

      // Handle Add Background Toggle
      const backgroundSwitch = document.getElementById("backgroundSwitch");
      const backgroundTextboxContainer = document.getElementById("backgroundTextboxContainer");

      backgroundSwitch.onchange = () => {
        if (backgroundSwitch.checked) {
          backgroundTextboxContainer.style.display = "flex";
        } else {
          backgroundTextboxContainer.style.display = "none";
          document.getElementById("bgUrl").value = "";
        }
      };

    })();
  </script>
</body>
</html>
