/**
 * Guard Dog Users & Sessions Page JavaScript
 *
 * Handles tab navigation for the consolidated Users & Sessions page.
 * This script manages ONLY the outer tab interface (Email Verification,
 * Password Policy, Temporary Access, Sessions). Nested tab interfaces
 * within each section are handled by their respective page scripts.
 *
 * @package GuardDog
 * @since 2.0.0
 */

(function($) {
    'use strict';

    $(document).ready(function() {
        GuardDogUsersSessions.init();
    });

    const GuardDogUsersSessions = {

        /**
         * Storage key for outer tab persistence
         */
        storageKey: 'guard_dog_users_sessions_active_tab',

        /**
         * Query param used to persist the outer tab in the URL.
         */
        queryParam: 'users_sessions_tab',

        /**
         * Initialize the page functionality
         */
        init: function() {
            this.initTabNavigation();
        },

        /**
         * Initialize tab navigation scoped to the outer container only
         */
        initTabNavigation: function() {
            const self = this;

            $('.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') || '';

                // Only handle the outer Users & Sessions tabs
                if (containerKey !== self.storageKey) {
                    return;
                }

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

                    const targetTab = $(this).data('tab');

                    // Update active tab link within this container only
                    $tabLinks.removeClass('active');
                    $(this).addClass('active');

                    // Show target panel within this container only
                    $tabPanels.removeClass('active');
                    $tabPanels.filter('#' + targetTab).addClass('active');

                    // Persist active tab
                    sessionStorage.setItem(self.storageKey, targetTab);
                    self.updateUrl(targetTab);
                });

                // Restore saved tab
                self.restoreActiveTab($tabLinks, $tabPanels);
            });
        },

        /**
         * Restore the previously active tab from storage or URL
         */
        restoreActiveTab: function($tabLinks, $tabPanels) {
            let activeTab = sessionStorage.getItem(this.storageKey);

            // Check URL hash as fallback
            if (!activeTab && window.location.hash) {
                activeTab = window.location.hash.substring(1);
            }

            // Check URL parameter (server-side tab selection takes priority)
            const urlParams = new URLSearchParams(window.location.search);
            const tabParam = urlParams.get(this.queryParam) || urlParams.get('tab');
            if (tabParam && $tabPanels.filter('#' + tabParam).length > 0) {
                activeTab = tabParam;
            }

            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');
            } else {
                // Ensure first tab is active if nothing else is
                if ($tabLinks.filter('.active').length === 0) {
                    $tabLinks.first().addClass('active');
                    $tabPanels.first().addClass('active');
                }
            }
        },

        /**
         * Keep the selected outer tab in the current URL so postbacks and reloads
         * stay on the same feature after the page reorganization.
         */
        updateUrl: function(activeTab) {
            if (!window.history || !window.history.replaceState) {
                return;
            }

            const url = new URL(window.location.href);
            url.searchParams.set(this.queryParam, activeTab);
            url.searchParams.delete('tab');
            url.searchParams.delete('_wpnonce');

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

    };

})(jQuery);
