var formContainer           = document.getElementById('form-container');
var openAiAppShortcode      = document.getElementById('ai-app-onsite-openAi-app-shortcode');
var formContainer           = document.querySelector('.ai_app_onsite_openAi_app_form');
var testAppContainer        = document.getElementById('test-app-container');
var previewActionContainer  = document.getElementById('preview-action-container');
var systemSettingsContainer = document.getElementById('system-settings-container');
var shortcodeBox            = document.getElementById('shortcode-box');
var gutenbergBlock          = document.getElementById('openAi-app-gutenberg-block');

function ai_app_onsite_create_app_preview_form(is_preview_button = false) {
    var loader = document.getElementById('loader');

    const appCorner = document.getElementById('app-corner').value;
    const appHeight = document.getElementById('app-height').value;
    const appWidth  = document.getElementById('app-width-figure').value;

    var xhr = new XMLHttpRequest();

    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
            if(is_preview_button){
                loader.style.display = 'none';
            }

            if (xhr.status === 200) {
                response = JSON.parse(xhr.responseText);

                if (response.status === '404' || response.status === '400') {
                    formContainer.innerHTML = '<p>' + response.message + '</p>';
                    openAiAppShortcode.value = '';
                    testAppContainer.style.display = 'none';
                    previewActionContainer.style.display = 'none';
                    shortcodeBox.style.display = 'none';
                    systemSettingsContainer.style.display = 'none';
                    return;
                } else {
                    formContainer.innerHTML = '';
                    testAppContainer.style.display = 'block';
                    previewActionContainer.style.display = 'block';
                    shortcodeBox.style.display = 'flex';
                    systemSettingsContainer.style.display = 'block';
                    // Replace form content
                    formContainer.innerHTML = response?.form_html;
                }
               

                // Set the data recevied from db
                ai_app_onsite_set_app_preview_properties_data(response?.appropriates, is_preview_button);
                aiAppInitColorPopup();

                var parser = new DOMParser();
                var doc = parser.parseFromString(response?.form_html, 'text/html');

                // Find the element with the class
                var element = doc.querySelector('.ai-app-preview-form-heading');

                var shortCodeGenerated = doc.querySelector('input[name="short_code_generated"]').value;


                // Get the text content of the element
                var value = element ? element.textContent : null;
                var gutenberg_block = value;
                if (gutenberg_block) {
                    gutenberg_block = value;
                } else {
                    gutenberg_block = 'AI App Onsite';
                }

                if (value) {
                    value = value.split(' ').map(function (word) {
                        return word.charAt(0).toLowerCase() + word.slice(1).toLowerCase();
                    }).join('_');
                } else {
                    value = 'aiapp';
                }

                openAiAppShortcode.value = `[${shortCodeGenerated}]`;

                const parts = shortCodeGenerated.split("_aiao");

                gutenbergBlock.value = parts[0] + ' Aiao';
                localStorage.setItem('app_Title', parts[0]);
                localStorage.setItem('app_Title_gutenberg_block', parts[0]);

                testAppContainer.style.display = 'block';
                previewActionContainer.style.display = 'block';
                shortcodeBox.style.display = 'flex';
                systemSettingsContainer.style.display = 'block';
                if (formContainer) {
                    // Find the submit button inside the form
                    var submitButton = formContainer.querySelector('button[type="button"]');
                    if (submitButton) {
                        // Disable the submit button
                        submitButton.disabled = true;
                    }
                }
                var messageContainer = document.getElementById('app-properties-msg-container-preview');
                if(is_preview_button){
                    messageContainer.innerHTML = '<span style="color: green;">App Preview has been updated successfully.</span>';
                }
                setTimeout(function () {
                    messageContainer.innerHTML = '';
                    const appPreviewSettingsFormTracker = trackFormChanges('#app_preview_settings_form');
                    window.FormChangeRegistry.register('app_preview_settings', appPreviewSettingsFormTracker, 'app-preview');
            
                    document.getElementById('save_ai_app_app_properties_data').addEventListener('click', function () {
                        appPreviewSettingsFormTracker.reset();
                    });
                }, 1000);
            } 
        }
    };

    xhr.open('POST', myPluginAjax.ajaxurl, true);
    if(is_preview_button){
        loader.style.display = 'flex';
    }

    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
    const postData = new URLSearchParams();

    var titleColors = aiAppBuildColorArray('title-color', 'title_color', false);
    var fontColor = aiAppBuildColorArray('font-color', 'font_color', false);
    var bgColor = aiAppBuildColorArray('bg-color', 'bg_color', true);
    var btnColors = aiAppBuildColorArray('btn-color', 'btn_color', true);
    var btnFontColors = aiAppBuildColorArray('btn-font-color', 'btn_font_color', false);
    var responseBgColors = aiAppBuildColorArray('response-bg-color', 'response_bg_color', true);

    postData.append('title_color', JSON.stringify(titleColors));
    postData.append('font_color', JSON.stringify(fontColor));
    postData.append('btn_color', JSON.stringify(btnColors));
    postData.append('btn_font_color', JSON.stringify(btnFontColors));
    postData.append('response_bg_color', JSON.stringify(responseBgColors));
    postData.append('background_color', JSON.stringify(bgColor));
    postData.append('action', 'ai_app_onsite_create_app_preview_form');
    postData.append('app_corner', appCorner);
    postData.append('app_height', appHeight);
    postData.append('app_width', appWidth);
    postData.append('is_preview_button', is_preview_button)

    xhr.send(postData.toString());
}

function ai_app_onsite_set_app_preview_properties_data(response, is_preview) {
    if (!Array.isArray(response) || response.length === 0) {
        console.error("Response is empty or not an array.");
        return;
    }

    var firstObject        = response[0];
    var title_colors       = JSON.parse(firstObject.title_color);
    var font_colors        = JSON.parse(firstObject.font_color);
    var bg_colors          = JSON.parse(firstObject.bg_color);
    var btn_colors         = JSON.parse(firstObject.btn_color);
    var btn_font_colors    = JSON.parse(firstObject.btn_font_color);
    var response_bg_colors = JSON.parse(firstObject.response_bg_color);


    setTimeout(function () {
      var selected_title_color = getSelectedTitleColor(title_colors);
      var selected_font_colors = getSelectedFontColor(font_colors);
      var selected_bg_colors = getSelectedBgColor(bg_colors);
      var selected_btn_colors = getSelectedBtnBgColor(btn_colors);
      var selected_btn_font_colors = getSelectedBtnFontColor(btn_font_colors);
      var selected_response_bg_colors = getSelectedResponseBgColor(response_bg_colors);

      var selected_title_value = aiAppComparableColorValue(selected_title_color);
      var selected_font_value = aiAppComparableColorValue(selected_font_colors);
      var selected_bg_value = aiAppComparableColorValue(selected_bg_colors);
      var selected_btn_value = aiAppComparableColorValue(selected_btn_colors);
      var selected_btn_font_value = aiAppComparableColorValue(selected_btn_font_colors);
      var selected_response_bg_value = aiAppComparableColorValue(selected_response_bg_colors);

      aiAppApplyBackgroundStyle(document.getElementById("response-bg-preview"), selected_response_bg_colors);
      var response_header_text = firstObject.response_header || "Response Header";
      var headingColor = aiAppNormalizeColorValue(selected_font_colors);
      document.getElementById("ai-app-motivational-heading").innerHTML = '<h6 style="color: ' + headingColor + ';margin-bottom: 0;">'+response_header_text+'</h6>';

      var radioInputs = document.querySelectorAll(
        '.input-group-color input[type="radio"]'
      );

      radioInputs.forEach(function (radio) {
        var label = radio.closest("label");
        var colorWithoutHash = radio.value.replace(/^#/, "");
        var type = radio.name;

        // Remove previously added class in all cases
        label.classList.remove(colorWithoutHash);

        // Apply for Title Color
        if (type === "title-color" && radio.value === selected_title_value) {
          label.classList.add(colorWithoutHash);
          label.click();
        }

        // Apply for Font Color
        if (type === "font-color" && radio.value === selected_font_value) {
          label.classList.add(colorWithoutHash);
          label.click();
        }

        // Apply for Bg Color
        if (type === "bg-color" && radio.value === selected_bg_value) {
          label.classList.add(colorWithoutHash);
          label.click();
        }

        // Apply for Button Color
        if (type === "btn-color" && radio.value === selected_btn_value) {
            label.classList.add(colorWithoutHash);
            label.click();
        }

        // Apply for Button Font Color
        if (
            type === "btn-font-color" &&
            radio.value === selected_btn_font_value
        ) {
            label.classList.add(colorWithoutHash);
            label.click();
        }

        // Apply for Response Bg Color
        if (
            type === "response-bg-color" &&
            radio.value === selected_response_bg_value
        ) {
            label.classList.add(colorWithoutHash);
            label.click();
        }
      });
    }, 100);

    applyColorSelection({ data: title_colors,       baseKey: "title_color",        inputName: "title-color" });
    applyColorSelection({ data: font_colors,        baseKey: "font_color",         inputName: "font-color" });
    applyColorSelection({ data: bg_colors,          baseKey: "bg_color",           inputName: "bg-color" });
    applyColorSelection({ data: btn_colors,         baseKey: "btn_color",          inputName: "btn-color" });
    applyColorSelection({ data: btn_font_colors,    baseKey: "btn_font_color",     inputName: "btn-font-color" });
    applyColorSelection({ data: response_bg_colors, baseKey: "response_bg_color",  inputName: "response-bg-color" });

    var app_corner = firstObject.app_corner;
    var app_height = firstObject.app_height;
    var app_width  = firstObject.app_width;

    document.getElementById("app-corner").value       = app_corner || "soft-corner";
    document.getElementById("app-height").value       = app_height || "slight-lift";
    document.getElementById("app-width-figure").value = app_width || "70";

    document.getElementById('app-corner').setAttribute('name', 'app_corner');
    document.getElementById('app-height').setAttribute('name', 'app_height');
    document.getElementById("app-width-figure").setAttribute("name", "app_width_figure");

    
}
function getSelectedTitleColor(data) {
    for (var i = 0; i < data.length; i++) {
        if (data[i].hasOwnProperty('title_color_selected')) {
            return data[i].title_color_selected;
        }
    }
    return null;
}
function getSelectedFontColor(data) {
    for (var i = 0; i < data.length; i++) {
        if (data[i].hasOwnProperty('font_color_selected')) {
            return data[i].font_color_selected;
        }
    }
    return null;
}
function getSelectedBgColor(data) {
    for (var i = 0; i < data.length; i++) {
        if (data[i].hasOwnProperty('bg_color_selected')) {
            return data[i].bg_color_selected;
        }
    }
    return null;
}
function getSelectedBtnBgColor(data){
    for (var i = 0; i < data.length; i++) {
        if (data[i].hasOwnProperty('btn_color_selected')) {
            return data[i].btn_color_selected;
        }
    }
    return null;
}
function getSelectedBtnFontColor(data){
    for (var i = 0; i < data.length; i++) {
        if (data[i].hasOwnProperty('btn_font_color_selected')) {
            return data[i].btn_font_color_selected;
        }
    }
    return null;
}
function getSelectedResponseBgColor(data){
    for (var i = 0; i < data.length; i++) {
        if (data[i].hasOwnProperty('response_bg_color_selected')) {
            return data[i].response_bg_color_selected;
        }
    }
    return null;
}

/* Test app */
function ai_app_onsite_test_from() {

    // Show loader
    var loader = document.getElementById('loader');
    var aiappTestResponse = document.getElementById('ai-app-onsite-test-response');
    var aiappOnsitePropertiesNonce = document.getElementById('ai_app_onsite_properties_nonce_field').value;

    var xhr = new XMLHttpRequest();

    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
            var messageContainer = document.getElementById('model-settings-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 AI result
                        aiappTestResponse.innerHTML = response.data;
                    } else {
                        // Show error message if request fails
                        aiappTestResponse.innerHTML = '<span style="color: red;">Error: ' + response.data + '</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();

    // Select the form element
    var form = document.querySelector('.ai_app_onsite_openAi_app_form form');

    if (!validateForm(form)) {
        return; // Exit if form validation fails
    } else {
        formData = validateForm(form);
        loader.style.display = 'flex';

        // If all required fields are filled, continue with form submission
        formData.append('aiappOnsitePropertiesNonce', aiappOnsitePropertiesNonce);
        // Append action to form data
        formData.append('action', 'ai_app_onsite_openAi_api');

        // Send the form data
        xhr.send(formData);
    }
}

function ai_app_onsite_update_style_properties_only() {
    // Clear all previous error messages
    document.querySelectorAll('.fields-error').forEach(function (error) {
        error.textContent = '';
    });

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

    // Create and send AJAX request
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
            var messageContainer = document.getElementById('app-properties-msg-container-preview');
            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>';

                        ai_app_onsite_create_app_preview_form(true);
                    } 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);

    // Create FormData object
    var formData = new FormData();

    // Gather form data
    formData.append('action', 'ai_app_onsite_update_style_properties_only');

    var titleColors = aiAppBuildColorArray('title-color', 'title_color', false);
    var fontColor = aiAppBuildColorArray('font-color', 'font_color', false);
    var bgColor = aiAppBuildColorArray('bg-color', 'bg_color', true);
    var btnColor = aiAppBuildColorArray('btn-color', 'btn_color', true);
    var btnFontColor = aiAppBuildColorArray('btn-font-color', 'btn_font_color', false);
    var responseBgColor = aiAppBuildColorArray('response-bg-color', 'response_bg_color', true);

    formData.append('titleColors', JSON.stringify(titleColors));
    formData.append('fontColor', JSON.stringify(fontColor));
    formData.append('bgColor', JSON.stringify(bgColor));
    formData.append('btnColor', JSON.stringify(btnColor));
    formData.append('btnFontColor', JSON.stringify(btnFontColor));
    formData.append('responseBgColor', JSON.stringify(responseBgColor));

    var appWidth  = document.getElementById('app-width-figure').value.trim() ? document.getElementById('app-width-figure').value.trim() : '70';
    var appCorner = document.getElementById('app-corner').value.trim();
    var appHeight = document.getElementById('app-height').value.trim();
    formData.append('app-corner', appCorner);
    formData.append('app-height', appHeight);
    formData.append('app-width', appWidth);

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

    xhr.send(formData);
}

function validateForm(form) {
    // Check if form exists
    if (!form) {
        console.error('Form not found.');
        return false; // Exit if form is not found
    }

    // Create a new FormData object to store form data
    var formData = new FormData();

    // Select all input, select, and textarea elements within the form
    var fields = form.querySelectorAll('input, select, textarea, number');
    // Flag to keep track of validation status
    var isValid = true;

    // Iterate over each field
    fields.forEach(function (field) {


        var errorParagraph = document.getElementById(field.id + '-error'); // Get the error paragraph for this field

        if (!errorParagraph) {
            console.error('Error paragraph not found for field with ID:', field.id);
            return; // Exit the loop if error paragraph is not found
        }

        // Check if the field is required and its value is empty
        if (field.hasAttribute('required') && field.value.trim() === '') {
            var error = 'This field is required.';
            errorParagraph.textContent = error;
            isValid = false;
            field.classList.add('invalid');
        } else {
            field.classList.remove('invalid');
            errorParagraph.textContent = ''; // Clear error message
        }

        // Append field's ID, name, and value to the formData object
        formData.append(field.name, field.value);

        // Listen for input/change event to remove error message when field value changes
        field.addEventListener('input', function () {
            if (field.value.trim() !== '') {
                errorParagraph.textContent = ''; // Clear error message if field is not empty
                field.classList.remove('invalid');
            }
        });
    });

    // If any required field is empty, show an alert and prevent form submission
    if (!isValid) {
        return false; // Form is invalid
    }

    return formData; // Return form data if form is valid
}

function openAi_app_copy_shortcode(divId) {
    // Get the div element
    var copyDiv = document.getElementById(divId);

    // Create a temporary textarea element
    var tempTextArea = document.createElement("textarea");

    // Set the value of the textarea to the text content of the div
    tempTextArea.value = copyDiv.textContent;

    // Append the textarea to the body (required for the copy command to work)
    document.body.appendChild(tempTextArea);

    // Select the text inside the textarea
    tempTextArea.select();
    tempTextArea.setSelectionRange(0, 99999); // For mobile devices

    // Copy the text inside the textarea
    document.execCommand("copy");

    // Delay the removal of the temporary textarea to show the blue selection
    setTimeout(function () {
        document.body.removeChild(tempTextArea);
    }, 100); // Adjust the delay time as needed
}

function ai_app_onsite_openAi_app_shortcode() {
    var inputField = document.querySelector("#ai-app-onsite-openAi-app-shortcode");
    inputField.select();
    inputField.setSelectionRange(0, 99999); // For mobile devices
    document.execCommand("copy");
}

function ai_app_onsite_openAi_app_gutenberg_block() {
    var inputField = document.querySelector("#openAi-app-gutenberg-block");
    inputField.select();
    inputField.setSelectionRange(0, 99999); // For mobile devices
    document.execCommand("copy");
}

jQuery('body').on('click', '.assets-copy-icon', function () {
    ai_app_onsite_openAi_app_shortcode();
    var copyText;
    if (jQuery(this).closest('.col-lg-6').find('#ai-app-onsite-openAi-app-shortcode').length) {
        ai_app_onsite_openAi_app_shortcode();
    } else if (jQuery(this).closest('.col-lg-6').find('#openAi-app-gutenberg-block').length) {
        ai_app_onsite_openAi_app_gutenberg_block();
    } else {
        copyText = jQuery('#openai-key')[0];
    }

});


jQuery('body').on('click', '.copy-span', function (e) {
    const span = this;  // The clicked span element
    const textToCopy = span.textContent;

    // Create a temporary input element to copy the text
    const tempInput = document.createElement('input');
    document.body.appendChild(tempInput);

    // Set the value of the input to the text of the span
    tempInput.value = textToCopy;

    // Select the content in the input
    tempInput.select();
    tempInput.setSelectionRange(0, 99999); // For mobile devices

    // Copy the content to clipboard
    try {
        document.execCommand('copy');
    } catch (err) {
        console.error('Unable to copy text', err);
    }

    // Remove the temporary input element
    document.body.removeChild(tempInput);

    // Create a tooltip to show the copied text near the mouse cursor
    const tooltip = document.createElement('div');
    tooltip.textContent = 'Copied to clipboard: ' + textToCopy;
    tooltip.style.position = 'absolute';
    tooltip.style.left = `${e.pageX + 10}px`; // Slight offset from mouse position
    tooltip.style.top = `${e.pageY + 10}px`;
    tooltip.style.padding = '5px 10px';
    tooltip.style.backgroundColor = 'rgba(0, 0, 0, 0.7)';
    tooltip.style.color = '#fff';
    tooltip.style.borderRadius = '5px';
    tooltip.style.fontSize = '14px';
    tooltip.style.zIndex = '9999';
    tooltip.style.pointerEvents = 'none'; // Tooltip shouldn't interfere with clicks

    // Append the tooltip to the body
    document.body.appendChild(tooltip);

    // Remove the tooltip after 2 seconds
    setTimeout(function () {
        document.body.removeChild(tooltip);
    }, 2000);
});

document.addEventListener('change', function (event) {
    if (
        event.target.matches('input[type="radio"][name="title-color"]') ||
        event.target.matches('input[type="radio"][name="font-color"]') ||
        event.target.matches('input[type="radio"][name="bg-color"]')  || 
        event.target.matches('input[type="radio"][name="btn-color"]') ||
        event.target.matches('input[type="radio"][name="btn-font-color"]') ||
        event.target.matches('input[type="radio"][name="response-bg-color"]')
    ) {
        
        // Remove checked attribute from all radios in the same group
        const name = event.target.name;
        const allRadios = document.querySelectorAll(`input[type="radio"][name="${name}"]`);
        allRadios.forEach(function (radio) {
            radio.removeAttribute('checked');
        });
        // Set checked attribute on selected one
        event.target.setAttribute('checked', 'checked');
    }
});
