// Admin Panel JavaScript - Modern & Interactive
document.addEventListener('DOMContentLoaded', function () {

    // Initialize page loader
    initPageLoader();

    // Initialize sidebar
    initSidebar();

    // Initialize header interactions
    initHeader();

    // Initialize tooltips and popovers
    initTooltips();

    // Initialize command palette
    initCommandPalette();

    // Initialize charts
    initCharts();

    // Initialize animations
    initAnimations();

    // Initialize theme toggle
    initThemeToggle();

    // Initialize search functionality
    initSearch();

    // Initialize perfect scrollbar
    initScrollbars();
});

// Page Loader
function initPageLoader() {
    const loader = document.getElementById('pageLoader');

    window.addEventListener('load', function () {
        setTimeout(() => {
            if (loader) {
                loader.classList.add('hidden');
                setTimeout(() => {
                    loader.remove();
                }, 500);
            }
        }, 800);
    });
}

// Sidebar Management
function initSidebar() {
    const sidebar = document.getElementById('adminSidebar');
    const collapseBtn = document.getElementById('sidebarCollapseBtn');
    const mobileToggle = document.getElementById('mobileMenuToggle');
    const backdrop = document.getElementById('backdrop');

    // Collapse/Expand functionality
    if (collapseBtn) {
        collapseBtn.addEventListener('click', function () {
            sidebar.classList.toggle('collapsed');

            // Rotate arrow icon
            const icon = this.querySelector('i');
            if (sidebar.classList.contains('collapsed')) {
                icon.style.transform = 'rotate(180deg)';
                localStorage.setItem('sidebarCollapsed', 'true');
            } else {
                icon.style.transform = 'rotate(0deg)';
                localStorage.setItem('sidebarCollapsed', 'false');
            }
        });
    }

    // Restore sidebar state
    const sidebarCollapsed = localStorage.getItem('sidebarCollapsed');
    if (sidebarCollapsed === 'true' && sidebar) {
        sidebar.classList.add('collapsed');
        const icon = collapseBtn?.querySelector('i');
        if (icon) icon.style.transform = 'rotate(180deg)';
    }

    // Mobile menu toggle
    if (mobileToggle) {
        mobileToggle.addEventListener('click', function () {
            sidebar.classList.toggle('show');
            backdrop.classList.toggle('show');
            document.body.style.overflow = sidebar.classList.contains('show') ? 'hidden' : '';
        });
    }

    // Close mobile menu on backdrop click
    if (backdrop) {
        backdrop.addEventListener('click', function () {
            sidebar.classList.remove('show');
            backdrop.classList.remove('show');
            document.body.style.overflow = '';
        });
    }

    // Submenu toggle
    const menuItems = document.querySelectorAll('.menu-item.has-submenu');
    menuItems.forEach(item => {
        const link = item.querySelector('.menu-link');
        const submenu = item.querySelector('.submenu');

        if (link && submenu) {
            link.addEventListener('click', function (e) {
                e.preventDefault();

                // Close other submenus
                menuItems.forEach(otherItem => {
                    if (otherItem !== item) {
                        otherItem.classList.remove('open');
                    }
                });

                // Toggle current submenu
                item.classList.toggle('open');
            });
        }
    });

    // Sidebar search functionality
    const sidebarSearch = document.querySelector('.sidebar-search .search-input');
    if (sidebarSearch) {
        sidebarSearch.addEventListener('input', function () {
            const searchTerm = this.value.toLowerCase();
            const menuItems = document.querySelectorAll('.menu-item');

            menuItems.forEach(item => {
                const menuText = item.querySelector('.menu-text');
                const submenuLinks = item.querySelectorAll('.submenu-link');
                let found = false;

                // Check main menu text
                if (menuText && menuText.textContent.toLowerCase().includes(searchTerm)) {
                    found = true;
                }

                // Check submenu items
                submenuLinks.forEach(link => {
                    if (link.textContent.toLowerCase().includes(searchTerm)) {
                        found = true;
                        item.classList.add('open'); // Open submenu if match found
                    }
                });

                // Show/hide menu item
                item.style.display = found || searchTerm === '' ? 'block' : 'none';
            });
        });
    }
}

// Header Interactions
function initHeader() {
    const dropdownToggles = document.querySelectorAll('[data-bs-toggle="dropdown"]');
    dropdownToggles.forEach(toggle => {
        toggle.addEventListener('click', function (e) {
            e.preventDefault();
            e.stopPropagation();

            // Close other dropdowns first
            const allDropdowns = document.querySelectorAll('.dropdown-menu');
            allDropdowns.forEach(dropdown => {
                if (dropdown !== this.nextElementSibling) {
                    dropdown.classList.remove('show');
                }
            });

            // Toggle current dropdown
            const dropdown = this.nextElementSibling;
            if (dropdown) {
                dropdown.classList.toggle('show');
            }
        });
    });

    // User dropdown
    const userDropdownToggles = document.querySelectorAll('[data-bs-toggle="dropdown"]');
    userDropdownToggles.forEach(toggle => {
        toggle.addEventListener('click', function (e) {
            e.preventDefault();
            e.stopPropagation();

            // Close other dropdowns first
            const allDropdowns = document.querySelectorAll('.dropdown-menu');
            allDropdowns.forEach(dropdown => {
                if (dropdown !== this.nextElementSibling) {
                    dropdown.classList.remove('show');
                }
            });

            // Toggle current dropdown
            const dropdown = this.nextElementSibling;
            if (dropdown) {
                dropdown.classList.toggle('show');
            }
        });
    });

    // Notification dropdown specific
    const notificationBtn = document.querySelector('.notification-btn');
    if (notificationBtn) {
        notificationBtn.addEventListener('click', function (e) {
            e.preventDefault();
            e.stopPropagation();

            // Close other dropdowns
            const allDropdowns = document.querySelectorAll('.dropdown-menu, .user-dropdown');
            allDropdowns.forEach(dropdown => {
                dropdown.classList.remove('show');
            });

            // Toggle notification dropdown
            const notificationDropdown = this.nextElementSibling;
            if (notificationDropdown) {
                notificationDropdown.classList.toggle('show');
            }
        });
    }

    // User menu dropdown specific
    const userMenuToggle = document.querySelector('.user-menu-toggle');
    if (userMenuToggle) {
        userMenuToggle.addEventListener('click', function (e) {
            e.preventDefault();
            e.stopPropagation();

            // Close other dropdowns
            const allDropdowns = document.querySelectorAll('.dropdown-menu, .notification-dropdown');
            allDropdowns.forEach(dropdown => {
                dropdown.classList.remove('show');
            });

            // Toggle user dropdown
            const userDropdown = this.nextElementSibling;
            if (userDropdown) {
                userDropdown.classList.toggle('show');
            }
        });
    }

    // Quick add dropdown
    const quickAddBtn = document.querySelector('.header-action-btn[data-bs-toggle="dropdown"]');
    if (quickAddBtn) {
        quickAddBtn.addEventListener('click', function (e) {
            e.preventDefault();
            e.stopPropagation();

            // Close other dropdowns
            const allDropdowns = document.querySelectorAll('.notification-dropdown, .user-dropdown');
            allDropdowns.forEach(dropdown => {
                dropdown.classList.remove('show');
            });

            // Toggle quick add dropdown
            const dropdown = this.nextElementSibling;
            if (dropdown) {
                dropdown.classList.toggle('show');
            }
        });
    }

    // Close dropdowns when clicking outside
    document.addEventListener('click', function (e) {
        const dropdowns = document.querySelectorAll('.dropdown-menu.show, .notification-dropdown.show, .user-dropdown.show');
        dropdowns.forEach(dropdown => {
            dropdown.classList.remove('show');
        });
    });

    // Prevent dropdown content clicks from closing dropdown
    const dropdownContents = document.querySelectorAll('.dropdown-menu, .notification-dropdown, .user-dropdown');
    dropdownContents.forEach(dropdown => {
        dropdown.addEventListener('click', function (e) {
            e.stopPropagation();
        });
    });

    // Notification mark as read
    const markAllReadBtn = document.querySelector('.mark-all-read');
    if (markAllReadBtn) {
        markAllReadBtn.addEventListener('click', function (e) {
            e.stopPropagation();
            const unreadItems = document.querySelectorAll('.notification-item.unread');
            unreadItems.forEach(item => {
                item.classList.remove('unread');
            });

            // Update badge count
            const badge = document.querySelector('.notification-badge');
            if (badge) {
                badge.textContent = '0';
                badge.style.display = 'none';
            }
        });
    }
}

// Command Palette
function initCommandPalette() {
    const commandPalette = document.getElementById('commandPalette');
    const searchInput = document.querySelector('.global-search .search-input');

    // Open command palette with Ctrl+K
    document.addEventListener('keydown', function (e) {
        if (e.ctrlKey && e.key === 'k') {
            e.preventDefault();
            if (commandPalette) {
                commandPalette.classList.add('show');
                const paletteInput = commandPalette.querySelector('input');
                if (paletteInput) {
                    paletteInput.focus();
                }
            }
        }

        // Close with Escape
        if (e.key === 'Escape') {
            if (commandPalette) {
                commandPalette.classList.remove('show');
            }
        }
    });

    // Focus search on click
    if (searchInput) {
        searchInput.addEventListener('click', function () {
            if (commandPalette) {
                commandPalette.classList.add('show');
                const paletteInput = commandPalette.querySelector('input');
                if (paletteInput) {
                    paletteInput.focus();
                    paletteInput.value = this.value;
                }
            }
        });
    }

    // Close command palette on backdrop click
    if (commandPalette) {
        commandPalette.addEventListener('click', function (e) {
            if (e.target === this) {
                this.classList.remove('show');
            }
        });
    }
}

// Charts Initialization
function initCharts() {
    // Mini sparkline charts for stats cards
    const chartElements = document.querySelectorAll('[id$="Chart"]');

    chartElements.forEach(element => {
        if (element.getContext) {
            const ctx = element.getContext('2d');

            // Generate sample data
            const data = generateSparklineData();

            // Draw sparkline
            drawSparkline(ctx, data, element.width, element.height);
        }
    });

    // Main performance chart
    const performanceChart = document.getElementById('performanceChart');
    if (performanceChart) {
        initPerformanceChart(performanceChart);
    }
}

// Generate sample sparkline data
function generateSparklineData() {
    const data = [];
    let value = 50;

    for (let i = 0; i < 20; i++) {
        value += (Math.random() - 0.5) * 10;
        value = Math.max(0, Math.min(100, value));
        data.push(value);
    }

    return data;
}

// Draw sparkline chart
function drawSparkline(ctx, data, width, height) {
    const padding = 4;
    const chartWidth = width - padding * 2;
    const chartHeight = height - padding * 2;

    const max = Math.max(...data);
    const min = Math.min(...data);
    const range = max - min || 1;

    ctx.clearRect(0, 0, width, height);
    ctx.strokeStyle = '#3b82f6';
    ctx.lineWidth = 2;
    ctx.lineCap = 'round';
    ctx.lineJoin = 'round';

    ctx.beginPath();

    data.forEach((value, index) => {
        const x = padding + (index / (data.length - 1)) * chartWidth;
        const y = padding + chartHeight - ((value - min) / range) * chartHeight;

        if (index === 0) {
            ctx.moveTo(x, y);
        } else {
            ctx.lineTo(x, y);
        }
    });

    ctx.stroke();

    // Add gradient fill
    const gradient = ctx.createLinearGradient(0, 0, 0, height);
    gradient.addColorStop(0, 'rgba(59, 130, 246, 0.1)');
    gradient.addColorStop(1, 'rgba(59, 130, 246, 0)');

    ctx.fillStyle = gradient;
    ctx.lineTo(width - padding, height - padding);
    ctx.lineTo(padding, height - padding);
    ctx.closePath();
    ctx.fill();
}

// Performance Chart
function initPerformanceChart(canvas) {
    // This would typically use Chart.js or similar library
    // For demo purposes, we'll create a simple implementation

    const ctx = canvas.getContext('2d');
    const width = canvas.width;
    const height = canvas.height;

    // Sample data
    const labels = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'];
    const datasets = [
        {label: 'Kullanıcılar', data: [65, 78, 90, 81, 56, 85], color: '#3b82f6'},
        {label: 'Acenteler', data: [28, 48, 40, 19, 86, 27], color: '#10b981'},
        {label: 'Rezervasyonlar', data: [18, 28, 30, 39, 46, 37], color: '#f59e0b'}
    ];

    drawLineChart(ctx, width, height, labels, datasets);
}

// Simple line chart implementation
function drawLineChart(ctx, width, height, labels, datasets) {
    const padding = 60;
    const chartWidth = width - padding * 2;
    const chartHeight = height - padding * 2;

    ctx.clearRect(0, 0, width, height);

    // Find max value for scaling
    const allValues = datasets.flatMap(d => d.data);
    const maxValue = Math.max(...allValues);
    const minValue = Math.min(...allValues);
    const valueRange = maxValue - minValue || 1;

    // Draw grid lines
    ctx.strokeStyle = '#e5e7eb';
    ctx.lineWidth = 1;

    for (let i = 0; i <= 5; i++) {
        const y = padding + (i / 5) * chartHeight;
        ctx.beginPath();
        ctx.moveTo(padding, y);
        ctx.lineTo(width - padding, y);
        ctx.stroke();
    }

    // Draw datasets
    datasets.forEach(dataset => {
        ctx.strokeStyle = dataset.color;
        ctx.lineWidth = 3;
        ctx.lineCap = 'round';
        ctx.lineJoin = 'round';

        ctx.beginPath();

        dataset.data.forEach((value, index) => {
            const x = padding + (index / (dataset.data.length - 1)) * chartWidth;
            const y = padding + chartHeight - ((value - minValue) / valueRange) * chartHeight;

            if (index === 0) {
                ctx.moveTo(x, y);
            } else {
                ctx.lineTo(x, y);
            }
        });

        ctx.stroke();

        // Draw points
        ctx.fillStyle = dataset.color;
        dataset.data.forEach((value, index) => {
            const x = padding + (index / (dataset.data.length - 1)) * chartWidth;
            const y = padding + chartHeight - ((value - minValue) / valueRange) * chartHeight;

            ctx.beginPath();
            ctx.arc(x, y, 4, 0, Math.PI * 2);
            ctx.fill();
        });
    });

    // Draw labels
    ctx.fillStyle = '#6b7280';
    ctx.font = '12px Inter';
    ctx.textAlign = 'center';

    labels.forEach((label, index) => {
        const x = padding + (index / (labels.length - 1)) * chartWidth;
        ctx.fillText(label, x, height - padding + 20);
    });
}

// Theme Toggle
function initThemeToggle() {
    const themeToggle = document.getElementById('themeToggle');
    const currentTheme = localStorage.getItem('theme') || 'light';

    // Apply saved theme
    document.documentElement.setAttribute('data-theme', currentTheme);
    updateThemeIcon(themeToggle, currentTheme);

    if (themeToggle) {
        themeToggle.addEventListener('click', function () {
            const currentTheme = document.documentElement.getAttribute('data-theme') || 'light';
            const newTheme = currentTheme === 'light' ? 'dark' : 'light';

            document.documentElement.setAttribute('data-theme', newTheme);
            localStorage.setItem('theme', newTheme);
            updateThemeIcon(this, newTheme);
        });
    }
}

function updateThemeIcon(button, theme) {
    if (!button) return;

    const icon = button.querySelector('i');
    if (icon) {
        icon.className = theme === 'light' ? 'fas fa-moon' : 'fas fa-sun';
    }
}

// Search Functionality
function initSearch() {
    const searchInputs = document.querySelectorAll('.search-input');

    searchInputs.forEach(input => {
        // Add search suggestions/autocomplete here
        input.addEventListener('input', function () {
            const query = this.value.trim();

            if (query.length > 2) {
                // Simulate search results
                showSearchSuggestions(this, query);
            } else {
                hideSearchSuggestions(this);
            }
        });

        // Handle keyboard navigation
        input.addEventListener('keydown', function (e) {
            if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
                e.preventDefault();
                navigateSearchSuggestions(e.key);
            } else if (e.key === 'Enter') {
                e.preventDefault();
                selectSearchSuggestion();
            }
        });
    });
}

function showSearchSuggestions(input, query) {
    // This would typically make an AJAX request
    // For demo purposes, we'll show some mock suggestions

    const suggestions = [
        {type: 'page', title: 'Dashboard', url: '/admin/dashboard'},
        {type: 'page', title: 'Kullanıcılar', url: '/admin/users'},
        {type: 'page', title: 'Acenteler', url: '/admin/agencies'},
        {type: 'action', title: 'Yeni Kullanıcı Ekle', action: 'create-user'},
        {type: 'action', title: 'Rapor İndir', action: 'download-report'}
    ].filter(item => item.title.toLowerCase().includes(query.toLowerCase()));

    // Create or update suggestions dropdown
    let dropdown = input.parentNode.querySelector('.search-suggestions');
    if (!dropdown) {
        dropdown = document.createElement('div');
        dropdown.className = 'search-suggestions';
        input.parentNode.appendChild(dropdown);
    }

    dropdown.innerHTML = suggestions.map((item, index) => `
        <div class="suggestion-item" data-index="${index}" data-type="${item.type}" data-url="${item.url || ''}" data-action="${item.action || ''}">
            <i class="fas fa-${item.type === 'page' ? 'file' : 'bolt'}"></i>
            <span>${item.title}</span>
        </div>
    `).join('');

    dropdown.style.display = suggestions.length > 0 ? 'block' : 'none';
}

function hideSearchSuggestions(input) {
    const dropdown = input.parentNode.querySelector('.search-suggestions');
    if (dropdown) {
        dropdown.style.display = 'none';
    }
}

// Tooltips
function initTooltips() {
    const tooltipElements = document.querySelectorAll('[title]');

    tooltipElements.forEach(element => {
        element.addEventListener('mouseenter', function () {
            showTooltip(this);
        });

        element.addEventListener('mouseleave', function () {
            hideTooltip();
        });
    });
}

function showTooltip(element) {
    const title = element.getAttribute('title');
    if (!title) return;

    // Remove title to prevent browser tooltip
    element.setAttribute('data-title', title);
    element.removeAttribute('title');

    // Create tooltip
    const tooltip = document.createElement('div');
    tooltip.className = 'custom-tooltip';
    tooltip.textContent = title;
    document.body.appendChild(tooltip);

    // Position tooltip
    const rect = element.getBoundingClientRect();
    tooltip.style.left = rect.left + rect.width / 2 - tooltip.offsetWidth / 2 + 'px';
    tooltip.style.top = rect.top - tooltip.offsetHeight - 8 + 'px';

    // Show with animation
    setTimeout(() => tooltip.classList.add('show'), 10);
}

function hideTooltip() {
    const tooltips = document.querySelectorAll('.custom-tooltip');
    tooltips.forEach(tooltip => {
        tooltip.classList.remove('show');
        setTimeout(() => tooltip.remove(), 150);
    });

    // Restore title attributes
    const elements = document.querySelectorAll('[data-title]');
    elements.forEach(element => {
        element.setAttribute('title', element.getAttribute('data-title'));
        element.removeAttribute('data-title');
    });
}

// Perfect Scrollbar
function initScrollbars() {
    const sidebarMenu = document.querySelector('.sidebar-menu');
    const dropdownMenus = document.querySelectorAll('.dropdown-menu');

    // Only initialize Perfect Scrollbar if library is available
    if (typeof PerfectScrollbar !== 'undefined') {
        if (sidebarMenu) {
            new PerfectScrollbar(sidebarMenu, {
                wheelSpeed: 2,
                wheelPropagation: false,
                minScrollbarLength: 20,
                suppressScrollX: true
            });
        }

        dropdownMenus.forEach(element => {
            new PerfectScrollbar(element, {
                wheelSpeed: 2,
                wheelPropagation: false,
                minScrollbarLength: 20,
                suppressScrollX: true
            });
        });
    } else {
        // Fallback: ensure native scrolling works
        if (sidebarMenu) {
            sidebarMenu.style.overflowY = 'auto';
            sidebarMenu.style.overflowX = 'hidden';
        }

        dropdownMenus.forEach(element => {
            element.style.overflowY = 'auto';
            element.style.overflowX = 'hidden';
        });
    }
}

// Animations
function initAnimations() {
    // Intersection Observer for scroll animations
    const observerOptions = {
        threshold: 0.1,
        rootMargin: '0px 0px -50px 0px'
    };

    const observer = new IntersectionObserver((entries) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                entry.target.classList.add('animate__animated', 'animate__fadeInUp');
                observer.unobserve(entry.target);
            }
        });
    }, observerOptions);

    // Observe cards and stats
    const animatedElements = document.querySelectorAll('.card, .stats-card');
    animatedElements.forEach(element => {
        observer.observe(element);
    });

    // Counter animations
    const counters = document.querySelectorAll('.stats-number');
    counters.forEach(counter => {
        animateCounter(counter);
    });
}

function animateCounter(element) {
    const target = parseInt(element.textContent.replace(/\D/g, ''));
    const duration = 2000;
    const step = target / (duration / 16);
    let current = 0;

    const timer = setInterval(() => {
        current += step;
        if (current >= target) {
            element.textContent = formatNumber(target);
            clearInterval(timer);
        } else {
            element.textContent = formatNumber(Math.floor(current));
        }
    }, 16);
}

function formatNumber(number) {
    return new Intl.NumberFormat('tr-TR').format(number);
}

// Dashboard specific functions
function initDashboardInteractions() {
    // Filter tabs
    const filterTabs = document.querySelectorAll('.filter-tab');
    filterTabs.forEach(tab => {
        tab.addEventListener('click', function () {
            // Remove active class from all tabs
            filterTabs.forEach(t => t.classList.remove('active'));

            // Add active class to clicked tab
            this.classList.add('active');

            // Filter table data based on selection
            const filter = this.getAttribute('data-filter');
            filterTableData(filter);
        });
    });

    // Period buttons for charts
    const periodButtons = document.querySelectorAll('.btn-group-toggle .btn');
    periodButtons.forEach(button => {
        button.addEventListener('click', function () {
            // Remove active class from all buttons
            periodButtons.forEach(b => b.classList.remove('active'));

            // Add active class to clicked button
            this.classList.add('active');

            // Update chart data
            const period = this.getAttribute('data-period');
            updateChartData(period);
        });
    });
}

function filterTableData(filter) {
    const tableRows = document.querySelectorAll('.data-table tbody tr');

    tableRows.forEach(row => {
        const statusBadge = row.querySelector('.status-badge');
        if (!statusBadge) return;

        const status = statusBadge.classList.contains('pending') ? 'pending' :
            statusBadge.classList.contains('confirmed') ? 'confirmed' :
                statusBadge.classList.contains('approved') ? 'confirmed' : 'other';

        if (filter === 'all' || status === filter) {
            row.style.display = '';
            // Add slide in animation
            row.style.animation = 'slideInRight 0.3s ease-out';
        } else {
            row.style.display = 'none';
        }
    });
}

function updateChartData(period) {
    // This would typically make an AJAX request to get new data
    console.log('Updating chart data for period:', period);

    // Show loading state
    const chartContainer = document.querySelector('.chart-container');
    if (chartContainer) {
        chartContainer.style.opacity = '0.5';

        // Simulate data loading
        setTimeout(() => {
            chartContainer.style.opacity = '1';

            // Re-initialize chart with new data
            const performanceChart = document.getElementById('performanceChart');
            if (performanceChart) {
                initPerformanceChart(performanceChart);
            }
        }, 500);
    }
}

// Auto-refresh functionality
function initAutoRefresh() {
    // Refresh stats every 30 seconds
    setInterval(() => {
        updateDashboardStats();
    }, 30000);

    // Refresh notifications every 60 seconds
    setInterval(() => {
        updateNotifications();
    }, 60000);
}

function updateDashboardStats() {
    // This would make an AJAX request to get updated stats
    console.log('Refreshing dashboard stats...');
}

function updateNotifications() {
    // This would make an AJAX request to get new notifications
    console.log('Checking for new notifications...');
}

// Initialize dashboard specific features if we're on dashboard page
if (document.querySelector('.dashboard-container')) {
    document.addEventListener('DOMContentLoaded', function () {
        initDashboardInteractions();
        initAutoRefresh();
    });
}

// Utility functions
function debounce(func, wait) {
    let timeout;
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}

function throttle(func, limit) {
    let inThrottle;
    return function () {
        const args = arguments;
        const context = this;
        if (!inThrottle) {
            func.apply(context, args);
            inThrottle = true;
            setTimeout(() => inThrottle = false, limit);
        }
    }
}

// Export functions for external use
window.AdminPanel = {
    initCharts,
    updateChartData,
    showTooltip,
    hideTooltip,
    formatNumber,
    debounce,
    throttle
};
