// Clever Sidebar UX Logic
window.sidebarUX = {
    dotNetRef: null,
    resizeObserver: null,
    titleObserver: null,
    
    // Initialize sidebar UX behavior
    initialize: function(dotNetRef) {
        this.dotNetRef = dotNetRef;
        this.setupResizeListener();
        this.setupClickOutsideListener();
        this.setupSidebarStateObserver();
        this.setupTitleObserver();
        return this.isMobile();
    },
    
    // Check if current screen size is mobile
    isMobile: function() {
        return window.matchMedia('(max-width: 768px)').matches;
    },
    
    // Helper function for checking mobile state (for NavMenuEnhanced)
    checkMobileState: function() {
        return window.matchMedia('(max-width: 768px)').matches;
    },
    
    // Setup responsive behavior
    setupResizeListener: function() {
        const mediaQuery = window.matchMedia('(max-width: 768px)');
        
        const handleResize = (e) => {
            if (this.dotNetRef) {
                this.dotNetRef.invokeMethodAsync('OnScreenSizeChanged', e.matches);
            }
        };
        
        // Listen for screen size changes
        mediaQuery.addListener(handleResize);
        
        // Store reference for cleanup
        this.mediaQueryListener = { mediaQuery, handleResize };
    },
    
    // Setup click outside listener for all screen sizes
    setupClickOutsideListener: function() {
        document.addEventListener('click', (event) => {
            // Check if sidebar is currently open
            const sidebarElement = document.querySelector('.e-sidebar');
            if (!sidebarElement || !sidebarElement.classList.contains('e-open')) {
                return; // Sidebar is not open, no need to check
            }

            const isPinnedDesktopSidebar = sidebarElement.classList.contains('desktop-nav-pinned') && !this.isMobile();
            if (isPinnedDesktopSidebar) {
                return;
            }
            
            const sidebar = document.querySelector('.e-sidebar');
            const sidebarContent = document.querySelector('.e-sidebar-overlay');
            const sidebarContainer = document.querySelector('.e-sidebar-container');
            const eventTarget = event.target;
            
            // Check if click is on Syncfusion backdrop (when ShowBackdrop is enabled)
            const isBackdropClick = eventTarget.classList && eventTarget.classList.contains('e-sidebar-overlay');
            
            // Check if click is inside any sidebar-related element
            const isInsideSidebar = sidebar && sidebar.contains(eventTarget);
            const isInsideSidebarContent = sidebarContent && sidebarContent.contains(eventTarget);
            const isInsideSidebarContainer = sidebarContainer && sidebarContainer.contains(eventTarget);

            // IMPORTANT: detect opener/closer from event ancestry, not querySelector,
            // because Blazor rerender can remove opener before this document handler runs.
            const isMenuButton = eventTarget.closest && (
                eventTarget.closest('.floating-menu-btn') ||
                eventTarget.closest('.nav-menu-open-trigger')
            );
            const isCloseButton = eventTarget.closest && eventTarget.closest('.x-sidebar-close-btn');
            
            // Check if click is on Syncfusion dropdown elements (they render outside sidebar)
            const isSyncfusionDropdown = eventTarget.closest('.e-ddl-popup') || 
                                       eventTarget.closest('.e-popup') || 
                                       eventTarget.closest('.e-calendar') ||
                                       eventTarget.closest('.e-datepicker-popup') ||
                                       eventTarget.closest('.e-dropdown-popup') ||
                                       eventTarget.classList.contains('e-list-item') ||
                                       eventTarget.classList.contains('e-ddl-popup');
            
            // Close sidebar if clicking on backdrop or outside sidebar elements, but NOT on Syncfusion dropdowns
            if (isBackdropClick || (!isInsideSidebar && !isInsideSidebarContent && !isInsideSidebarContainer && 
                !isMenuButton && !isCloseButton && !isSyncfusionDropdown)) {
                if (this.dotNetRef) {
                    this.dotNetRef.invokeMethodAsync('CloseSidebarFromJS');
                }
            }
        });
    },
    
    // Setup observer to watch for sidebar state changes
    setupSidebarStateObserver: function() {
        // Wait for sidebar element to be available
        const checkForSidebar = () => {
            const sidebarElement = document.querySelector('.e-sidebar');
            if (sidebarElement) {
                // Create observer to watch for class changes on sidebar
                this.sidebarObserver = new MutationObserver((mutations) => {
                    mutations.forEach((mutation) => {
                        if (mutation.type === 'attributes' && mutation.attributeName === 'class') {
                            // Sidebar state changed, notify with a small delay to ensure DOM is updated
                            setTimeout(() => {
                                this.notifySidebarStateChanged();
                            }, 100);
                        }
                    });
                });
                
                // Start observing class changes on the sidebar element
                this.sidebarObserver.observe(sidebarElement, {
                    attributes: true,
                    attributeFilter: ['class']
                });
            } else {
                // Sidebar not found yet, try again after a short delay
                setTimeout(checkForSidebar, 100);
            }
        };
        
        checkForSidebar();
    },

    // Notify about sidebar state changes
    notifySidebarStateChanged: function() {
        if (this.dotNetRef) {
            this.dotNetRef.invokeMethodAsync('OnSidebarStateChangedFromJS');
        }
    },

    getDocumentTitle: function() {
        return (document.title || '').trim();
    },

    setupTitleObserver: function() {
        const notifyTitleChanged = () => {
            if (this.dotNetRef) {
                this.dotNetRef.invokeMethodAsync('OnDocumentTitleChanged', this.getDocumentTitle());
            }
        };

        const titleElement = document.querySelector('title');
        if (!titleElement) {
            notifyTitleChanged();
            return;
        }

        this.titleObserver = new MutationObserver(() => {
            notifyTitleChanged();
        });

        this.titleObserver.observe(titleElement, {
            childList: true,
            characterData: true,
            subtree: true
        });

        notifyTitleChanged();
    },
    
    // Cleanup function
    dispose: function() {
        if (this.mediaQueryListener) {
            this.mediaQueryListener.mediaQuery.removeListener(this.mediaQueryListener.handleResize);
        }
        if (this.sidebarObserver) {
            this.sidebarObserver.disconnect();
            this.sidebarObserver = null;
        }
        if (this.titleObserver) {
            this.titleObserver.disconnect();
            this.titleObserver = null;
        }
        this.dotNetRef = null;
    }
};

// Legacy support for existing calls
window.setupSidebarResizeListener = function(dotNetRef) {
    return window.sidebarUX.initialize(dotNetRef);
};

// Global function to trigger sidebar state change notification
window.triggerSidebarStateChange = function() {
    if (window.sidebarUX && window.sidebarUX.dotNetRef) {
        window.sidebarUX.notifySidebarStateChanged();
    }
};
