/**
 * Guard Dog Sessions Page JavaScript
 *
 * Handles tab navigation and session management functionality.
 *
 * @package GuardDog
 * @since 1.9.1
 */

(function($) {
    'use strict';

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

    const GuardDogSessions = {

        /**
         * Storage key for tab persistence
         */
        storageKey: 'guard_dog_sessions_active_tab',

        /**
         * Query param used to persist the inner Sessions tab.
         */
        queryParam: 'sessions_tab',

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

        /**
         * Initialize tab navigation
         */
        initTabNavigation: function() {
            const self = this;

            // Scope tab switching to each tabbed interface to prevent
            // clobbering nested tab panels on consolidated pages.
            $('.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') || self.storageKey;

                // Only handle containers matching our storage key
                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');

                    // Store active tab in sessionStorage for persistence
                    sessionStorage.setItem(containerKey, targetTab);
                    self.updateUrl(targetTab);
                });

                // Initialize active tab for this container
                self.initializeActiveTabForContainer($tabLinks, $tabPanels, containerKey);
            });
        },

        /**
         * Initialize the active tab for a specific scoped container
         */
        initializeActiveTabForContainer: function($tabLinks, $tabPanels, containerKey) {
            let activeTab = sessionStorage.getItem(containerKey);

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

            // Check URL parameter (for server-side tab selection)
            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) {
                // Activate the stored/selected tab within this container
                $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 Sessions tab on the current URL so filters, reloads,
         * and direct navigation stay on the nested Sessions feature.
         */
        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.set('users_sessions_tab', 'sessions');
            url.searchParams.delete('tab');
            url.searchParams.delete('_wpnonce');

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

        /**
         * Initialize session termination confirmations
         */
        initSessionTermination: function() {
            if (typeof guardDogSessions !== 'undefined') {
                return;
            }

            // Get localized strings if available
            const strings = (typeof guard_dog_sessions !== 'undefined' && guard_dog_sessions.strings)
                ? guard_dog_sessions.strings
                : {};

            // Confirmation for single session termination
            $('.guard-dog-terminate-session').on('click', function(e) {
                const confirmMessage = strings.confirmTerminate || 'Are you sure you want to terminate this session?';
                if (!confirm(confirmMessage)) {
                    e.preventDefault();
                }
            });

            // Confirmation for terminating all user sessions
            $('.guard-dog-terminate-all-sessions').on('click', function(e) {
                const confirmMessage = strings.confirmTerminateAll || 'Are you sure you want to terminate all sessions for this user?';
                if (!confirm(confirmMessage)) {
                    e.preventDefault();
                }
            });
        }

    };

})(jQuery);
