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

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

    // Update underline position
    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 => {
            if (content.id === tabName) {
                content.classList.add("active-content");
            } else {
                content.classList.remove("active-content");
            }
        });
    }

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

    // Click event for tabs
    tabs.forEach(tab => {
        tab.addEventListener("click", function (event) {
            event.preventDefault();

            // Remove active class from all tabs
            tabs.forEach(t => t.classList.remove("active"));

            // Add active class to clicked tab
            this.classList.add("active");

            // Update underline position
            updateUnderline();

            // Show corresponding tab content
            const tabName = this.getAttribute("data-tab");
            showContent(tabName);

            // Update the URL
            updateUrl(tabName);
        });
    });

    // Check the URL for the active tab on page load
    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");
            // Force a reflow and update underline after adding active class
            requestAnimationFrame(() => {
                updateUnderline();
                showContent(currentTab);
            });
        }
    } else {
        // Default to the first tab if no path is specified in the URL
        if (tabs.length > 0) {
            const firstTab = tabs[0];
            firstTab.classList.add("active");
            // Force a reflow and update underline
            requestAnimationFrame(() => {
                updateUnderline();
                showContent(firstTab.getAttribute("data-tab"));
            });
        }
    }

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

// JavaScript function to update the URL without page refresh
function go_to_page(pageUrl) {
    // Construct the new URL based on the provided page URL
    const newUrl = pageUrl.includes('?') ? pageUrl : `${pageUrl}?path=${new URL(pageUrl).searchParams.get('page')}`;

    // Use pushState to change the URL without reloading the page
    history.pushState(null, '', newUrl);
}

// Function to handle URL changes on page load or refresh
function handleUrlChange() {
    const currentUrl = new URL(window.location.href);
    const page = currentUrl.searchParams.get('page');

    // Optional: Load content based on the page parameter (if necessary)
    if (page) {
        // console.log(`You are now on the ${page} page.`);
        // Add logic to load content or perform actions based on the page
    }
}

// Listen for popstate event when user clicks browser back/forward buttons
window.addEventListener('popstate', handleUrlChange);

// Call handleUrlChange on page load to ensure the correct content is displayed
document.addEventListener("DOMContentLoaded", handleUrlChange);

/**
 * 
 * This code handles all the template
 * 
 */
// Function to activate a template when a button is clicked
function activateTemplate(button) {
    const templateId = button.getAttribute('data-template-id');
    const templateTitle = button.getAttribute('data-template-title');
    const category = button.getAttribute('data-template-category');
    const nonce = button.getAttribute('data-nonce');

    button.textContent = 'Activating...';

    const formData = new URLSearchParams();
    formData.append('action', 'author_kit_activate_template');
    formData.append('template_id', templateId);
    formData.append('category', category);
    formData.append('nonce', nonce);

    fetch(author_kit_template_activation_vars.ajaxurl, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: formData.toString(),
    })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                button.textContent = 'Activated';
                button.disabled = true;
                button.classList.remove('ct-button-primary');
                button.classList.add('ct-button-success');

                document.querySelectorAll(`.activate-template-button[data-template-category="${category}"]`).forEach(otherButton => {
                    if (otherButton !== button) {
                        otherButton.textContent = 'Activate';
                        otherButton.disabled = false;
                        otherButton.classList.remove('ct-button-success');
                        otherButton.classList.add('ct-button-primary');
                    }
                });

                const demoActions = button.closest('.ct-demo-actions');
                if (demoActions) {
                    const previewLink = demoActions.querySelector('.ct-button');
                    if (previewLink && data.data && data.data.customizer_link) {
                        previewLink.textContent = 'Customize';
                        previewLink.setAttribute('href', data.data.customizer_link);
                    }
                }

                // console.log(`Template "${templateTitle}" activated successfully.`);
                show_author_kit_toast(`Template "${templateTitle}" activated successfully.`, 'success');

                setTimeout(function () {
                    location.reload();
                }, 1000);
            } else {
                let errorMessage = 'Template Activation Failed.';
                if (data.data && data.data.message) {
                    errorMessage += ` Reason: ${data.data.message}`;
                }
                console.error('Template activation failed:', data);
                show_author_kit_toast(errorMessage, 'error');
            }
        })
        .catch(error => {
            console.error('Network or server error occurred:', error);
            show_author_kit_toast('Network Error: Unable to activate template. Please check your connection or try again later.', 'error');
        });
}

document.addEventListener('DOMContentLoaded', function () {
    const bioToggleSwitch = document.getElementById('awp-enable-template-bio-box-switch');
    const archiveToggleSwitch = document.getElementById('awp-enable-template-bio-archive-switch');
    const bylineToggleSwitch = document.getElementById('awp-enable-template-byline-switch');

    const bioActiveStatusMessage = document.getElementById('template-activation-message-bio');
    const archiveActiveStatusMessage = document.getElementById('template-activation-message-archive');
    const bylineActiveStatusMessage = document.getElementById('template-activation-message-byline');
    const bioStatusLabel = document.getElementById('switch-label-bio-box-status');
    const archiveStatusLabel = document.getElementById('switch-label-archive-page-status');
    const bylineStatusLabel = document.getElementById('switch-label-byline-status');

    function setToggleState(toggleSwitch, state) {
        if (toggleSwitch) {
            toggleSwitch.checked = state;
        }
    }

    fetch(author_kit_switch_ajax_object_vars.ajaxurl, {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: new URLSearchParams({
            action: 'author_kit_fetch_toggle_states',
            nonce: author_kit_switch_ajax_object_vars.nonce
        })
    })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                setToggleState(bioToggleSwitch, data.data.bio);
                setToggleState(archiveToggleSwitch, data.data.archive);
                setToggleState(bylineToggleSwitch, data.data.byline);

                updateStatus(bioToggleSwitch?.checked || false, bioActiveStatusMessage, bioStatusLabel, 'bio');
                updateStatus(archiveToggleSwitch?.checked || false, archiveActiveStatusMessage, archiveStatusLabel, 'archive');
                updateStatus(bylineToggleSwitch?.checked || false, bylineActiveStatusMessage, bylineStatusLabel, 'byline');
            } else {
                console.error('Failed to fetch toggle states:', data.message);
                show_author_kit_toast('Unable to retrieve toggle states. Please reload or check console for errors.', 'error');
            }
        })
        .catch(error => {
            console.error('Error occurred while fetching toggle states:', error);
            show_author_kit_toast('Error fetching toggle states. Please try again later.', 'error');
        });

    function addToggleListener(toggleSwitch, type, messageElement, labelElement) {
        if (toggleSwitch) {
            toggleSwitch.addEventListener('change', function () {
                const newState = this.checked;
                fetch(author_kit_switch_ajax_object_vars.ajaxurl, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                    body: new URLSearchParams({
                        action: 'author_kit_toggle_author_bio_display',
                        state: newState,
                        setting_type: type,
                        nonce: author_kit_switch_ajax_object_vars.nonce
                    })
                })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            // console.log(`${type} display state updated:`, data.data);

                            // Determine readable state
                            const isEnabled = newState === true || newState === 'checked' || newState === 1;
                            const stateLabel = isEnabled ? 'enabled' : 'disabled';

                            updateStatus(newState, messageElement, labelElement, type);

                            // Show toast with correct status
                            show_author_kit_toast(
                                `"${type.charAt(0).toUpperCase() + type.slice(1)}" feature ${stateLabel} successfully.`,
                                'success'
                            );
                        }
                        else {
                            console.error(`Failed to update ${type} state:`, data.message);
                            show_author_kit_toast(`Failed to update "${type}" setting.`, 'error');
                        }
                    })
                    .catch(error => {
                        console.error('Error occurred while updating toggle state:', error);
                        show_author_kit_toast(`Error updating "${type}" setting. Please try again later.`, 'error');
                    });
            });
        }
    }

    addToggleListener(bioToggleSwitch, 'bio', bioActiveStatusMessage, bioStatusLabel);
    addToggleListener(archiveToggleSwitch, 'archive', archiveActiveStatusMessage, archiveStatusLabel);
    addToggleListener(bylineToggleSwitch, 'byline', bylineActiveStatusMessage, bylineStatusLabel);

    function updateStatus(isChecked, messageElement, labelElement, type) {
        let message = '';

        if (type === 'bio') {
            message = isChecked
                ? 'Author Bio is enabled. Customize it in the Customizer.'
                : 'Author Bio is disabled. Please enable it to use.';
        } else if (type === 'archive') {
            message = isChecked
                ? 'Author Archive is enabled. Customize it in the Customizer.'
                : 'Author Archive is disabled. Please enable it to use.';
        } else if (type === 'byline') {
            message = isChecked
                ? 'Author Byline is enabled. Customize it in the Customizer.'
                : 'Author Byline is disabled. Please enable it to use.';
        }


        if (messageElement) {
            messageElement.textContent = message;
        }
    }
});
