/**
 * Mobile Navigation Enhancement
 * 
 * This script improves the mobile navigation experience by:
 * - Ensuring proper navbar collapse behavior
 * - Adding smooth transitions
 * - Handling viewport changes
 * - Fixing z-index issues on mobile
 */

(function ($) {
    'use strict';

    $(document).ready(function () {

        // Initialize navbar fixes
        initializeNavbarFixes();

        // Handle window resize events
        $(window).on('resize', function () {
            handleViewportChange();
        });

        // Handle navbar toggle clicks
        $(document).on('click', '.navbar-toggle', function () {
            handleNavbarToggle();
        });

        // Close mobile menu when clicking outside
        $(document).on('click', function (event) {
            if (!$(event.target).closest('.navbar').length) {
                closeNavbarCollapse();
            }
        });

    });

    /**
 * Initialize navbar-specific fixes
 */
    function initializeNavbarFixes() {
        // Ensure proper body padding on load
        adjustBodyPadding();

        // Add mobile-friendly classes
        if (isMobileDevice()) {
            $('body').addClass('mobile-device');
            $('.navbar').addClass('mobile-navbar');
        }

        // Improve accessibility
        $('.navbar-toggle').attr('aria-label', 'Toggle navigation menu');

        // Ensure sidebar is properly positioned on page load
        setTimeout(function () {
            var $navbar = $('.navbar-fixed-top');
            if ($navbar.length > 0) {
                adjustSidebarPosition($navbar.outerHeight());
            }
        }, 100);
    }

    /**
     * Handle viewport changes (resize, orientation change)
     */
    function handleViewportChange() {
        // Debounce the resize event
        clearTimeout(window.navbarResizeTimeout);
        window.navbarResizeTimeout = setTimeout(function () {
            adjustBodyPadding();
            closeNavbarCollapse();
        }, 150);
    }

    /**
     * Handle navbar toggle behavior
     */
    function handleNavbarToggle() {
        var $collapse = $('.navbar-collapse');
        var isExpanded = $collapse.hasClass('in') || $collapse.hasClass('collapsing');

        // Update aria-expanded attribute
        $('.navbar-toggle').attr('aria-expanded', !isExpanded);

        // Add/remove body class to prevent scrolling when menu is open
        if (!isExpanded) {
            $('body').addClass('navbar-open');
        } else {
            $('body').removeClass('navbar-open');
        }
    }

    /**
     * Close navbar collapse menu
     */
    function closeNavbarCollapse() {
        var $collapse = $('.navbar-collapse');
        if ($collapse.hasClass('in')) {
            $collapse.collapse('hide');
            $('.navbar-toggle').attr('aria-expanded', 'false');
            $('body').removeClass('navbar-open');
        }
    }

    /**
 * Adjust body padding based on navbar height
 */
    function adjustBodyPadding() {
        var $navbar = $('.navbar-fixed-top');
        if ($navbar.length > 0) {
            var navbarHeight = $navbar.outerHeight();
            var additionalPadding = 10;

            // Adjust padding based on screen size
            if ($(window).width() <= 480) {
                additionalPadding = 15;
            } else if ($(window).width() <= 767) {
                additionalPadding = 12;
            }

            var totalPadding = navbarHeight + additionalPadding;

            // Apply the padding with a smooth transition
            $('body').css({
                'padding-top': totalPadding + 'px',
                'transition': 'padding-top 0.3s ease-in-out'
            });

            // Also adjust container if needed
            $('#container').css({
                'margin-top': '0',
                'padding-top': '10px'
            });

            // Adjust sidebar position to account for navbar
            adjustSidebarPosition(navbarHeight);
        }
    }

    /**
 * Adjust sidebar position based on navbar height
 */
    function adjustSidebarPosition(navbarHeight) {
        var $sidebar = $('#sidebar');
        if ($sidebar.length > 0) {
            var sidebarGap = 8; // Small gap between navbar and sidebar
            var sidebarTop = navbarHeight + sidebarGap;

            // For large screens (1400px+), remove gap for seamless connection
            if ($(window).width() >= 1400) {
                sidebarTop = navbarHeight;
                sidebarGap = 0;
            }

            // Apply sidebar positioning
            $sidebar.css({
                'top': sidebarTop + 'px',
                'height': 'calc(100vh - ' + sidebarTop + 'px)',
                'transition': 'top 0.3s ease-in-out, height 0.3s ease-in-out'
            });

            // Adjust sidebar channels if they exist
            var $sidebarChannels = $('#sidebar-channels');
            if ($sidebarChannels.length > 0) {
                $sidebarChannels.css({
                    'top': '80px', // Account for user section
                    'bottom': '60px' // Account for tabs
                });
            }
        }
    }

    /**
     * Check if the device is mobile
     */
    function isMobileDevice() {
        return (typeof window.orientation !== "undefined") ||
            (navigator.userAgent.indexOf('IEMobile') !== -1) ||
            /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
    }

    /**
     * Handle scroll behavior when mobile menu is open
     */
    $(document).on('shown.bs.collapse hidden.bs.collapse', '.navbar-collapse', function (e) {
        if ($(window).width() <= 767) {
            if (e.type === 'shown') {
                // Menu opened - prevent body scroll
                $('body').addClass('navbar-open');
            } else {
                // Menu closed - restore body scroll
                $('body').removeClass('navbar-open');
            }
        }
    });

})(jQuery);

// Additional CSS to prevent body scroll when mobile menu is open
var mobileMenuCSS = `
<style>
@media (max-width: 767px) {
    body.navbar-open {
        overflow: hidden;
        position: fixed;
        width: 100%;
    }
    
    .mobile-device .navbar-collapse.in {
        max-height: calc(100vh - 60px);
        overflow-y: auto;
        -webkit-overflow-scrolling: touch;
    }
    
    .mobile-navbar .navbar-nav > li > a:active,
    .mobile-navbar .navbar-nav > li > a:focus {
        background-color: rgba(255, 255, 255, 0.1);
    }
}
</style>
`;

// Inject the CSS
$('head').append(mobileMenuCSS); 