{{-- localization --}}
<script type="text/javascript" src="{{ route('eventmie.eventmie_lang') }}"></script>

<!-- Scripts for dark & light mode -->
@vite(['resources/js/theme.js'])


{{-- VueJs Global Constants --}}
<script type="text/javascript">
    const my_lang = {!! json_encode(session('my_lang', \Config::get('app.locale'))) !!};
    const timezone_conversion = {!! json_encode(!empty(setting('regional.timezone_conversion')) ? 1 : 0) !!};
    const timezone_default = {!! json_encode(setting('regional.timezone_default')) !!};
    const defaultTheme = {!! json_encode(setting('site.default_theme', 'auto')) !!};

    const date_format = {
        vue_date_format: '{!! format_js_date() !!}',
        vue_time_format: '{!! format_js_time() !!}'
    };

    // set local timezone 
    var local_timezone = {!! json_encode(route('eventmie.local_timezone')) !!};
    function setLocalTimezone() {
        // Making our request
        fetch(local_timezone, {
                method: 'POST',
                headers: {
                    'X-CSRF-TOKEN': document.head.querySelector('meta[name="csrf-token"]').content,
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    local_timezone: Intl.DateTimeFormat().resolvedOptions().timeZone
                })
            })
            .then(Result => Result.json())
            .then(string => {
                console.log('lang', string);
            })
            .catch(errorMsg => {
                console.log(errorMsg);
            });
    }
    setLocalTimezone();
</script>


{{-- Javascript Global Listener --}}
@if(!in_array(Route::currentRouteName(), ['eventmie.scan_ticket_camera', 'eventmie.scan_ticket_laser']))
<script type="text/javascript">
    /**
     * Header menu onscroll 
     */
    var lastScrollTop = 0;

    function handleScroll() {
        let el = document.getElementById('navbar_vue');
        let st = window.pageYOffset || document.documentElement.scrollTop;

        lastScrollTop = st <= 0 ? 0 : st; // For Mobile or negative scrolling
        if (window.scrollY > 1) {
            el.classList.add('shadow');
            el.classList.add('menu-fixed');
        } else {
            el.classList.remove('shadow');
            el.classList.remove('menu-fixed');

            if (el.classList.contains('is-active')) {
                el.classList.add('is-mobile');
            }
        }
    };

    function scrollListener(obj, type, fn) {
        if (obj.attachEvent) {
            obj['e' + type + fn] = fn;
            obj[type + fn] = function() {
                obj['e' + type + fn](window.event);
            };
            obj.attachEvent('on' + type, obj[type + fn]);
        } else {
            obj.addEventListener(type, fn, false);
        }
    }

    scrollListener(window, 'scroll', function(e) {
        handleScroll();
    });

    // dashboard  Toggle
    function clickToggle() {
        let dbWrapperTwo = document.getElementById("db-wrapper-two");
        let dbWrapper = document.getElementById("db-wrapper");
        sideToggle(dbWrapperTwo, dbWrapper);
    }

    //dashboard Toggle
    sideToggle = (dbWrapperTwo, dbWrapper) => {
        if (dbWrapper.classList == '' || dbWrapperTwo == '') {
            dbWrapperTwo.classList.add('toggled');
            dbWrapper.classList.add('toggled');
        } else {
            dbWrapperTwo.classList.remove('toggled');
            dbWrapper.classList.remove('toggled');
        }
    }

    // Copy to clipboard
    function copyToClipboard() {
        var dummy = document.createElement('input'),
            text = window.location.href;

        document.body.appendChild(dummy);
        dummy.value = text;
        dummy.select();
        document.execCommand('copy');
        document.body.removeChild(dummy);

        alert(trans('em.url_copied'));
    }

    // Bootstrap Navbar collapse using JS Script
    document.addEventListener("DOMContentLoaded", function() {
        const navbarToggler = document.querySelector(".navbar-toggler");
        const navbarCollapse = document.querySelector(".navbar-collapse");
        console.log(navbarToggler, navbarCollapse, 'navbar-collapse');
        if (navbarToggler || navbarCollapse) {
            navbarToggler.addEventListener("click", function() {
                // Toggle the visibility of the dropdown menu
                if (navbarCollapse.style.display === "none" || navbarCollapse.style.display === "") {
                    navbarCollapse.style.display = "block";
                    navbarCollapse.classList.add('show');
                } else {
                    navbarCollapse.style.display = "none";
                    navbarCollapse.classList.remove('show');
                }
            });

            // Close the dropdown if the user clicks outside of it
            document.addEventListener("click", function(event) {
                if (!navbarToggler.contains(event.target) && !navbarCollapse.contains(event.target)) {
                    navbarCollapse.style.display = "none";
                    navbarCollapse.classList.add('show');
                }
            });
        }
    });

    // Bootstrap Dropdown using JS Script
    document.addEventListener("DOMContentLoaded", function() {
        const dropdownButtons = document.querySelectorAll(".dropdown-toggle");
        const dropdownMenus = document.querySelectorAll(".dropdown-menu");

        if (dropdownButtons || dropdownMenus) {
            // Add click event listeners to each dropdown button
            dropdownButtons.forEach((button, index) => {
                button.addEventListener("click", function() {
                    // Toggle the visibility of the corresponding dropdown menu
                    if (dropdownMenus[index].style.display === "none" || dropdownMenus[index]
                        .style
                        .display === "") {
                        dropdownMenus[index].style.display = "block";
                        dropdownMenus[index].style.border = "1px solid #fff";
                        dropdownMenus[index].classList.add('show', 'shadow');
                    } else {
                        dropdownMenus[index].style.display = "none";
                        dropdownMenus[index].classList.remove('show', 'shadow');
                    }
                });
            });

            // Close all dropdowns if the user clicks outside of any dropdown
            document.addEventListener("click", function(event) {
                dropdownButtons.forEach((button, index) => {
                    if (!button.contains(event.target) && !dropdownMenus[index].contains(event
                            .target)) {
                        dropdownMenus[index].style.display = "none";
                        dropdownMenus[index].style.border = "1px solid #fff";
                        dropdownMenus[index].classList.remove('show', 'shadow');
                    }
                });
            });
        }
    });

    // Simple Global Custom Dropdown Handler - Click Outside Only
    document.addEventListener("DOMContentLoaded", function() {
        // Add simple CSS to prevent hover after clicking outside
        const style = document.createElement('style');
        style.textContent = `
            /* Nuclear option: completely override hover when no-hover class is present */
            .custom-dropdown.no-hover .dropdownmenu,
            .custom-dropdown.no-hover:hover .dropdownmenu,
            .custom-dropdown.no-hover:focus-within .dropdownmenu {
                display: none !important;
                visibility: hidden !important;
                opacity: 0 !important;
                pointer-events: none !important;
                max-height: 0 !important;
                max-width: 0 !important;
                overflow: hidden !important;
                position: absolute !important;
                left: -9999px !important;
                top: -9999px !important;
            }
            
            /* Make sure it overrides the existing CSS rule with maximum specificity */
            html body .custom-dropdown.no-hover .dropdownmenu,
            html body .custom-dropdown.no-hover:hover .dropdownmenu,
            html body .custom-dropdown.no-hover:focus-within .dropdownmenu {
                display: none !important;
                visibility: hidden !important;
                opacity: 0 !important;
                pointer-events: none !important;
                max-height: 0 !important;
                max-width: 0 !important;
                overflow: hidden !important;
                position: absolute !important;
                left: -9999px !important;
                top: -9999px !important;
            }
             
             /* Force menu visible when JS toggles it open (Safari-safe) */
             .custom-dropdown.js-open .dropdownmenu,
             html body .custom-dropdown.js-open .dropdownmenu {
                 display: block !important;
                 visibility: visible !important;
                 opacity: 1 !important;
                 pointer-events: auto !important;
             }
        `;
        document.head.appendChild(style);
        
        // Only handle clicking outside to close dropdowns
        document.addEventListener('click', function(e) {
            // If clicking outside any dropdown, close all open dropdowns and disable hover on ALL dropdowns
            if (!e.target.closest('.custom-dropdown')) {
                // First, close any open dropdowns
                const openDropdowns = document.querySelectorAll('.custom-dropdown .dropdownmenu[style*="block"], .custom-dropdown .dropdownmenu.show');
                
                openDropdowns.forEach(function(dropdown) {
                    const customDropdown = dropdown.closest('.custom-dropdown');
                    if (customDropdown) {
                        // Close the dropdown
                        dropdown.style.display = 'none';
                        dropdown.classList.remove('show');
                        
                        // Update Vue component if exists
                        try {
                            const vueComponent = customDropdown.__vue__;
                            if (vueComponent && typeof vueComponent.isOpen !== 'undefined') {
                                vueComponent.isOpen = false;
                            }
                        } catch (error) {
                            console.debug('Vue component not found for dropdown:', customDropdown);
                        }
                    }
                });
                
                // Then, disable hover on ALL custom dropdowns
                const allDropdowns = document.querySelectorAll('.custom-dropdown');
                allDropdowns.forEach(function(dropdown) {
                    dropdown.classList.add('no-hover');
                     dropdown.classList.remove('js-open');
                    console.log('Added no-hover class to:', dropdown);
                });
            }
        });
        
        // Handle dropdown button clicks with state management
        document.addEventListener('click', function(e) {
            const dropdownButton = e.target.closest('.custom-dropdown');
            if (dropdownButton) {
                const dropdownMenu = dropdownButton.querySelector('.dropdownmenu');
                
                // Only proceed if dropdownMenu exists
                if (dropdownMenu && dropdownButton.classList.contains('no-hover')) {
                    // This dropdown was previously closed by clicking outside
                    console.log('Processing dropdown that was closed by outside click');
                    
                    // Remove the no-hover class
                    dropdownButton.classList.remove('no-hover');
                    
                    // Check if dropdown is currently closed
                    const isCurrentlyClosed = dropdownMenu.style.display === 'none' || 
                                            dropdownMenu.style.display === '' ||
                                            !dropdownMenu.classList.contains('show');
                    
                    if (isCurrentlyClosed) {
                        // Open the dropdown
                        dropdownMenu.style.display = 'block';
                        dropdownMenu.classList.add('show');
                         dropdownButton.classList.add('js-open');
                        console.log('Opened dropdown:', dropdownButton);
                        
                        // Update Vue component if exists
                        try {
                            const vueComponent = dropdownButton.__vue__;
                            if (vueComponent && typeof vueComponent.isOpen !== 'undefined') {
                                vueComponent.isOpen = true;
                            }
                        } catch (error) {
                            console.debug('Vue component not found for dropdown:', dropdownButton);
                        }
                        
                        // Prevent any other handlers from running
                        e.stopImmediatePropagation();
                        e.preventDefault();
                    }
                }
            }
        });
        
        // Test function to check if CSS is working
        window.testDropdownHover = function() {
            const dropdowns = document.querySelectorAll('.custom-dropdown');
            dropdowns.forEach(function(dropdown) {
                console.log('Dropdown:', dropdown);
                console.log('Classes:', dropdown.classList.toString());
                console.log('Has no-hover:', dropdown.classList.contains('no-hover'));
                
                const menu = dropdown.querySelector('.dropdownmenu');
                if (menu) {
                    console.log('Menu display:', menu.style.display);
                    console.log('Menu computed display:', window.getComputedStyle(menu).display);
                }
            });
        };
    });
    

</script>
@endif