/**
 * Guard Dog Admin JavaScript
 * 
 * Handles admin interface interactions for the multi-page
 * admin interface.
 */

(function($) {
    'use strict';

    /**
     * Admin object
     */
    window.GuardDogAdmin = {
        
        /**
         * Initialize admin functionality
         */
        init: function() {
            this.bindEvents();
            this.initTooltips();
            this.initFormValidation();
        },

        /**
         * Initialize a scoped tabbed interface that persists state in the URL.
         *
         * @param {Object} options Tab configuration.
         */
        initScopedTabs: function(options) {
            const self = this;
            const settings = Object.assign({
                storageKey: '',
                queryParam: 'tab',
                extraUrlParams: {}
            }, options || {});

            if (!settings.storageKey) {
                return;
            }

            $('.guard-dog-tabbed-interface').each(function() {
                const $container = $(this);
                const $tabNav = $container.children('.guard-dog-tab-nav').add($container.children('nav'));
                const $tabLinks = $tabNav.find('.guard-dog-tab-link');
                const $tabContent = $container.children('.guard-dog-tab-content');
                const $tabPanels = $tabContent.children('.guard-dog-tab-panel');
                const containerKey = $tabLinks.first().data('storage-key') || '';

                if (containerKey !== settings.storageKey) {
                    return;
                }

                // Prevent duplicate bindings when a page script is enqueued more than once.
                if ($container.data('guardDogTabsInitialized')) {
                    self.restoreScopedTabState($tabLinks, $tabPanels, settings);
                    return;
                }

                $container.data('guardDogTabsInitialized', true);

                $tabLinks.on('click', function(e) {
                    e.preventDefault();

                    const targetTab = $(this).data('tab');
                    $tabLinks.removeClass('active');
                    $(this).addClass('active');

                    $tabPanels.removeClass('active');
                    $tabPanels.filter('#' + targetTab).addClass('active');

                    sessionStorage.setItem(settings.storageKey, targetTab);
                    self.updateScopedTabUrl(settings.queryParam, targetTab, settings.extraUrlParams);
                });

                self.restoreScopedTabState($tabLinks, $tabPanels, settings);
            });
        },

        /**
         * Restore the previously selected tab for a scoped tabbed interface.
         *
         * @param {jQuery} $tabLinks Tab links in the current container.
         * @param {jQuery} $tabPanels Tab panels in the current container.
         * @param {Object} settings Tab configuration.
         */
        restoreScopedTabState: function($tabLinks, $tabPanels, settings) {
            let activeTab = sessionStorage.getItem(settings.storageKey);
            const urlParams = new URLSearchParams(window.location.search);
            const tabParam = urlParams.get(settings.queryParam) || urlParams.get('tab');

            if (tabParam && $tabPanels.filter('#' + tabParam).length > 0) {
                activeTab = tabParam;
            } else if (!activeTab && window.location.hash) {
                activeTab = window.location.hash.substring(1);
            }

            if (activeTab && $tabPanels.filter('#' + activeTab).length > 0) {
                $tabLinks.removeClass('active');
                $tabPanels.removeClass('active');

                $tabLinks.filter('[data-tab="' + activeTab + '"]').addClass('active');
                $tabPanels.filter('#' + activeTab).addClass('active');
                sessionStorage.setItem(settings.storageKey, activeTab);
            } else if ($tabLinks.filter('.active').length === 0) {
                $tabLinks.first().addClass('active');
                $tabPanels.first().addClass('active');
            }
        },

        /**
         * Keep the selected tab in the current URL for reloads and form posts.
         *
         * @param {string} queryParam Query parameter name for the active tab.
         * @param {string} activeTab Active tab id.
         * @param {Object|Function} extraUrlParams Additional params to persist.
         */
        updateScopedTabUrl: function(queryParam, activeTab, extraUrlParams) {
            if (!window.history || !window.history.replaceState) {
                return;
            }

            const url = new URL(window.location.href);
            const extraParams = (typeof extraUrlParams === 'function')
                ? extraUrlParams(activeTab)
                : (extraUrlParams || {});

            url.searchParams.set(queryParam, activeTab);

            Object.entries(extraParams).forEach(function([key, value]) {
                if (value === null || value === undefined || value === '') {
                    url.searchParams.delete(key);
                    return;
                }

                url.searchParams.set(key, value);
            });

            url.searchParams.delete('tab');
            url.searchParams.delete('_wpnonce');

            window.history.replaceState({}, '', url.toString());
        },

        /**
         * Bind event handlers
         */
        bindEvents: function() {
            // Settings form submissions
            if (typeof guard_dog_admin === 'undefined') {
                $('.guard-dog-settings-form').on('submit', this.handleFormSubmission);
            }
        },

        /**
         * Initialize tooltips for help icons
         */
        initTooltips: function() {
            $('.guard-dog-help-tooltip').each(function() {
                $(this).attr('title', $(this).data('tooltip'));
            });
        },

        /**
         * Initialize form validation
         */
        initFormValidation: function() {
            // Email validation
            $('input[type="email"]').on('blur', function() {
                const email = $(this).val();
                const isValid = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
                
                if (email && !isValid) {
                    $(this).addClass('error');
                    $(this).next('.error-message').remove();
                    $(this).after('<span class="error-message">Please enter a valid email address</span>');
                } else {
                    $(this).removeClass('error');
                    $(this).next('.error-message').remove();
                }
            });

            // URL validation
            $('input[type="url"]').on('blur', function() {
                const url = $(this).val();
                const isValid = /^https?:\/\/.+/.test(url);
                
                if (url && !isValid) {
                    $(this).addClass('error');
                    $(this).next('.error-message').remove();
                    $(this).after('<span class="error-message">Please enter a valid URL starting with http:// or https://</span>');
                } else {
                    $(this).removeClass('error');
                    $(this).next('.error-message').remove();
                }
            });
        },

        /**
         * Handle form submissions
         */
        handleFormSubmission: function(e) {
            e.preventDefault();
            
            const $form = $(this);
            const $submitButton = $form.find('input[type="submit"]');
            const originalText = $submitButton.val();
            
            // Show loading state
            $submitButton.val(guard_dog_admin.strings.saving);
            $submitButton.prop('disabled', true);
            $form.addClass('guard-dog-loading');
            
            // Submit form via AJAX
            $.ajax({
                url: $form.attr('action') || ajaxurl,
                type: 'POST',
                data: $form.serialize(),
                success: function(response) {
                    // Form submitted successfully
                    console.log('Settings saved successfully');
                },
                error: function() {
                    console.error('Error saving settings');
                },
                complete: function() {
                    // Restore button state
                    $submitButton.val(originalText);
                    $submitButton.prop('disabled', false);
                    $form.removeClass('guard-dog-loading');
                }
            });
        },


    };

    /**
     * Initialize when document is ready
     */
    $(document).ready(function() {
        GuardDogAdmin.init();
    });

})(jQuery); 
