(function (jQuery, window, document, undefined) {
    'use strict';

    jQuery(function ($) {
        // ===== CACHE DOM ELEMENTS =====
        // Caching jQuery selectors improves performance by avoiding repeated DOM queries

        var $body = $('body');
        var $pageNav = $('.page-nav');
        var $navMenu = $('[data-nav-menu]');         // Main navigation container
        var $navToggle = $('[data-nav-toggle]');     // Navigation toggle button (hamburger)
        var $dropdownToggles = $(
            '[data-dropdown-toggle], .page-nav-item--has-dropdown > .dropdown-toggle[data-toggle="dropdown"]'
        ); // Dropdown toggle links (new + composer-rendered legacy attribute)
        var $compatDropdownToggles = $('[data-compat-dropdown-toggle]'); // Legacy dropdown support

        // ===== HELPER FUNCTIONS =====

        /**
         * Close main navigation menu
         * Removes the 'is-open' class and sets ARIA attribute for accessibility
         */
        function closeNavMenu() {
            $navMenu.removeClass('is-open');
            $navToggle.attr('aria-expanded', 'false');
        }

        /**
         * Close all open navigation dropdowns
         * Used when opening a new dropdown or closing nav menu
         * Sets ARIA attribute for screen readers
         */
        function closeNavDropdowns() {
            $('.page-nav-item--has-dropdown').removeClass('open');
            $dropdownToggles.attr('aria-expanded', 'false');
        }

        /**
         * Restore the responsive navigation state when moving to desktop width.
         */
        function resetResponsiveNavigation() {
            if (window.innerWidth < 1024) {
                return;
            }

            closeNavMenu();
            closeNavDropdowns();
            $pageNav.removeClass('in');
            $('.page-nav-toggle').removeClass('active');
            $body.css({overflow: 'visible', position: 'static'});
        }

        // ===== PRIMARY NAVIGATION TOGGLE =====
        // Handle hamburger menu toggle for mobile/responsive navigation
        $navToggle.on('click', function () {
            var isOpen = $navMenu.hasClass('is-open');

            // Toggle the menu visibility class
            $navMenu.toggleClass('is-open', !isOpen);
            // Update ARIA state for screen readers
            $navToggle.attr('aria-expanded', String(!isOpen));

            // Close any open dropdowns when closing menu
            if (isOpen) {
                closeNavDropdowns();
            }
        });

        // ===== NAVIGATION DROPDOWN TOGGLES =====
        // Handle dropdown menus within navigation (main nav items with sub-items)
        $dropdownToggles.on('click', function (event) {
            event.preventDefault();

            var $toggle = $(event.currentTarget);
            var $item = $toggle.closest('.page-nav-item--has-dropdown');
            var isOpen = $item.hasClass('open');

            // Close all other dropdowns first
            closeNavDropdowns();

            // Open this dropdown if it wasn't already open
            if (!isOpen) {
                $item.addClass('open');
                $toggle.attr('aria-expanded', 'true');
            }
        });

        // ===== COMPATIBILITY DROPDOWN TOGGLES =====
        // Legacy dropdown support for backward compatibility with older markup patterns
        $compatDropdownToggles.on('click', function (event) {
            event.preventDefault();

            var $toggle = $(event.currentTarget);
            var $dropdown = $toggle.closest('[data-compat-dropdown]');
            var isOpen = $dropdown.hasClass('open');

            // Close all compatibility dropdowns
            $('[data-compat-dropdown]').removeClass('open');
            $('[data-compat-dropdown-toggle]').attr('aria-expanded', 'false');

            // Open this dropdown if it wasn't already open
            if (!isOpen) {
                $dropdown.addClass('open');
                $toggle.attr('aria-expanded', 'true');
            }
        });

        // ===== CLOSE DROPDOWNS/MENUS ON OUTSIDE CLICK =====
        // Centralized click handler to close any open menus when clicking elsewhere
        // Improves UX by preventing menus from staying open unexpectedly
        $(document).on('click', function (event) {
            // Close main navigation menu if click is outside nav area
            if (!$(event.target).closest('[data-nav-menu], [data-nav-toggle]').length) {
                closeNavMenu();
            }

            // Close navigation dropdowns if click is outside dropdown items
            if (!$(event.target).closest('.page-nav-item--has-dropdown').length) {
                closeNavDropdowns();
            }

            // Close compatibility dropdowns if click is outside compat dropdown area
            if (!$(event.target).closest('[data-compat-dropdown]').length) {
                $('[data-compat-dropdown]').removeClass('open');
                $('[data-compat-dropdown-toggle]').attr('aria-expanded', 'false');
            }
        });

        // ===== ALERT DISMISSAL =====
        // Support legacy flash alerts and Bootstrap-style close controls.
        $(document).on('click', '[data-dismiss="alert"], [data-alert-dismiss], .alert .close, .flash-message .close', function (event) {
            event.preventDefault();

            var $button = $(event.currentTarget);
            var $alert = $button.closest('.alert, .flash-message');

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

            $alert.fadeOut(150, function () {
                $(this).remove();
            });
        });

        // ===== RESPONSIVE NAVIGATION RESET =====
        // Reset navigation when window is resized to desktop width
        // Ensures menus don't stay open when transitioning from mobile to desktop
        $(window).on('resize', function () {
            resetResponsiveNavigation();
        });

        // ===== SELECT2 PLUGIN INITIALIZATION =====
        // Initialize Select2 dropdowns for enhanced form select elements
        // Select2 provides better styling, searching, and usability for selects

        if ($.fn.select2) {
            // Filter selects to only initialize those that aren't already initialized
            // Excludes: already-initialized selects (.select2-hidden-accessible)
            //          and native selects marked with [data-native-select] attribute
            $('select').filter(function () {
                return !$(this).hasClass('select2-hidden-accessible') && !$(this).is('[data-native-select]');
            }).each(function () {
                var $select = $(this);

                $select.select2({
                    width: '100%'  // Make Select2 dropdowns full width of container
                }).on('select2:select select2:unselect', function () {
                    // Auto-focus the select after selection/deselection for keyboard users
                    $(this).focus();
                });
            });
        }

        // ===== SUBMIT BUTTON AUTO-DISABLE PREVENTION =====
        // Prevent accidental double-submission by temporarily disabling submit buttons
        // Improves UX by preventing duplicate form submissions and their consequences
        // preventing double-click on submit buttons
        $(document).on('click', 'button[type="submit"]', function (event) {
            // Allow submission if button has the submit-autodisable-exclude class
            if ($(this).hasClass('submit-autodisable-exclude')) {
                return;
            }

            var $button = $(event.currentTarget);
            var buttonText = $button.text();

            // Immediately disable button to prevent double-click
            $button.addClass('disabled')
                .attr('disabled', true)
                .text('Processing...');

            // Submit the form after a short delay to allow UI updates to render
            // (150ms is enough for CSS transitions to display the disabled state)
            setTimeout(function () {
                $button.closest('form').trigger('submit');
            }, 150);

            // Re-enable button after 5 seconds as a safeguard
            // (in case form submission fails or redirects take time)
            setTimeout(function () {
                $button.removeClass('disabled')
                    .removeAttr('disabled')
                    .text(buttonText);
            }, 5000);
        });
    });
})(jQuery, window, document);
