/**
 * Guard Dog Authentication Page JavaScript
 *
 * Keeps the consolidated Authentication page tabs in sync with the URL so
 * settings saves redirect back to the active section.
 *
 * @package GuardDog
 * @since 2.0.0
 */

(function($) {
    'use strict';

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

    const GuardDogAuthentication = {

        /**
         * Storage key for the Authentication tabs.
         */
        storageKey: 'guard_dog_authentication_active_tab',

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

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

        /**
         * Scope handling to the consolidated Authentication tab interface 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') || '';

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

                $tabLinks.on('click', function() {
                    const targetTab = $(this).data('tab');
                    sessionStorage.setItem(self.storageKey, targetTab);
                    self.updateUrl(targetTab);
                });

                self.restoreActiveTab($tabPanels);
            });
        },

        /**
         * Honor the URL query param over stored state after reload/save.
         */
        restoreActiveTab: function($tabPanels) {
            let activeTab = sessionStorage.getItem(this.storageKey);
            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) {
                sessionStorage.setItem(this.storageKey, activeTab);
            }
        },

        /**
         * Keep the current Authentication tab in the URL for options.php redirects.
         */
        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);
