var availableFields      = document.getElementById("available-fields");
var promptInput          = document.getElementById('quill-editor');
var promptMaxTokenValue  = document.getElementById('prompt-max-token-value');
var promptError          = document.getElementById('prompt-error');
var aiResponseStyle      = document.getElementById('ai-response-style');
var aiResponseTone       = document.getElementById('ai-response-tone');
var egAiOutput           = document.getElementById('eg-ai-output');
let initialPromptContent = '';
let appPromptFormTracker = null;

function onChangePromptInput() {
    // Clear all previous error messages
    var errorElements = document.querySelectorAll('.fields-error'); // Ensure these elements are present
    if (errorElements.length > 0) {
        errorElements.forEach(function (error) {
            error.textContent = ''; // Clear the error message
        });
    }

    // Use Quill API to get the content of the Quill editor
    const promptInputValue = window.quill.getText().trim(); // 'prompt' is the editor ID

    // Target the error message container
    var promptError = document.querySelector('.prompt-error'); // Ensure this selector is correct for your error display element

    var errors = [];

    // Validation: Check if the prompt input is empty
    if (!promptInputValue) {
        errors.push('Prompt is required.');
    }

    // If there are validation errors, display them in the corresponding error container
    if (errors.length > 0) {
        errors.forEach(function (error) {
            if (error === 'Prompt is required.' && promptError) {
                promptError.textContent = error; // Display the error message
            } else {
                console.log("Error container for 'Prompt is required.' not found.");
            }
        });
        return false; // Return false if validation fails
    }

    // If no errors, return true (proceed with form submission or further actions)
    return true;
}

// read Model_Token_field
function ai_app_onsite_get_Model_Token_field() {
    var xhr = new XMLHttpRequest();

    promptMaxTokenValue.innerHTML = '3000';
    promptMaxTokenValue.style.display = 'none';

    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
            if (xhr.status === 200) {

                response = JSON.parse(xhr.responseText);
                if (response.status === '404') {
                    return;
                }
                promptMaxTokenValue.innerHTML = response[0].max_tokens;
                promptMaxTokenValue.style.display = 'none';

            } else {
                // Handle error response
                console.error('Error occurred: ' + xhr.responseText);
            }
        }
    };

    xhr.open('POST', myPluginAjax.ajaxurl, true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
    xhr.send('action=ai_app_onsite_get_Model_Token_field');
}


// read field_tags
function ai_app_onsite_get_field_tags() {
    var xhr = new XMLHttpRequest();

    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
            if (xhr.status === 200) {
                response = JSON.parse(xhr.responseText);
                if (response.status === '404') {
                    return;
                }
                availableFields.innerHTML = '';
                response.forEach(function (value) {
                    var fieldCatcher = document.createElement('span');
                    fieldCatcher.textContent = value.field_tag;
                    fieldCatcher.id = 'aiAppOnsiteVariable' + value.field_tag;
                    fieldCatcher.classList.add('copy-span');
                    availableFields.appendChild(fieldCatcher);
                    availableFields.appendChild(document.createTextNode(' '));
                });
            } else {
                // Handle error response
                console.error('Error occurred: ' + xhr.responseText);
            }
        }
    };

    xhr.open('POST', myPluginAjax.ajaxurl, true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
    xhr.send('action=ai_app_onsite_get_field_tags');
}


// read field_tags
function ai_app_onsite_get_prompt_editor() {
    var xhr = new XMLHttpRequest();

    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
            if (xhr.status === 200) {

                var response = JSON.parse(xhr.responseText);

                if (response.status === '404') {
                    if (typeof window.quill !== "undefined" && window.quill) {
                        window.quill.setText(''); // Clears all content
                    }
                    promptInput.value = '';
                    return;
                }

                // Accessing the first object in the array
                var firstObject = response[0];

                // Access properties of the first object
                var prompt_html = removeSlashes(firstObject.prompt_html);
                var prompt = removeSlashes(firstObject.prompt);
                var ai_response_style = firstObject.ai_response_style;
                var ai_response_tone = firstObject.ai_response_tone;
                var eg_ai_output = firstObject.eg_ai_output;

                // Use quill API to set the value of the WYSIWYG editor
                if (typeof window.quill !== "undefined" && window.quill) {
                    window.quill.root.innerHTML = prompt_html;
                } else {
                    // If quill is not initialized, set the value directly to the textarea
                    promptInput.value = prompt_html;
                }
                initialPromptContent = prompt_html;

                if (ai_response_style) {
                    aiResponseStyle.value = ai_response_style;
                }

                if (ai_response_tone) {
                    aiResponseTone.value = ai_response_tone;
                }
                if (egAiOutput) {
                    egAiOutput.value = eg_ai_output;
                }

            } else {
                // Handle error response
                console.error('Error occurred: ' + xhr.responseText);
            }
        }

        setTimeout(function () {
            initializeFormTracker();
        }, 1500);
    };

    xhr.open('POST', myPluginAjax.ajaxurl, true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
    xhr.send('action=ai_app_onsite_get_prompt_editor');
}

function removeSlashes(input) {
    return input.replace(/\\/g, ''); // Remove all backslashes
}


//Start save model settings JS
function ai_app_onsite_save_prompt_editor() {

    //check Prompt value
    if (onChangePromptInput() === false) {
        return;
    };

    // Show loader
    var loader = document.getElementById('loader');
    loader.style.display = 'flex';

    var xhr = new XMLHttpRequest();

    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
            var messageContainer = document.getElementById('ai_app_onsite_prompt_editor-msg-container');
            // Hide loader after 5 seconds
            setTimeout(function () {
                loader.style.display = 'none';

                if (xhr.status === 200) {
                    // Handle the response from the server
                    var response = JSON.parse(xhr.responseText);
                    if (response.success) {
                        // Show success message
                        messageContainer.innerHTML = '<span style="color: green;"> ' + response.data + '</span>';
                    } else {
                        // Show error message if request fails
                        messageContainer.innerHTML = '<span style="color: red;">Error: ' + response.error + '</span>';
                    }
                } else {
                    // Show error message if request fails
                    messageContainer.innerHTML = '<span style="color: red;">Error: Failed to save data</span>';
                }
                // Hide message after 3 seconds
                setTimeout(function () {
                    messageContainer.innerHTML = '';
                }, 3000);
            }, 2000);
        }
    };

    xhr.open('POST', myPluginAjax.ajaxurl, true);

    var formData = new FormData();

    // Get prompt data from the quill editor
    var promptInputValue = '';

    if (typeof window.quill !== "undefined" && window.quill) {
        promptInputValue = window.quill.root.innerHTML.trim();
    } else if (promptInput) {
        // Fallback if Quill is not loaded, get the value from the textarea
        promptInputValue = promptInput.value.trim();
    }

    var aiResponseStyleValue = aiResponseStyle ? aiResponseStyle.value.trim() : '';
    var aiResponseToneValue = aiResponseTone ? aiResponseTone.value.trim() : '';
    var egAiOutputValue = egAiOutput ? egAiOutput.value.trim() : '';

    // Gather form data api-key
    formData.append('action', 'ai_app_onsite_save_prompt_editor');
    formData.append('prompt', promptInputValue ? promptInputValue : "");
    formData.append('ai_response_style', aiResponseStyleValue !== 'Optional' ? aiResponseStyleValue : "");
    formData.append('ai_response_tone', aiResponseToneValue !== 'Optional' ? aiResponseToneValue : "");
    formData.append('eg_ai_output', egAiOutputValue ? egAiOutputValue : "");

    // Include nonce field value
    formData.append('ai_app_onsite_prompt_editor_nonce_field', document.getElementById("ai_app_onsite_prompt_editor_nonce_field").value);

    xhr.send(formData);
}

function initializeFormTracker() {
  if (typeof quill !== "undefined" && typeof window.quill !== "undefined") {
    const quill = window.quill; // make sure your Quill instance is global if needed

    // Setup form tracker
    const appPromptFormTracker = trackFormChanges('#prompt-editor');
    window.FormChangeRegistry.register('app_prompt_settings', appPromptFormTracker, 'prompt-editor');

    // Save button handler
    const saveBtn = document.getElementById('ai_app_onsite_save_prompt_editor');
    if (saveBtn) {
      saveBtn.addEventListener('click', function (e) {
        e.preventDefault();

        // Reset dirty state and save
        appPromptFormTracker.reset();
        ai_app_onsite_save_prompt_editor();
      });
    }

    // Track changes in Quill content

    quill.on('text-change', function (delta, oldDelta, source) {
      const currentContent = normalizeContent(quill.root.innerHTML);
      const initialContent = normalizeContent(initialPromptContent);
      const hiddenField = document.querySelector('input[name="editor_prompt_aiapp"]');

      if (currentContent !== initialContent) {
        if (hiddenField) hiddenField.value = quill.root.innerHTML;
        appPromptFormTracker.markDirty();
      } else {
        appPromptFormTracker.reset();
      }
    });
  }
}


// Normalization function
function normalizeContent(content) {
  return content
    .replace(/&nbsp;/g, ' ')                  // Convert non-breaking space
    .replace(/<p><br><\/p>/gi, '')            // Remove empty line blocks
    .replace(/<p>\s*<\/p>/gi, '')             // Remove empty paragraphs
    .replace(/<br\s*\/?>/gi, '')              // Remove inline <br> tags
    .replace(/\s+/g, ' ')                     // Collapse extra spaces
    .replace(/>\s+</g, '><')                  // Remove space between tags
    .trim();
}










