var removeLogoBtn = document.getElementById('remove-logo-btn');
var previewImage = document.getElementById('previewImage');
var fileUploadDiv = document.getElementById('file-upload-div');

// === Save & Restore Tab using Cookie ===
document.addEventListener('DOMContentLoaded', function () {
    function getCookie(name) {
        return document.cookie
            .split('; ')
            .find(row => row.startsWith(name + '='))
            ?.split('=')[1] || '';
    }

    function deleteCookie(name) {
        document.cookie = name + '=; path=/; max-age=0';
    }

    const savedTabId = getCookie('ai_app_onsite_active_tab');
    const fallbackTabId = 'plugin-settings-tab';

    const isFreshInstall = myPluginAjax.isFreshInstall == '1' ? true : false;

    if (isFreshInstall) {
        deleteCookie('ai_app_onsite_active_tab');
        handleTabClick(fallbackTabId); // Activate the default tab
    } else if (savedTabId) {
        handleTabClick(savedTabId); // Activate the saved tab
    } else {
        handleTabClick(fallbackTabId); // Activate the default tab
    }

    document.querySelectorAll('a.open-new-tab').forEach(function (link) {
        link.setAttribute('target', '_blank');
        link.setAttribute('rel', 'noopener noreferrer');
    });

    const observer = new MutationObserver(function (mutationsList) {
        mutationsList.forEach(function (mutation) {
            mutation.addedNodes.forEach(function (node) {
                if (node.nodeType === 1) {
                    if (node.matches('a.open-new-tab')) {
                        node.setAttribute('target', '_blank');
                        node.setAttribute('rel', 'noopener noreferrer');
                    } else {
                        // Also check any child links inside
                        node.querySelectorAll('a.open-new-tab').forEach(function (link) {
                            link.setAttribute('target', '_blank');
                            link.setAttribute('rel', 'noopener noreferrer');
                        });
                    }
                }
            });
        });
    });
    
    observer.observe(document.body, { childList: true, subtree: true });

    const textareaDescription = document.getElementById("app-description");
    observeTextareaTransitions(textareaDescription, {
        onFilled: () => {
            updateCharacterCount && updateCharacterCount();
        },
        onEmptied: () => {
            updateCharacterCount && updateCharacterCount();
        }
    });

    const textareaDisclaimer = document.getElementById("app-disclaimer");
    observeTextareaTransitions(textareaDisclaimer, {
        onFilled: () => {
            updateCharacterCountDisclaimer && updateCharacterCountDisclaimer();
        },
        onEmptied: () => {
            updateCharacterCountDisclaimer && updateCharacterCountDisclaimer();
        }
    });
});

// Utility: observe empty -> filled and filled -> empty transitions
function observeTextareaTransitions(textarea, { onFilled, onEmptied } = {}) {
  if (!textarea) return;

  let wasEmpty = !textarea.value.trim();

  // 1) User-driven changes
  const handle = () => {
    const isEmpty = !textarea.value.trim();
    if (wasEmpty && !isEmpty) onFilled && onFilled();
    else if (!wasEmpty && isEmpty) onEmptied && onEmptied();
    wasEmpty = isEmpty;
  };

  textarea.addEventListener('input', handle);
  textarea.addEventListener('change', handle);

  // 2) Programmatic changes: patch the 'value' setter for THIS instance
  const desc = Object.getOwnPropertyDescriptor(
    HTMLTextAreaElement.prototype,
    'value'
  );

  Object.defineProperty(textarea, 'value', {
    configurable: true,
    get() {
      return desc.get.call(this);
    },
    set(v) {
      const prevEmpty = !desc.get.call(this).trim();
      desc.set.call(this, v);
      const nowEmpty = !desc.get.call(this).trim();
      if (prevEmpty && !nowEmpty) onFilled && onFilled();
      else if (!prevEmpty && nowEmpty) onEmptied && onEmptied();

      // Optional: keep other listeners in sync
      textarea.dispatchEvent(new Event('input', { bubbles: true }));
      wasEmpty = nowEmpty;
    }
  });

  // Return a cleanup if you ever need to detach
  return () => {
    textarea.removeEventListener('input', handle);
    textarea.removeEventListener('change', handle);
    // Optional: restore original descriptor if needed:
    // Object.defineProperty(textarea, 'value', desc);
  };
}

// === Main Tab Click Handler ===

function handleTabClick(tabId) {
    // event.preventDefault();

    var tab = document.getElementById(tabId);

    // Check if the clicked tab is already active
    if (tab.classList.contains('nav-tab-active')) {
        return;
    }

    // Remove active class from all tabs
    var tabs = document.querySelectorAll('.nav-tab');
    tabs.forEach(function (tab) {
        tab.classList.remove('nav-tab-active');
    });

    // Hide all tab contents
    var tabContents = document.querySelectorAll('.tab-content');
    tabContents.forEach(function (content) {
        content.style.display = 'none';
    });

    // Add active class to clicked tab
    tab.classList.add('nav-tab-active');

    // Show corresponding tab content
    var contentId = tabId.replace("tab", "content");
    var content = document.getElementById(contentId);
    if (content) {
        content.style.display = 'block';
    }

    // ✅ Save active tab in cookie for 7 days
    document.cookie = "ai_app_onsite_active_tab=" + tabId + "; path=/; max-age=" + (60 * 60 * 24 * 7);

    // ✅ Custom logic per tab
    if (tabId === 'plugin-settings-tab') {
        ai_app_onsite_get_plugin_settings();
    } else if (tabId === 'app-properties-tab') {
        ai_app_onsite_get_app_properties();
    } else if (tabId === 'model-settings-tab') {
        ai_app_onsite_get_model_settings();
    } else if (tabId === 'field-selector-tab') {
        ai_app_onsite_read_field_selector();
    } else if (tabId === 'prompt-editor-tab') {
        ai_app_onsite_get_Model_Token_field();
        ai_app_onsite_get_field_tags();
        ai_app_onsite_get_prompt_editor();
    } else if (tabId === 'app-preview-tab') {
        ai_app_onsite_create_app_preview_form();
    } else if (tabId === 'email-intregation-tab') {
        ai_app_onsite_get_email_settings();
    }


}


/*function unserialize(serializedString) {
    // Remove the leading 's:' and trailing ';'
    var dataString = serializedString.slice(2, -1);
    
    // Remove the preceding length indicator and trailing quotes from each value
    var valuesArray = dataString.split(',').map(function(value) {
        return value.replace(/^\d+:"|\"$/g, '').trim();
    });
    
    return valuesArray;
}*/

//End get plugin setting from db js


function removeLogoFile(input) {
    removeLogoBtn.style.display = 'none';
    previewImage.style.display = 'none';
    fileUploadDiv.classList.add('col-md-12');
    fileUploadDiv.classList.remove('col-md-8');

    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;
                }
            } 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_remove_app_logo');
}

//upload file js
function validateFile(input) {
    var file = document.getElementById('file-upload').files[0];
    var fileError = document.getElementById('fileError');
    var previewImage = document.getElementById('previewImage');

    // Check if file is selected
    if (!file) {
        fileError.textContent = 'Please select a file.';
        previewImage.style.display = 'none';
        return;
    }

    // Check file type
    var validExtensions = ['image/svg+xml', 'image/png', 'image/jpeg', 'image/gif'];
    if (!validExtensions.includes(file.type)) {
        fileError.textContent = 'Please select a valid image file (SVG, PNG, JPG, or GIF).';
        this.value = ''; // Clear the input field
        previewImage.style.display = 'none';
        return;
    }
    uploadSiteLogo(file);
    input.value = '';
}

function uploadSiteLogo(file) {
    fileUploadDiv.classList.add('col-md-8');
    fileUploadDiv.classList.remove('col-md-12');
    var formData = new FormData();
    formData.append('app-file', file);
    formData.append('action', 'ai_app_onsite_handle_sitelogo_upload');
    // Include nonce field value
    formData.append('ai_app_onsite_app_properties_logo_field_nonce_field', document.getElementById("ai_app_onsite_app_properties_nonce_field").value);


    var xhr = new XMLHttpRequest();
    xhr.open('POST', myPluginAjax.ajaxurl, true);

    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) { // Ensure the request is complete
            if (xhr.status === 200) {
                if (xhr.responseText) { // Check if the response text is not empty
                    try {
                        var response = JSON.parse(xhr.responseText);
                        var app_logo = response.data.file_url;
                        if (app_logo) {
                            var previewImage = document.getElementById('previewImage');
                            previewImage.style.backgroundImage    = `url('${app_logo}')`;
                            previewImage.style.backgroundSize     = 'contain'; // Optional: Adjust background size
                            previewImage.style.backgroundRepeat   = 'no-repeat'; // Optional: Prevent repetition
                            previewImage.style.backgroundPosition = 'center'; // Optional: Center the image
                            previewImage.style.display          = 'block';
                            previewImage.style.width            = '350px';
                            previewImage.style.height           = '160px';
                            previewImage.style.position         = 'relative';
                            removeLogoBtn.style.display         = 'block';
                        }




                        var messageContainer = document.getElementById('app-properties-msg-container');
                        if (messageContainer) {
                            var successMessage = 'App Image Uploaded Successful';
                            if (response.success) {
                                messageContainer.innerHTML = '<span style="color: green;">' + successMessage + '</span>';
                            } else {
                                messageContainer.innerHTML = '<span style="color: red;">Error: ' + response.error + '</span>';
                            }

                            var previewImage = document.getElementById('previewImage');
                            previewImage.src            = response.data;
                            previewImage.style.display  = 'block';
                            removeLogoBtn.style.display = 'block';
                        } else {
                            console.error('messageContainer element not found');
                        }
                    } catch (e) {
                        console.error('Failed to parse response:', e);
                        var messageContainer = document.getElementById('messageContainer');
                        if (messageContainer) {
                            messageContainer.innerHTML = '<span style="color: red;">Error parsing response</span>';
                        } else {
                            console.error('messageContainer element not found');
                        }
                    }
                } else {
                    console.error('Empty response');
                    var messageContainer = document.getElementById('messageContainer');
                    if (messageContainer) {
                        messageContainer.innerHTML = '<span style="color: red;">Empty response</span>';
                    } else {
                        console.error('messageContainer element not found');
                    }
                }
            } else {
                console.error('Request failed with status:', xhr.status);
                var messageContainer = document.getElementById('messageContainer');
                if (messageContainer) {
                    messageContainer.innerHTML = '<span style="color: red;">Error: ' + xhr.status + '</span>';
                } else {
                    console.error('messageContainer element not found');
                }
            }
            // Hide message after 3 seconds
            setTimeout(function () {
                messageContainer.innerHTML = '';
            }, 3000);


        }
    };

    xhr.send(formData);
}


function save_changes() {
    //  Get the active tab ID
    var activeTab = document.querySelector('.nav-tab-active');
    if (!activeTab) {
        console.error('No active tab found');
        return;
    }
    var tabId = activeTab.id;

    // Call the appropriate function based on the active tab
    // This assumes you have functions defined for each tab's save logic
    if (tabId === 'plugin-settings-tab') {
        ai_app_onsite_save_plugin_settings();
    } else if (tabId === 'app-properties-tab') {
        ai_app_onsite_save_app_properties();
    } else if (tabId === 'model-settings-tab') {
        ai_app_onsite_save_model_settings();
    } else if (tabId === 'field-selector-tab') {
        ai_app_onsite_save_field_selector();
    } else if (tabId === 'prompt-editor-tab') {
        ai_app_onsite_save_prompt_editor();
    } else if (tabId === 'app-preview-tab') {
        ai_app_onsite_save_app_preview_form();
    } else if (tabId === 'email-intregation-tab') {
        ai_app_onsite_save_email_settings();
    }
}

// Function to update character count
function updateCharacterCount() {
    var textarea = document.getElementById('app-description');
    var wordCount = document.getElementById('wordCount');
    var appDescriptionError = document.getElementById('app-description-error');
    var maxLength = 5000; // Change this to your desired maximum character count
    var currentLength = textarea.value.length;
    var charactersLeft = maxLength - currentLength;

    appDescriptionError.innerHTML = "";

    wordCount.textContent = charactersLeft + " characters left";

    if (charactersLeft < 0) {
        wordCount.textContent = "Limit exceeded";
        textarea.value = textarea.value.substring(0, maxLength); // Trim excess characters
        charactersLeft = 0; // Update characters left to 0
        alert("Character limit exceeded.");

    }
}

// Bind the function to the input event of the textarea to update count dynamically
var textarea = document.getElementById('app-description');
if (textarea) {
    textarea.addEventListener('input', updateCharacterCount);
}

// Function to update character count for disclaimer textarea
function updateCharacterCountDisclaimer() {
    var textareaDisclaimer = document.getElementById('app-disclaimer');
    var wordCountDisclaimer = document.getElementById('wordCountDisclaimer');
    var appDisclaimerError = document.getElementById('app-disclaimer-error');
    var maxLength = 500; // Change this to your desired maximum character count
    var currentLength = textareaDisclaimer.value.length;
    var charactersLeft = maxLength - currentLength;

    appDisclaimerError.innerHTML = "";

    wordCountDisclaimer.textContent = charactersLeft + " characters left";

    if (charactersLeft < 0) {
        wordCountDisclaimer.textContent = "Limit exceeded";
        textareaDisclaimer.value = textareaDisclaimer.value.substring(0, maxLength); // Trim excess characters
        charactersLeft = 0; // Update characters left to 0
        alert("Character limit exceeded.");

    }
}

// Bind the function to the input event of the textarea to update count dynamically
var textareaDisclaimer = document.getElementById('app-disclaimer');
if (textareaDisclaimer) {
    textareaDisclaimer.addEventListener('input', updateCharacterCountDisclaimer);
}


function change_preview() {
    var btnPreview = document.getElementById('preview-submit-btn-txt');
    var btnTxt = document.getElementById('submit-btn-txt');

    // Check if btnTxt.value is empty, if so, set it to 'Submit'
    btnTxt.value = btnTxt.value === '' ? 'Submit' : btnTxt.value;

    // Set the text content of btnPreview to the value of btnTxt
    btnPreview.textContent = btnTxt.value;
}


//color picker Script
function selectColor(e) {
    var color = e.value;
    var colors = convertHexaToRgba(color);
    var radioId = color.substring(1);

    // Check if radio button already exists
    // var existingLabel = document.querySelector('.input-group-color .' + e.name);

    // existingLabel.remove();

    // if (existingLabel) {
    //     // Change only the style of the existing label's input
    //     var radio = existingLabel.querySelector('input.color');
    //     //radio.className = color;
    //     radio.checked = true;
    //     radio.id = radioId;
    //     radio.value = color;

    //     var span = existingLabel.querySelector('span');
    //     span.style.backgroundColor = colors.rgbaColor;
    //     span.style.border = '1px solid ' + colors.rgbaBorderColor;

    //     createBorder(radioId);

    // } else {
    createLable(e);
    //}
}


function convertHexaToRgba(color) {
    // Convert hexadecimal color to RGBA
    var r = parseInt(color.substring(1, 3), 16);
    var g = parseInt(color.substring(3, 5), 16);
    var b = parseInt(color.substring(5, 7), 16);

    var alpha = 0.7;
    var alphaBorder = 1;
    var alphaBorderBefore = 0.3;

    var rgbaColor = `rgba(${r}, ${g}, ${b}, ${alpha})`;
    var rgbaBorderColor = `rgba(${r}, ${g}, ${b}, ${alphaBorder})`;
    var rgbaBorderBeforeColor = `rgba(${r}, ${g}, ${b}, ${alphaBorderBefore})`;


    return {
        rgbaColor: rgbaColor,
        rgbaBorderColor: rgbaBorderColor,
        rgbaBorderBeforeColor: rgbaBorderBeforeColor
    };
}

function createLable(e) {
    var color = e.value;
    var colors = convertHexaToRgba(color);
    // Remove hash symbol
    var radioId = color.substring(1);

    var existingLabel = document.querySelector('.input-group-color .' + e.name);


    existingLabel.remove();

    // Create the div element
    var newLabel = document.createElement('label');
    newLabel.className = 'color-container ' + e.name;
    // newLabel.style.backgroundColor = color;

    // Create a new radio button element 
    var radio = document.createElement("input");
    radio.type = "radio";
    radio.name = e.name;
    radio.className = 'color';
    radio.id = radioId;
    radio.value = color;

    radio.checked = true;

    var span = document.createElement("span");
    span.className = 'checkmark';
    span.style.backgroundColor = colors.rgbaColor;
    span.style.border = '1px solid ' + colors.rgbaBorderColor;


    // Find the label with class "select-color"
    var selectColorLabel = document.querySelector('.select-color');
    var selectColorLabel = e.parentNode;

    // Insert the new label before the label with class "select-color"
    selectColorLabel.parentNode.insertBefore(newLabel, selectColorLabel);

    // Add the radio button and span to the new label 
    newLabel.appendChild(radio);
    newLabel.appendChild(span);

    createBorder(radioId);
}


function autoCreateLable(e, title_color) {
    var color = e.value;
    var colors = convertHexaToRgba(color);
    // Remove hash symbol
    var radioId = color.substring(1);

    var existingLabel = document.querySelector('.input-group-color .' + e.name);


    existingLabel.remove();

    // Create the div element
    var newLabel = document.createElement('label');
    newLabel.className = 'color-container ' + e.name;
    // newLabel.style.backgroundColor = color;

    // Create a new radio button element 
    var radio = document.createElement("input");
    radio.type = "radio";
    radio.name = e.name;
    radio.className = 'color';
    radio.id = radioId;
    radio.value = color;

    if (title_color) {
        var keys = Object.keys(title_color);
        var key = keys[0];
        if (key == 'title_color_selected') {
            radio.checked = true;
        }
        if (key == 'font_color_selected') {
            radio.checked = true;
        }
        if (key == 'bg_color_selected') {
            radio.checked = true;
        }
    }

    var span = document.createElement("span");
    span.className = 'checkmark';
    span.style.backgroundColor = colors.rgbaColor;
    span.style.border = '1px solid ' + colors.rgbaBorderColor;


    // Find the label with class "select-color"
    var selectColorLabel = document.querySelector('.select-color');
    var selectColorLabel = e.parentNode;

    // Insert the new label before the label with class "select-color"
    selectColorLabel.parentNode.insertBefore(newLabel, selectColorLabel);

    // Add the radio button and span to the new label 
    newLabel.appendChild(radio);
    newLabel.appendChild(span);

    createBorder(radioId);
}

function createBorder(radioId) {

    // Check if the radio button is checked
    var radioButton = document.getElementById(radioId);
    var colors = convertHexaToRgba('#' + radioId);

    if (radioButton && radioButton.checked) {

        // Define your CSS rule
        var cssRule = 'label.color-container.' + radioButton.name + ' input:checked ~ .checkmark:before { background: transparent; border: 2px solid #000 !important; }';

        //var cssRule = ''; 

        // Create a new style element
        var style = document.createElement('style');

        // Append the CSS rule to the style element
        style.appendChild(document.createTextNode(cssRule));

        // Append the style element to the document's head
        document.head.appendChild(style);
    }
}