const { __, _x, _n, sprintf } = wp.i18n;

// Help Page Script
document.addEventListener("DOMContentLoaded", function () {

    document.getElementById('ak-help-form').addEventListener('submit', function (e) {
        e.preventDefault();

        show_author_kit_toast("Sending an Email...", 'performing');

        const form = document.getElementById('ak-help-form');
        const formData = new FormData(form);

        formData.append('action', 'author_kit_help_email');
        formData.append('nonce', author_kit_settings_script_vars.nonce);

        const submitButton = document.getElementById('ak-form-submit');
        submitButton.disabled = true;
        submitButton.textContent = "Sending...";

        try {
            fetch(author_kit_settings_script_vars.ajax_url, {
                method: "POST",
                body: (formData),
            })
                .then((response) => response.json())
                .then((data) => {
                    if (data.success) {
                        show_author_kit_toast(data.data.message, 'success');

                        setTimeout(function () {
                            document.getElementById('ak-help-form').reset();
                        }, 3000);


                    } else {
                        show_author_kit_toast(data.data.message, 'error');
                    }
                })
                .catch((error) => show_author_kit_toast(__("Error Occurred in Request", "author-kit"), 'error'));

        } finally {
            submitButton.disabled = false;
            submitButton.textContent = "🚀 Submit Support Request";
        }
    });

});



// General Settings page Script
document.addEventListener("DOMContentLoaded", function () {
    const tabs = document.querySelectorAll(".nav-link");
    const contents = document.querySelectorAll(".content");
    const underline = document.querySelector(".underline");

    // Update underline position based on the active tab
    function updateUnderline() {
        const activeTab = document.querySelector(".nav-link.active");
        if (activeTab) {
            underline.style.left = `${activeTab.offsetLeft}px`;
            underline.style.width = `${activeTab.offsetWidth}px`;
        }
    }

    // Show content based on the active tab
    function showContent(tabName) {
        contents.forEach(content => {
            content.classList.toggle("active-content", content.id === tabName);
        });
    }

    // Update URL without reloading the page
    function updateUrl(tabName) {
        const urlParams = new URLSearchParams(window.location.search);
        urlParams.set('path', tabName);
        history.pushState(null, '', `${window.location.pathname}?${urlParams.toString()}`);
    }

    // Set active tab and update underline on tab click
    tabs.forEach(tab => {
        tab.addEventListener("click", function (event) {
            event.preventDefault();
            tabs.forEach(t => t.classList.remove("active"));
            this.classList.add("active");
            const tabName = this.getAttribute("data-tab");

            updateUnderline();
            showContent(tabName);
            updateUrl(tabName);
        });
    });

    // Check URL on page load to restore the last active tab
    const urlParams = new URLSearchParams(window.location.search);
    const currentTab = urlParams.get('path');

    if (currentTab) {
        const activeTab = document.querySelector(`.nav-link[data-tab="${currentTab}"]`);
        if (activeTab) {
            activeTab.classList.add("active");
            showContent(currentTab);
        }
    } else {
        // Default to the first tab if no path is specified
        tabs[0].classList.add("active");
        showContent(tabs[0].getAttribute("data-tab"));
    }

    // Ensure underline position is set after active class is applied
    requestAnimationFrame(updateUnderline);

    // Update underline on window resize
    window.addEventListener("resize", updateUnderline);

    // Handle browser back/forward button navigation
    window.addEventListener('popstate', () => {
        const popTab = new URLSearchParams(window.location.search).get('path');
        tabs.forEach(t => t.classList.remove("active"));
        if (popTab) {
            const activeTab = document.querySelector(`.nav-link[data-tab="${popTab}"]`);
            if (activeTab) {
                activeTab.classList.add("active");
                showContent(popTab);
                updateUnderline();
            }
        }
    });


    /**this handles the social icons update */

    const selectDisplay = document.getElementById('selected-platforms-display');
    const multiSelect = document.getElementById('platform-multiselect');

    // Add icon element for open/close toggle
    const toggleIcon = document.createElement('i');
    toggleIcon.className = 'fa-solid fa-chevron-down toggle-icon';
    selectDisplay.appendChild(toggleIcon);

    // Create custom options UI
    const customOptionsList = document.createElement('div');
    customOptionsList.className = 'custom-options-list';

    [...multiSelect.options].forEach(option => {
        const item = document.createElement('div');
        item.className = 'custom-option';
        item.dataset.value = option.value;

        const icon = document.createElement('i');
        icon.className = option.dataset.icon;
        icon.style.color = option.dataset.color;

        const text = document.createElement('span');
        text.textContent = option.textContent;

        const checkIcon = document.createElement('i');
        checkIcon.className = 'fa-solid fa-circle-check';
        checkIcon.style.marginLeft = '8px';
        checkIcon.style.display = 'none'; // Hidden by default

        item.appendChild(icon);
        item.appendChild(text);
        item.appendChild(checkIcon);

        if (option.selected) {
            item.classList.add('selected');
            checkIcon.style.display = 'inline';
        }

        item.addEventListener('click', () => {
            option.selected = !option.selected;
            item.classList.toggle('selected');
            checkIcon.style.display = option.selected ? 'inline' : 'none';
            updateSelectedCount();
        });

        customOptionsList.appendChild(item);
    });

    multiSelect.parentElement.appendChild(customOptionsList);

    // Show/Hide options list with icon toggle
    selectDisplay.addEventListener('click', () => {
        const isOpen = customOptionsList.classList.toggle('show');
        toggleIcon.className = isOpen ? 'fa-solid fa-chevron-up toggle-icon' : 'fa-solid fa-chevron-down toggle-icon';
    });

    // Update selected count
    function updateSelectedCount() {
        const selectedOptions = [...multiSelect.options].filter(opt => opt.selected);
        selectDisplay.childNodes[0].nodeValue = `${selectedOptions.length} Social Platforms Selected`;
    }

    updateSelectedCount();


});






