<!-- ui.html -->
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Export HTML</title>
  <!-- Include CodeMirror CSS -->
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.10/codemirror.min.css" />
  <!-- Include Dracula Theme for CodeMirror -->
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.10/theme/dracula.min.css" />
  <!-- Include Font Awesome for Icons -->
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" />

  <!-- Custom Styles for Modern UI -->
  <style>
    /* Reset and Base Styles */
    * {
      box-sizing: border-box;
    }

    body {
      margin: 0;
      padding: 0;
      font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
      background-color: #1e1e1e;
      color: #d4d4d4;
      display: flex;
      flex-direction: column;
      height: 100vh;
      overflow: hidden;
    }

    /* Toolbar Styling */
    .toolbar {
      background-color: #2d2d2d;
      padding: 10px;
      display: flex;
      align-items: center;
      border-bottom: 1px solid #444;
      flex-wrap: wrap; /* Allows items to wrap on smaller screens */
      gap: 10px; /* Uniform spacing between toolbar items */
    }

    /* Button Styling */
    .toolbar button {
      background: #3c3c3c;
      border: none;
      color: #d4d4d4;
      cursor: pointer;
      font-size: 14px;
      padding: 8px 12px;
      border-radius: 4px;
      display: flex;
      align-items: center;
      transition: background 0.3s, color 0.3s;
    }

    .toolbar button:hover {
      background: #575757;
      color: #ffffff;
    }

    .toolbar button i {
      margin-right: 5px;
    }

    /* Container for Split Text Lines Toggle */
    .split-text-container {
      display: flex;
      align-items: center;
      gap: 5px; /* Spacing between label and toggle */
    }

    /* Container for Add Background Toggle and Textbox */
    .background-container {
      display: flex;
      align-items: center;
      gap: 5px; /* Spacing between label, toggle, and textbox */
      flex-grow: 1; /* Allows the container to take available space */
      min-width: 200px; /* Prevents the container from becoming too small */
    }

    /* Toggle Switch Styling */
    .toggle-switch {
      position: relative;
      width: 50px;
      height: 24px;
    }

    .toggle-switch input {
      opacity: 0;
      width: 0;
      height: 0;
    }

    .slider {
      position: absolute;
      cursor: pointer;
      background-color: #ccc;
      border-radius: 24px;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      transition: 0.4s;
    }

    .slider:before {
      position: absolute;
      content: "";
      height: 18px;
      width: 18px;
      left: 3px;
      bottom: 3px;
      background-color: #fff;
      transition: 0.4s;
      border-radius: 50%;
    }

    input:checked + .slider {
      background-color: #2196F3;
    }

    input:checked + .slider:before {
      transform: translateX(26px);
    }

    /* Textbox Styling */
    .textbox-container {
      flex-grow: 1;
      max-width: 300px; /* Prevents the textbox from exceeding plugin width */
      display: flex;
      align-items: center;
    }

    .textbox-container input[type="text"] {
      width: 100%;
      padding: 6px 10px;
      border: none;
      border-radius: 4px;
      background-color: #3c3c3c;
      color: #d4d4d4;
      font-size: 14px;
    }

    /* Editor Container */
    .editor-container {
      flex: 1;
      display: flex;
      flex-direction: column;
      overflow: hidden;
    }

    /* CodeMirror Editor Styling */
    .CodeMirror {
      flex: 1;
      height: auto;
      font-size: 14px;
    }

    /* Message Styling */
    .message {
      padding: 10px;
      color: #ff6666;
      background-color: #333;
      border-top: 1px solid #444;
      font-size: 14px;
      text-align: center;
      opacity: 0;
      transition: opacity 0.5s ease-in-out;
    }

    /* Show message when content is set */
    .message.show {
      opacity: 1;
    }

    /* Responsive Adjustments */
    @media (max-width: 800px) {
      .toolbar {
        flex-direction: column;
        align-items: flex-start;
        gap: 10px;
      }

      .split-text-container,
      .background-container {
        width: 100%;
      }

      .textbox-container input[type="text"] {
        width: 100%;
      }
    }

    @media (max-width: 600px) {
      .toolbar button {
        font-size: 12px;
        padding: 6px 10px;
      }

      .CodeMirror {
        font-size: 12px;
      }

      .message {
        font-size: 12px;
      }

      .toggle-container {
        flex-direction: column;
        align-items: flex-start;
      }

      .textbox-container {
        max-width: 100%; /* Allows the textbox to take full width on small screens */
      }
    }

    /* Password Modal Styles */
    .modal-overlay {
      position: fixed;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background: rgba(30, 30, 30, 0.95);
      display: flex;
      align-items: center;
      justify-content: center;
      z-index: 1000;
    }

    .modal {
      background: #2d2d2d;
      padding: 30px 20px;
      border-radius: 8px;
      width: 320px;
      box-shadow: 0 4px 6px rgba(0,0,0,0.3);
      text-align: center;
    }

    .modal h2 {
      margin-bottom: 20px;
      color: #fff;
    }

    .modal input[type="password"] {
      width: 100%;
      padding: 12px 10px;
      margin-bottom: 20px;
      border: none;
      border-radius: 4px;
      font-size: 16px;
    }

    .modal button {
      width: 100%;
      padding: 12px;
      background: #2196F3;
      border: none;
      border-radius: 4px;
      color: #fff;
      font-size: 16px;
      cursor: pointer;
      transition: background 0.3s;
    }

    .modal button:hover {
      background: #1976D2;
    }

    .error-message {
      color: #ff6666;
      margin-top: 10px;
      font-size: 14px;
      display: none;
    }
  </style>
</head>
<body>
  <!-- Password Modal -->
  <div id="passwordModal" class="modal-overlay">
    <div class="modal">
      <h2>Enter Password</h2>
      <input type="password" id="passwordInput" placeholder="Password" />
      <button id="submitPassword">Submit</button>
      <div id="passwordError" class="error-message">Incorrect password. Plugin will close.</div>
    </div>
  </div>

  <!-- Main Plugin UI (Initially Hidden) -->
  <div id="mainUI" style="display: none; height: 100%; flex-direction: column;">
    <!-- Toolbar with Generate and Copy Buttons -->
    <div class="toolbar">
      <!-- 1. Generate Code Button -->
      <button id="generateButton"><i class="fas fa-file-export"></i> Generate Code</button>

      <!-- 2. Copy to Clipboard Button -->
      <button id="copyButton"><i class="fas fa-copy"></i> Copy to Clipboard</button>

      <!-- 3. Split Text Lines Toggle -->
      <div class="split-text-container">
        <span class="toggle-label">Split Text Lines</span>
        <label class="toggle-switch">
          <input type="checkbox" id="splitTextToggle" checked>
          <span class="slider"></span>
        </label>
      </div>

      <!-- 4. Add Background Toggle and 5. Background URL Textbox -->
      <div class="background-container">
        <span class="toggle-label">Add Background</span>
        <label class="toggle-switch">
          <input type="checkbox" id="backgroundSwitch">
          <span class="slider"></span>
        </label>
        <div class="textbox-container" id="backgroundTextboxContainer">
          <input type="text" id="backgroundUrl" placeholder="Enter background image URL">
        </div>
      </div>
    </div>

    <!-- Editor Container with CodeMirror Editor -->
    <div class="editor-container">
      <textarea id="codeEditor"></textarea>
    </div>

    <!-- Message Display Area -->
    <div id="message" class="message"></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>

  <!-- Initialize CodeMirror Editor and Handle UI Interactions -->
  <script>
    // Initialize CodeMirror editor
    const editor = CodeMirror.fromTextArea(document.getElementById('codeEditor'), {
      lineNumbers: true,
      mode: 'xml',
      theme: 'dracula',
      readOnly: true, // Make editor read-only to prevent accidental edits
      viewportMargin: Infinity, // Ensures the editor scales with content
    });

    // Get references to UI elements
    const generateButton = document.getElementById('generateButton');
    const copyButton = document.getElementById('copyButton');
    const splitTextToggle = document.getElementById('splitTextToggle');
    const backgroundSwitch = document.getElementById('backgroundSwitch');
    const backgroundTextboxContainer = document.getElementById('backgroundTextboxContainer');
    const backgroundUrlInput = document.getElementById('backgroundUrl');
    const messageDiv = document.getElementById('message');

    // Password Modal Elements
    const passwordModal = document.getElementById('passwordModal');
    const passwordInput = document.getElementById('passwordInput');
    const submitPasswordButton = document.getElementById('submitPassword');
    const passwordError = document.getElementById('passwordError');

    // Handle Add Background Toggle
    backgroundSwitch.onchange = () => {
      if (backgroundSwitch.checked) {
        backgroundTextboxContainer.style.display = 'flex';
      } else {
        backgroundTextboxContainer.style.display = 'none';
        backgroundUrlInput.value = ''; // Clear the textbox when disabled
      }
    };

    // Handle Generate Code Button Click
    generateButton.onclick = () => {
      console.log('Generate Code button clicked'); // Debugging log
      // Disable the generate button to prevent multiple clicks
      generateButton.disabled = true;
      generateButton.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Generating...';

      // Get the background URL from the textbox if enabled
      const isBackgroundEnabled = backgroundSwitch.checked;
      let backgroundUrl = '';
      if (isBackgroundEnabled) {
        backgroundUrl = backgroundUrlInput.value.trim();
        if (backgroundUrl === '') {
          showMessage('Please enter a background image URL or disable the Add Background toggle.', true);
          // Re-enable the generate button
          generateButton.disabled = false;
          generateButton.innerHTML = '<i class="fas fa-file-export"></i> Generate Code';
          return;
        }
      }

      // Get the state of the Split Text Lines toggle
      const splitTextLines = splitTextToggle.checked;

      // Send export request to the main plugin code with the toggle states and background URL
      parent.postMessage({
        pluginMessage: {
          type: 'export-html',
          splitTextLines,
          backgroundEnabled: isBackgroundEnabled,
          backgroundUrl
        }
      }, '*');
    };

    // Handle Copy to Clipboard Button Click
    copyButton.onclick = () => {
      const code = editor.getValue();
      if (!code) {
        showMessage('No code to copy. Please generate the code first.', true);
        return;
      }

      // Create a temporary textarea to facilitate copying
      const tempTextArea = document.createElement('textarea');
      tempTextArea.value = code;
      document.body.appendChild(tempTextArea);
      tempTextArea.select();
      try {
        document.execCommand('copy');
        showMessage('Code copied to clipboard!', false);
      } catch (err) {
        console.error('Failed to copy code:', err);
        showMessage('Failed to copy code.', true);
      }
      document.body.removeChild(tempTextArea);
    };

    /**
     * Displays a message to the user.
     * @param {string} msg - The message to display.
     * @param {boolean} isError - Whether the message is an error.
     */
    function showMessage(msg, isError) {
      messageDiv.textContent = msg;
      messageDiv.style.color = isError ? '#ff6666' : '#66ff66';
      messageDiv.classList.add('show');
      setTimeout(() => {
        messageDiv.classList.remove('show');
      }, 3000);
    }

    // Handle Password Submission
    submitPasswordButton.onclick = () => {
      const enteredPassword = passwordInput.value.trim();
      if (enteredPassword === '') {
        passwordError.textContent = 'Password cannot be empty.';
        passwordError.style.display = 'block';
        return;
      }

      // Send the entered password to the plugin code for verification
      parent.postMessage({
        pluginMessage: {
          type: 'password-submit',
          password: enteredPassword
        }
      }, '*');
    };

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

    // Listen for messages from the plugin code
    window.onmessage = (event) => {
      console.log('Received message from plugin:', event.data.pluginMessage); // Debugging log
      const msg = event.data.pluginMessage;

      if (msg.type === 'password-accepted') {
        // Hide the password modal and show the main UI
        passwordModal.style.display = 'none';
        document.getElementById('mainUI').style.display = 'flex';
      } else if (msg.type === 'html') {
        // Populate the editor with the exported HTML
        editor.setValue(msg.html);
        // Re-enable the generate button
        generateButton.disabled = false;
        generateButton.innerHTML = '<i class="fas fa-file-export"></i> Generate Code';
        // Show success message
        showMessage('HTML generated successfully!', false);
      } else if (msg.type === 'error') {
        // Show error message
        showMessage(msg.error, true);
        // Re-enable the generate button
        generateButton.disabled = false;
        generateButton.innerHTML = '<i class="fas fa-file-export"></i> Generate Code';
      }
    };
  </script>
</body>
</html>
