/**
 * Guard Dog User Registration Page Scripts
 *
 * Handles tab navigation and password expiration email trigger functionality.
 *
 * @package GuardDog
 * @since 1.9.0
 */

(function($) {
    'use strict';

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

    const GuardDogUserRegistration = {

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

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

        /**
         * 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);
                });

                // 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('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');
                }
            }
        },

        /**
         * Initialize manual expiration check trigger
         */
        initExpirationTrigger: function() {
            const $btn = $('#guard-dog-trigger-check');
            const $results = $('#guard-dog-trigger-results');

            if (!$btn.length) {
                return;
            }

            $btn.on('click', function() {
                // Check if localized data is available
                if (typeof guardDogUserRegistration === 'undefined') {
                    return;
                }

                const strings = guardDogUserRegistration.strings;

                if (!confirm(strings.confirmSend)) {
                    return;
                }

                $btn.prop('disabled', true).text(strings.sending);
                $results.hide().removeClass('success error');

                $.ajax({
                    url: guardDogUserRegistration.ajaxUrl,
                    type: 'POST',
                    data: {
                        action: 'guard_dog_trigger_expiration_check',
                        nonce: guardDogUserRegistration.nonce
                    },
                    success: function(response) {
                        if (response.success) {
                            const data = response.data;
                            $results
                                .addClass('success')
                                .html(
                                    '<span class="result-success">' + strings.complete + '</span> ' +
                                    strings.usersChecked + ' ' + data.users_checked + ', ' +
                                    strings.warningsSent + ' ' + data.warnings_sent + ', ' +
                                    strings.noticesSent + ' ' + data.notices_sent
                                )
                                .show();
                        } else {
                            const errorMessage = response.data && response.data.message
                                ? response.data.message
                                : strings.unknownError;
                            $results
                                .addClass('error')
                                .html('<span class="result-error">' + strings.error + '</span> ' + errorMessage)
                                .show();
                        }
                    },
                    error: function() {
                        $results
                            .addClass('error')
                            .html('<span class="result-error">' + strings.requestFailed + '</span>')
                            .show();
                    },
                    complete: function() {
                        $btn.prop('disabled', false).text(strings.buttonText);
                    }
                });
            });
        }

    };

})(jQuery);
