/**
 * Modern Sidebar JavaScript
 * Handles all interactive functionality
 */

class ModernSidebar {
    constructor() {
        this.sidebar = document.getElementById('modern-sidebar');
        this.sidebarToggleBtn = document.getElementById('sidebar-toggle-btn');
        this.themeToggleBtn = document.getElementById('theme-toggle-btn');
        this.userMenuBtn = document.getElementById('user-menu-btn');
        this.userMenuContainer = document.querySelector('.user-menu-container');
        this.loadingOverlay = document.getElementById('loading-overlay');
        this.adminMain = document.querySelector('.admin-main');
        
        this.init();
    }
    
    init() {
        this.setupSidebarToggle();
        this.setupThemeToggle();
        this.setupUserMenu();
        this.setupNavigation();
        this.setupBrowserHistory();
        this.setupInitialState();
    }
    
    setupSidebarToggle() {
        this.sidebarToggleBtn.addEventListener('click', () => {
            this.sidebar.classList.toggle('collapsed');
            
            // Save sidebar state
            const isCollapsed = this.sidebar.classList.contains('collapsed');
            localStorage.setItem('sidebar-collapsed', isCollapsed);
        });
        
        // Restore sidebar state
        const isCollapsed = localStorage.getItem('sidebar-collapsed') === 'true';
        if (isCollapsed) {
            this.sidebar.classList.add('collapsed');
        }
    }
    
    setupThemeToggle() {
        this.themeToggleBtn.addEventListener('click', () => {
            this.toggleTheme();
        });
    }
    
    toggleTheme() {
        const currentTheme = document.body.classList.contains('dark-theme') ? 'dark' : 'light';
        const newTheme = currentTheme === 'dark' ? 'light' : 'dark';
        
        // Update body class
        document.body.classList.remove('dark-theme', 'light-theme');
        document.body.classList.add(newTheme + '-theme');
        
        // Update button appearance
        const themeIcon = document.getElementById('theme-icon');
        const themeText = document.getElementById('theme-text');
        
        if (newTheme === 'dark') {
            themeIcon.className = 'fas fa-sun';
            themeText.textContent = 'Hell';
        } else {
            themeIcon.className = 'fas fa-moon';
            themeText.textContent = 'Dunkel';
        }
        
        // Save theme preference
        localStorage.setItem('admin-theme', newTheme);
        
        // Update theme manager if available
        if (window.themeManager) {
            window.themeManager.setTheme(newTheme);
        }
    }
    
    setupUserMenu() {
        this.userMenuBtn.addEventListener('click', (e) => {
            e.preventDefault();
            this.userMenuContainer.classList.toggle('active');
        });
        
        // Close user menu when clicking outside
        document.addEventListener('click', (e) => {
            if (!this.userMenuContainer.contains(e.target)) {
                this.userMenuContainer.classList.remove('active');
            }
        });
    }
    
    setupNavigation() {
        const navItems = document.querySelectorAll('.nav-item[data-url]');
        
        navItems.forEach(item => {
            item.addEventListener('click', (e) => {
                // Check if this is a special action (like edit, delete, etc.)
                const currentUrl = new URL(window.location);
                const hasSpecialParams = currentUrl.searchParams.has('action') || 
                                       currentUrl.searchParams.has('id') || 
                                       currentUrl.searchParams.has('edit') ||
                                       currentUrl.searchParams.has('delete');
                
                if (hasSpecialParams) {
                    // For special actions, do normal navigation
                    return;
                }
                
                e.preventDefault();
                
                const url = item.getAttribute('data-url');
                const page = item.getAttribute('data-page');
                
                this.loadPage(url, page, item);
            });
        });
        
        // Handle user dropdown items
        const userDropdownItems = document.querySelectorAll('.user-dropdown-item[data-url]');
        userDropdownItems.forEach(item => {
            item.addEventListener('click', (e) => {
                // Check if this is a special action
                const currentUrl = new URL(window.location);
                const hasSpecialParams = currentUrl.searchParams.has('action') || 
                                       currentUrl.searchParams.has('id') || 
                                       currentUrl.searchParams.has('edit') ||
                                       currentUrl.searchParams.has('delete');
                
                if (hasSpecialParams) {
                    // For special actions, do normal navigation
                    return;
                }
                
                e.preventDefault();
                
                const url = item.getAttribute('data-url');
                const page = item.getAttribute('data-page');
                
                this.loadPage(url, page, item);
                this.userMenuContainer.classList.remove('active');
            });
        });
    }
    
    async loadPage(url, page, clickedItem) {
        try {
            // Update active state
            this.updateActiveState(page);
            
            // Show loading
            this.showLoading();
            
            // Preserve current URL parameters
            const currentUrl = new URL(window.location);
            const targetUrl = new URL(url, window.location.origin);
            
            // Copy current parameters to target URL
            currentUrl.searchParams.forEach((value, key) => {
                if (!targetUrl.searchParams.has(key)) {
                    targetUrl.searchParams.set(key, value);
                }
            });
            
            // Load content via AJAX
            const response = await fetch(targetUrl.toString());
            const html = await response.text();
            
            // Extract main content from response
            const parser = new DOMParser();
            const doc = parser.parseFromString(html, 'text/html');
            const newMainContent = doc.querySelector('.admin-main');
            
            if (newMainContent) {
                // Replace content with animation
                await this.animateContentChange(newMainContent.innerHTML);
                
                // Update browser URL without reload
                window.history.pushState({}, '', targetUrl.toString());
            } else {
                // Fallback to page reload
                window.location.href = targetUrl.toString();
            }
            
        } catch (error) {
            console.error('Error loading page:', error);
            this.hideLoading();
            
            // Fallback to page reload
            window.location.href = url;
        }
    }
    
    updateActiveState(page) {
        // Remove active class from all nav items
        document.querySelectorAll('.nav-item').forEach(nav => {
            nav.classList.remove('active');
        });
        
        // Add active class to current page
        const activeNavItem = document.querySelector(`[data-page="${page}"]`);
        if (activeNavItem) {
            activeNavItem.classList.add('active');
        }
    }
    
    showLoading() {
        this.loadingOverlay.classList.add('active');
    }
    
    hideLoading() {
        this.loadingOverlay.classList.remove('active');
    }
    
    async animateContentChange(newContent) {
        return new Promise((resolve) => {
            // Fade out current content
            this.adminMain.style.opacity = '0';
            this.adminMain.style.transform = 'translateY(20px)';
            
            setTimeout(() => {
                // Replace content
                this.adminMain.innerHTML = newContent;
                
                // Fade in new content
                this.adminMain.style.opacity = '1';
                this.adminMain.style.transform = 'translateY(0)';
                
                // Hide loading
                this.hideLoading();
                
                // Reinitialize any scripts in the new content
                this.reinitializeScripts();
                
                resolve();
            }, 300);
        });
    }
    
    reinitializeScripts() {
        // Re-run any scripts that might be in the loaded content
        const scripts = this.adminMain.querySelectorAll('script');
        scripts.forEach(script => {
            const newScript = document.createElement('script');
            newScript.textContent = script.textContent;
            document.head.appendChild(newScript);
            document.head.removeChild(newScript);
        });
    }
    
    setupBrowserHistory() {
        // Handle browser back/forward buttons
        window.addEventListener('popstate', (event) => {
            const url = new URL(window.location);
            const pathname = url.pathname;
            
            // Determine page from pathname
            let page = 'dashboard';
            if (pathname.includes('events.php')) page = 'events';
            else if (pathname.includes('appointments.php')) page = 'appointments';
            else if (pathname.includes('storage.php')) page = 'storage';
            else if (pathname.includes('profile.php')) page = 'profile';
            else if (pathname.includes('settings.php')) page = 'settings';
            else if (pathname.includes('users.php')) page = 'users';
            
            // Update active state
            this.updateActiveState(page);
            
            // Reload page content
            this.loadPageFromUrl(window.location.href);
        });
    }
    
    async loadPageFromUrl(url) {
        try {
            this.showLoading();
            
            const response = await fetch(url);
            const html = await response.text();
            
            const parser = new DOMParser();
            const doc = parser.parseFromString(html, 'text/html');
            const newMainContent = doc.querySelector('.admin-main');
            
            if (newMainContent) {
                await this.animateContentChange(newMainContent.innerHTML);
            }
            
        } catch (error) {
            console.error('Error loading page from URL:', error);
            this.hideLoading();
            window.location.reload();
        }
    }
    
    setupInitialState() {
        // Set initial active state
        const currentPage = window.currentPage || 'dashboard';
        this.updateActiveState(currentPage);
        
        // Initialize theme
        const savedTheme = localStorage.getItem('admin-theme') || 'light';
        document.body.classList.add(savedTheme + '-theme');
        
        const themeIcon = document.getElementById('theme-icon');
        const themeText = document.getElementById('theme-text');
        
        if (savedTheme === 'dark') {
            themeIcon.className = 'fas fa-sun';
            themeText.textContent = 'Hell';
        } else {
            themeIcon.className = 'fas fa-moon';
            themeText.textContent = 'Dunkel';
        }
    }
}

// Initialize when DOM is loaded
document.addEventListener('DOMContentLoaded', function() {
    new ModernSidebar();
});

// Export for global access
window.ModernSidebar = ModernSidebar;
