/**
 * Dashboard Manager - Core functionality for Prolex Dashboard
 * Implements Phase 2, Phase 3, and Phase 4 features: theme toggle, filtering, sorting, accessibility, search,
 * card resizing, pinning, enhanced charts, advanced task management, analytics, lazy loading, and performance optimizations
 */

class DashboardManager {
    constructor() {
        this.cards = [];
        this.currentTheme = 'light';
        this.searchTerm = '';
        this.filterValue = 'all';
        this.sortValue = 'default';
        this.refreshInterval = null;
        this.isRefreshing = false;
        this.pinnedCards = new Set();
        this.cardSizes = new Map();
        this.taskData = [];
        this.analyticsData = {};
        this.chartInstances = new Map();
        this.lazyLoadedComponents = new Set();
        this.errorBoundaries = new Map();
        this.offlineMode = false;
        this.loadingStates = new Map();

        this.init();
    }

    init() {
        this.loadTheme();
        this.setupEventListeners();
        this.initializeCards();
        this.setupAccessibility();
        this.startRefreshSimulation();
        this.loadFromStorage();
        this.initializePhase3Features();
        this.loadAnalyticsData();
        this.initializePhase4Features();
    }

    // ===== PHASE 4: PERFORMANCE & UX OPTIMIZATION =====

    initializePhase4Features() {
        this.setupLazyLoading();
        this.setupLoadingSkeletons();
        this.setupErrorBoundaries();
        this.setupOfflineMode();
        this.setupExportFunctionality();
        this.optimizeBundleSize();
        this.addMicroInteractions();
    }

    // Lazy Loading Implementation
    setupLazyLoading() {
        this.intersectionObserver = new IntersectionObserver((entries) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    const card = entry.target;
                    this.lazyLoadCard(card);
                }
            });
        }, {
            rootMargin: '50px 0px',
            threshold: 0.1
        });

        // Observe all cards for lazy loading
        this.cards.forEach(card => {
            this.intersectionObserver.observe(card);
        });
    }

    lazyLoadCard(card) {
        const cardId = card.getAttribute('data-card');
        if (this.lazyLoadedComponents.has(cardId)) return;

        // Add loading state
        this.showLoadingSkeleton(card);

        // Simulate lazy loading delay
        setTimeout(() => {
            this.loadCardContent(card);
            this.lazyLoadedComponents.add(cardId);
            this.hideLoadingSkeleton(card);
        }, 200);
    }

    loadCardContent(card) {
        const cardId = card.getAttribute('data-card');

        switch (cardId) {
            case 'charts':
                this.lazyLoadChart(card);
                break;
            case 'analytics':
                this.lazyLoadAnalytics(card);
                break;
            case 'tasks':
                this.lazyLoadTasks(card);
                break;
            default:
                // For other cards, just ensure content is visible
                card.classList.add('loaded');
        }
    }

    lazyLoadChart(card) {
        if (!this.chartInstances.has('dashboardChart')) {
            this.createChart('dashboardChart', 'bar');
        }
        card.classList.add('loaded');
    }

    lazyLoadAnalytics(card) {
        this.renderAnalyticsWidgets(card);
        card.classList.add('loaded');
    }

    lazyLoadTasks(card) {
        this.renderTaskList(card);
        card.classList.add('loaded');
    }

    // Loading Skeletons
    setupLoadingSkeletons() {
        // Create skeleton templates
        this.createSkeletonTemplates();
    }

    createSkeletonTemplates() {
        const skeletonTemplates = {
            card: `
                <div class="skeleton-card">
                    <div class="skeleton-header">
                        <div class="skeleton-icon"></div>
                        <div class="skeleton-title"></div>
                    </div>
                    <div class="skeleton-content">
                        <div class="skeleton-line"></div>
                        <div class="skeleton-line short"></div>
                        <div class="skeleton-line"></div>
                    </div>
                </div>
            `,
            chart: `
                <div class="skeleton-chart">
                    <div class="skeleton-header">
                        <div class="skeleton-icon"></div>
                        <div class="skeleton-title"></div>
                    </div>
                    <div class="skeleton-chart-canvas"></div>
                </div>
            `,
            analytics: `
                <div class="skeleton-analytics">
                    <div class="skeleton-widget"></div>
                    <div class="skeleton-widget"></div>
                    <div class="skeleton-widget"></div>
                    <div class="skeleton-widget"></div>
                </div>
            `
        };

        this.skeletonTemplates = skeletonTemplates;
    }

    showLoadingSkeleton(card) {
        const cardId = card.getAttribute('data-card');
        const skeletonType = this.getSkeletonType(cardId);

        if (this.skeletonTemplates[skeletonType]) {
            card.innerHTML = this.skeletonTemplates[skeletonType];
            card.classList.add('loading');
        }
    }

    hideLoadingSkeleton(card) {
        card.classList.remove('loading');
        card.classList.add('loaded');
    }

    getSkeletonType(cardId) {
        const skeletonMap = {
            'charts': 'chart',
            'analytics': 'analytics',
            'stats': 'card',
            'tasks': 'card',
            'messages': 'card',
            'notifications': 'card'
        };
        return skeletonMap[cardId] || 'card';
    }

    // Error Boundaries
    setupErrorBoundaries() {
        this.cards.forEach(card => {
            this.wrapCardInErrorBoundary(card);
        });
    }

    wrapCardInErrorBoundary(card) {
        const cardId = card.getAttribute('data-card');
        const errorBoundary = {
            hasError: false,
            error: null,
            retryCount: 0,
            maxRetries: 3
        };

        this.errorBoundaries.set(cardId, errorBoundary);

        // Add error event listeners
        card.addEventListener('error', (e) => {
            this.handleCardError(cardId, e);
        });
    }

    handleCardError(cardId, error) {
        const boundary = this.errorBoundaries.get(cardId);
        if (!boundary) return;

        boundary.hasError = true;
        boundary.error = error;

        if (boundary.retryCount < boundary.maxRetries) {
            boundary.retryCount++;
            this.showErrorState(cardId, true);
            setTimeout(() => {
                this.retryCardLoad(cardId);
            }, 1000 * boundary.retryCount);
        } else {
            this.showErrorState(cardId, false);
        }
    }

    showErrorState(cardId, retryable = true) {
        const card = document.querySelector(`[data-card="${cardId}"]`);
        if (!card) return;

        const errorHtml = `
            <div class="error-boundary">
                <div class="error-icon">
                    <i class="fas fa-exclamation-triangle"></i>
                </div>
                <div class="error-message">
                    <h4>Failed to load content</h4>
                    <p>Something went wrong while loading this section.</p>
                    ${retryable ? '<button class="retry-btn" onclick="dashboardManager.retryCardLoad(\'' + cardId + '\')">Try Again</button>' : ''}
                </div>
            </div>
        `;

        card.innerHTML = errorHtml;
        card.classList.add('error-state');
    }

    retryCardLoad(cardId) {
        const card = document.querySelector(`[data-card="${cardId}"]`);
        if (!card) return;

        const boundary = this.errorBoundaries.get(cardId);
        if (boundary) {
            boundary.hasError = false;
            boundary.error = null;
        }

        card.classList.remove('error-state');
        this.lazyLoadCard(card);
    }

    // Offline Mode Support
    setupOfflineMode() {
        this.checkOnlineStatus();
        window.addEventListener('online', () => this.handleOnline());
        window.addEventListener('offline', () => this.handleOffline());

        // Cache critical data for offline use
        this.setupOfflineCache();
    }

    checkOnlineStatus() {
        this.offlineMode = !navigator.onLine;
        this.updateOfflineUI();
    }

    handleOnline() {
        this.offlineMode = false;
        this.updateOfflineUI();
        this.syncOfflineData();
        this.announceToScreenReader('Connection restored. Syncing data...');
    }

    handleOffline() {
        this.offlineMode = true;
        this.updateOfflineUI();
        this.announceToScreenReader('Connection lost. Working in offline mode.');
    }

    updateOfflineUI() {
        const body = document.body;
        if (this.offlineMode) {
            body.classList.add('offline-mode');
            this.showOfflineIndicator();
        } else {
            body.classList.remove('offline-mode');
            this.hideOfflineIndicator();
        }
    }

    showOfflineIndicator() {
        let indicator = document.getElementById('offline-indicator');
        if (!indicator) {
            indicator = document.createElement('div');
            indicator.id = 'offline-indicator';
            indicator.className = 'offline-indicator';
            indicator.innerHTML = `
                <i class="fas fa-wifi-slash"></i>
                <span>Offline Mode</span>
            `;
            document.body.appendChild(indicator);
        }
        indicator.style.display = 'flex';
    }

    hideOfflineIndicator() {
        const indicator = document.getElementById('offline-indicator');
        if (indicator) {
            indicator.style.display = 'none';
        }
    }

    setupOfflineCache() {
        if ('serviceWorker' in navigator) {
            navigator.serviceWorker.register('/sw.js')
                .then(registration => {
                    console.log('Service Worker registered for offline caching');
                })
                .catch(error => {
                    console.log('Service Worker registration failed');
                });
        }
    }

    syncOfflineData() {
        // Sync any offline changes when connection is restored
        const offlineData = JSON.parse(localStorage.getItem('offline-data') || '[]');
        if (offlineData.length > 0) {
            // In a real app, this would sync with the server
            console.log('Syncing offline data:', offlineData);
            localStorage.removeItem('offline-data');
        }
    }

    // Export Functionality
    setupExportFunctionality() {
        // Add export buttons event listeners
        const exportChartBtn = document.getElementById('exportChart');
        const exportDataBtn = document.getElementById('exportData');

        if (exportChartBtn) {
            exportChartBtn.addEventListener('click', () => this.exportChart());
        }

        if (exportDataBtn) {
            exportDataBtn.addEventListener('click', () => this.exportData());
        }
    }

    exportChart() {
        const canvas = document.getElementById('dashboardChart');
        if (!canvas) {
            this.showNotification('No chart available to export', 'error');
            return;
        }

        try {
            const link = document.createElement('a');
            link.download = `dashboard-chart-${new Date().toISOString().split('T')[0]}.png`;
            link.href = canvas.toDataURL();
            link.click();

            this.showNotification('Chart exported successfully', 'success');
        } catch (error) {
            this.showNotification('Failed to export chart', 'error');
            console.error('Chart export error:', error);
        }
    }

    exportData() {
        try {
            const data = {
                timestamp: new Date().toISOString(),
                cards: this.cards.map(card => ({
                    id: card.getAttribute('data-card'),
                    size: this.cardSizes.get(card.getAttribute('data-card')) || 'default',
                    pinned: this.pinnedCards.has(card.getAttribute('data-card'))
                })),
                theme: this.currentTheme,
                filters: {
                    search: this.searchTerm,
                    filter: this.filterValue,
                    sort: this.sortValue
                },
                analytics: this.analyticsData
            };

            const jsonString = JSON.stringify(data, null, 2);
            const blob = new Blob([jsonString], { type: 'application/json' });
            const url = URL.createObjectURL(blob);

            const link = document.createElement('a');
            link.href = url;
            link.download = `dashboard-data-${new Date().toISOString().split('T')[0]}.json`;
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);

            URL.revokeObjectURL(url);
            this.showNotification('Data exported successfully', 'success');
        } catch (error) {
            this.showNotification('Failed to export data', 'error');
            console.error('Data export error:', error);
        }
    }

    // Bundle Size Optimization
    optimizeBundleSize() {
        // Implement dynamic imports for heavy components
        this.lazyLoadHeavyComponents();

        // Remove unused event listeners
        this.cleanupEventListeners();

        // Compress and cache assets
        this.setupAssetCaching();
    }

    lazyLoadHeavyComponents() {
        // Example: Lazy load chart library if not already loaded
        if (typeof Chart === 'undefined') {
            import('https://cdn.jsdelivr.net/npm/chart.js').then(() => {
                console.log('Chart.js loaded dynamically');
            });
        }
    }

    cleanupEventListeners() {
        // Remove unused event listeners to reduce memory usage
        this.cards.forEach(card => {
            // Clean up any event listeners that are no longer needed
        });
    }

    setupAssetCaching() {
        // Implement service worker for asset caching
        if ('caches' in window) {
            const assets = this.getCacheableAssets();
            if (assets.length === 0) return;

            caches.open('dashboard-v1')
                .then(cache => {
                    return Promise.allSettled(
                        assets.map(url => cache.add(url).catch(() => null))
                    );
                })
                .catch(error => {
                    console.warn('Asset caching skipped:', error);
                });
        }
    }

    getCacheableAssets() {
        const assetUrls = new Set();
        const origin = window.location.origin;

        document.querySelectorAll('link[rel="stylesheet"][href]').forEach(link => {
            try {
                const url = new URL(link.getAttribute('href'), origin);
                if (url.origin === origin) assetUrls.add(url.href);
            } catch (e) {
                // Ignore invalid URLs
            }
        });

        document.querySelectorAll('script[src]').forEach(script => {
            try {
                const url = new URL(script.getAttribute('src'), origin);
                if (url.origin === origin) assetUrls.add(url.href);
            } catch (e) {
                // Ignore invalid URLs
            }
        });

        // Cache the current page shell for offline fallback
        assetUrls.add(window.location.href);

        return Array.from(assetUrls);
    }

    // Micro Interactions
    addMicroInteractions() {
        this.setupHoverEffects();
        this.setupClickAnimations();
        this.setupLoadingAnimations();
    }

    setupHoverEffects() {
        this.cards.forEach(card => {
            card.addEventListener('mouseenter', () => {
                card.style.transform = 'translateY(-2px)';
                card.style.boxShadow = '0 4px 12px rgba(0,0,0,0.15)';
            });

            card.addEventListener('mouseleave', () => {
                card.style.transform = 'translateY(0)';
                card.style.boxShadow = '';
            });
        });
    }

    setupClickAnimations() {
        const buttons = document.querySelectorAll('.btn, .task-item, .activity-item');
        buttons.forEach(button => {
            button.addEventListener('click', () => {
                button.style.transform = 'scale(0.98)';
                setTimeout(() => {
                    button.style.transform = '';
                }, 150);
            });
        });
    }

    setupLoadingAnimations() {
        // Add loading animations for async operations
        this.loadingStates.forEach((state, key) => {
            if (state) {
                const element = document.querySelector(`[data-loading="${key}"]`);
                if (element) {
                    element.classList.add('loading');
                }
            }
        });
    }

    // ===== PHASE 3: ADVANCED FEATURES =====

    initializePhase3Features() {
        this.setupFiltering();
        this.setupSorting();
        this.setupSearch();
        this.setupCardResizing();
        this.setupPinning();
        this.setupAdvancedTaskManagement();
        this.setupEnhancedCharts();
    }

    // Filtering Implementation
    setupFiltering() {
        const filterSelect = document.getElementById('filterSelect');
        if (filterSelect) {
            filterSelect.addEventListener('change', (e) => {
                this.filterValue = e.target.value;
                this.applyFilters();
                this.saveToStorage();
            });
        }
    }

    applyFilters() {
        this.cards.forEach(card => {
            const cardType = card.getAttribute('data-type');
            const shouldShow = this.filterValue === 'all' || cardType === this.filterValue;
            card.style.display = shouldShow ? 'block' : 'none';
        });
    }

    // Sorting Implementation
    setupSorting() {
        const sortSelect = document.getElementById('sortSelect');
        if (sortSelect) {
            sortSelect.addEventListener('change', (e) => {
                this.sortValue = e.target.value;
                this.applySorting();
                this.saveToStorage();
            });
        }
    }

    applySorting() {
        const container = document.querySelector('.dashboard-grid');
        if (!container) return;

        const cardsArray = Array.from(this.cards);

        switch (this.sortValue) {
            case 'name':
                cardsArray.sort((a, b) => {
                    const aTitle = a.querySelector('.card-title')?.textContent || '';
                    const bTitle = b.querySelector('.card-title')?.textContent || '';
                    return aTitle.localeCompare(bTitle);
                });
                break;
            case 'priority':
                cardsArray.sort((a, b) => {
                    const aPriority = a.getAttribute('data-priority') || 'low';
                    const bPriority = b.getAttribute('data-priority') || 'low';
                    const priorityOrder = { 'high': 3, 'medium': 2, 'low': 1 };
                    return priorityOrder[bPriority] - priorityOrder[aPriority];
                });
                break;
            case 'recent':
                cardsArray.sort((a, b) => {
                    const aTime = new Date(a.getAttribute('data-last-updated') || 0);
                    const bTime = new Date(b.getAttribute('data-last-updated') || 0);
                    return bTime - aTime;
                });
                break;
            default:
                // Keep original order
                break;
        }

        // Reorder DOM elements
        cardsArray.forEach(card => {
            container.appendChild(card);
        });
    }

    // Search Implementation
    setupSearch() {
        const searchInput = document.getElementById('dashboardSearch');
        if (searchInput) {
            searchInput.addEventListener('input', (e) => {
                this.searchTerm = e.target.value.toLowerCase();
                this.applySearch();
                this.saveToStorage();
            });
        }
    }

    applySearch() {
        this.cards.forEach(card => {
            const title = card.querySelector('.card-title')?.textContent.toLowerCase() || '';
            const content = card.querySelector('.card-content')?.textContent.toLowerCase() || '';
            const shouldShow = !this.searchTerm ||
                title.includes(this.searchTerm) ||
                content.includes(this.searchTerm);
            card.style.display = shouldShow ? 'block' : 'none';
        });
    }

    // Card Resizing
    setupCardResizing() {
        this.cards.forEach(card => {
            const resizeHandle = card.querySelector('.resize-handle');
            if (resizeHandle) {
                let isResizing = false;
                let startY = 0;
                let startHeight = 0;

                resizeHandle.addEventListener('mousedown', (e) => {
                    isResizing = true;
                    startY = e.clientY;
                    startHeight = card.offsetHeight;
                    document.body.style.cursor = 'ns-resize';
                    e.preventDefault();
                });

                document.addEventListener('mousemove', (e) => {
                    if (!isResizing) return;

                    const deltaY = e.clientY - startY;
                    const newHeight = Math.max(200, startHeight + deltaY);
                    card.style.height = newHeight + 'px';

                    const cardId = card.getAttribute('data-card');
                    this.cardSizes.set(cardId, newHeight);
                    this.saveToStorage();
                });

                document.addEventListener('mouseup', () => {
                    if (isResizing) {
                        isResizing = false;
                        document.body.style.cursor = '';
                    }
                });
            }
        });
    }

    // Card Pinning
    setupPinning() {
        this.cards.forEach(card => {
            const pinBtn = card.querySelector('.pin-btn');
            if (pinBtn) {
                pinBtn.addEventListener('click', () => {
                    const cardId = card.getAttribute('data-card');
                    if (this.pinnedCards.has(cardId)) {
                        this.unpinCard(cardId);
                    } else {
                        this.pinCard(cardId);
                    }
                    this.saveToStorage();
                });
            }
        });
    }

    pinCard(cardId) {
        this.pinnedCards.add(cardId);
        const card = document.querySelector(`[data-card="${cardId}"]`);
        if (card) {
            card.classList.add('pinned');
            card.querySelector('.pin-btn')?.classList.add('active');
        }
    }

    unpinCard(cardId) {
        this.pinnedCards.delete(cardId);
        const card = document.querySelector(`[data-card="${cardId}"]`);
        if (card) {
            card.classList.remove('pinned');
            card.querySelector('.pin-btn')?.classList.remove('active');
        }
    }

    // Advanced Task Management
    setupAdvancedTaskManagement() {
        this.loadTaskData();
        this.setupTaskFilters();
        this.setupTaskSorting();
        this.setupTaskSearch();
        this.setupBulkActions();
    }

    loadTaskData() {
        // Load tasks from server or local storage
        this.taskData = JSON.parse(localStorage.getItem('dashboard-tasks') || '[]');
        this.renderTaskList();
    }

    renderTaskList(container) {
        const taskContainer = container || document.getElementById('taskList');
        if (!taskContainer) return;

        const filteredTasks = this.filterTasks(this.taskData);

        taskContainer.innerHTML = filteredTasks.map(task => `
            <div class="task-item ${task.completed ? 'completed' : ''}" data-task-id="${task.id}">
                <input type="checkbox" ${task.completed ? 'checked' : ''} onchange="dashboardManager.toggleTask(${task.id})">
                <div class="task-content">
                    <div class="task-title">${this.escapeHtml(task.title)}</div>
                    <div class="task-meta">
                        <span class="task-priority priority-${task.priority}">${task.priority}</span>
                        <span class="task-due">${task.dueDate}</span>
                        <span class="task-assigned">${task.assignedTo}</span>
                    </div>
                </div>
                <div class="task-actions">
                    <button onclick="dashboardManager.editTask(${task.id})" class="btn-icon">
                        <i class="fas fa-edit"></i>
                    </button>
                    <button onclick="dashboardManager.deleteTask(${task.id})" class="btn-icon">
                        <i class="fas fa-trash"></i>
                    </button>
                </div>
            </div>
        `).join('');
    }

    filterTasks(tasks) {
        return tasks.filter(task => {
            const matchesSearch = !this.searchTerm || task.title.toLowerCase().includes(this.searchTerm);
            const matchesFilter = this.filterValue === 'all' || task.priority === this.filterValue;
            return matchesSearch && matchesFilter;
        });
    }

    setupTaskFilters() {
        // Similar to main filtering but for tasks
    }

    setupTaskSorting() {
        // Similar to main sorting but for tasks
    }

    setupTaskSearch() {
        // Similar to main search but for tasks
    }

    setupBulkActions() {
        const bulkActions = document.getElementById('bulkActions');
        if (bulkActions) {
            bulkActions.addEventListener('click', (e) => {
                const action = e.target.getAttribute('data-action');
                const selectedTasks = this.getSelectedTasks();

                switch (action) {
                    case 'complete':
                        selectedTasks.forEach(id => this.completeTask(id));
                        break;
                    case 'delete':
                        selectedTasks.forEach(id => this.deleteTask(id));
                        break;
                    case 'priority':
                        selectedTasks.forEach(id => this.setTaskPriority(id, 'high'));
                        break;
                }
            });
        }
    }

    getSelectedTasks() {
        return Array.from(document.querySelectorAll('.task-item input:checked'))
            .map(checkbox => parseInt(checkbox.closest('.task-item').getAttribute('data-task-id')));
    }

    toggleTask(taskId) {
        const task = this.taskData.find(t => t.id === taskId);
        if (task) {
            task.completed = !task.completed;
            this.saveTaskData();
            this.renderTaskList();
        }
    }

    completeTask(taskId) {
        const task = this.taskData.find(t => t.id === taskId);
        if (task) {
            task.completed = true;
            this.saveTaskData();
            this.renderTaskList();
        }
    }

    deleteTask(taskId) {
        this.taskData = this.taskData.filter(t => t.id !== taskId);
        this.saveTaskData();
        this.renderTaskList();
    }

    editTask(taskId) {
        const task = this.taskData.find(t => t.id === taskId);
        if (task) {
            // Open edit modal or inline edit
            this.showTaskEditForm(task);
        }
    }

    showTaskEditForm(task) {
        // Implementation for task editing
    }

    saveTaskData() {
        localStorage.setItem('dashboard-tasks', JSON.stringify(this.taskData));
    }

    // Enhanced Charts
    setupEnhancedCharts() {
        this.createChart('dashboardChart', 'bar');
        this.setupChartInteractions();
        this.setupChartThemes();
    }

    createChart(canvasId, type) {
        const canvas = document.getElementById(canvasId);
        if (!canvas) return;

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

        // Sample data - in real app, this would come from server
        const data = {
            labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'],
            datasets: [{
                label: 'Revenue',
                data: [12000, 19000, 15000, 25000, 22000, 30000],
                backgroundColor: 'rgba(54, 162, 235, 0.5)',
                borderColor: 'rgba(54, 162, 235, 1)',
                borderWidth: 1
            }]
        };

        const config = {
            type: type,
            data: data,
            options: {
                responsive: true,
                plugins: {
                    legend: {
                        position: 'top',
                    },
                    title: {
                        display: true,
                        text: 'Monthly Revenue'
                    }
                }
            }
        };

        this.chartInstances.set(canvasId, new Chart(ctx, config));
    }

    setupChartInteractions() {
        // Add click handlers, tooltips, etc.
    }

    setupChartThemes() {
        // Apply theme colors to charts
    }

    // ===== PHASE 2: THEME & ACCESSIBILITY =====

    loadTheme() {
        const savedTheme = localStorage.getItem('dashboard-theme') || 'light';
        this.setTheme(savedTheme);
    }

    setTheme(theme) {
        this.currentTheme = theme;
        document.body.setAttribute('data-theme', theme);
        this.saveToStorage();
    }

    toggleTheme() {
        const newTheme = this.currentTheme === 'light' ? 'dark' : 'light';
        this.setTheme(newTheme);
    }

    setupEventListeners() {
        // Theme toggle
        const themeToggle = document.getElementById('themeToggle');
        if (themeToggle) {
            themeToggle.addEventListener('click', () => this.toggleTheme());
        }

        // Refresh button
        const refreshBtn = document.getElementById('refreshBtn');
        if (refreshBtn) {
            refreshBtn.addEventListener('click', () => this.refreshData());
        }

        // Keyboard shortcuts
        document.addEventListener('keydown', (e) => {
            if (e.ctrlKey || e.metaKey) {
                switch (e.key) {
                    case 'r':
                        e.preventDefault();
                        this.refreshData();
                        break;
                    case 't':
                        e.preventDefault();
                        this.toggleTheme();
                        break;
                    case 'f':
                        e.preventDefault();
                        document.getElementById('dashboardSearch')?.focus();
                        break;
                }
            }
        });
    }

    initializeCards() {
        this.cards = Array.from(document.querySelectorAll('.dashboard-card'));
        this.cards.forEach(card => {
            const cardId = card.getAttribute('data-card');
            if (this.pinnedCards.has(cardId)) {
                card.classList.add('pinned');
            }
        });
    }

    setupAccessibility() {
        // Add ARIA labels, keyboard navigation, screen reader support
        this.setupKeyboardNavigation();
        this.setupScreenReaderSupport();
        this.setupFocusManagement();
    }

    setupKeyboardNavigation() {
        this.cards.forEach(card => {
            card.setAttribute('tabindex', '0');

            card.addEventListener('keydown', (e) => {
                switch (e.key) {
                    case 'Enter':
                    case ' ':
                        e.preventDefault();
                        card.click();
                        break;
                    case 'ArrowRight':
                        e.preventDefault();
                        this.focusNextCard(card);
                        break;
                    case 'ArrowLeft':
                        e.preventDefault();
                        this.focusPreviousCard(card);
                        break;
                }
            });
        });
    }

    focusNextCard(currentCard) {
        const currentIndex = this.cards.indexOf(currentCard);
        const nextIndex = (currentIndex + 1) % this.cards.length;
        this.cards[nextIndex].focus();
    }

    focusPreviousCard(currentCard) {
        const currentIndex = this.cards.indexOf(currentCard);
        const prevIndex = currentIndex === 0 ? this.cards.length - 1 : currentIndex - 1;
        this.cards[prevIndex].focus();
    }

    setupScreenReaderSupport() {
        // Add live regions, ARIA labels, etc.
        this.announceToScreenReader('Dashboard loaded successfully');
    }

    setupFocusManagement() {
        // Manage focus for modals, dropdowns, etc.
    }

    startRefreshSimulation() {
        // Simulate periodic data refresh
        this.refreshInterval = setInterval(() => {
            if (!this.isRefreshing) {
                this.refreshData();
            }
        }, 30000); // Refresh every 30 seconds
    }

    async refreshData() {
        if (this.isRefreshing) return;

        this.isRefreshing = true;
        this.showLoadingState();

        try {
            // Simulate API call
            await new Promise(resolve => setTimeout(resolve, 1000));

            // Update data
            this.updateCardData();
            this.updateCharts();

            this.announceToScreenReader('Dashboard data refreshed');
        } catch (error) {
            console.error('Refresh failed:', error);
            this.announceToScreenReader('Failed to refresh dashboard data');
        } finally {
            this.isRefreshing = false;
            this.hideLoadingState();
        }
    }

    showLoadingState() {
        this.cards.forEach(card => {
            card.classList.add('refreshing');
        });
    }

    hideLoadingState() {
        this.cards.forEach(card => {
            card.classList.remove('refreshing');
        });
    }

    updateCardData() {
        // Update card contents with new data
        this.cards.forEach(card => {
            const lastUpdated = card.querySelector('.last-updated');
            if (lastUpdated) {
                lastUpdated.textContent = new Date().toLocaleTimeString();
            }
        });
    }

    updateCharts() {
        // Update chart data
        this.chartInstances.forEach(chart => {
            // Simulate data update
            chart.data.datasets[0].data = chart.data.datasets[0].data.map(() =>
                Math.floor(Math.random() * 30000) + 10000
            );
            chart.update();
        });
    }

    loadFromStorage() {
        const savedData = JSON.parse(localStorage.getItem('dashboard-settings') || '{}');

        if (savedData.theme) {
            this.setTheme(savedData.theme);
        }

        if (savedData.pinnedCards) {
            savedData.pinnedCards.forEach(cardId => this.pinCard(cardId));
        }

        if (savedData.cardSizes) {
            this.cardSizes = new Map(Object.entries(savedData.cardSizes));
            this.applyCardSizes();
        }

        if (savedData.filters) {
            this.searchTerm = savedData.filters.search || '';
            this.filterValue = savedData.filters.filter || 'all';
            this.sortValue = savedData.filters.sort || 'default';
            this.applyFilters();
            this.applySorting();
            this.applySearch();
        }
    }

    saveToStorage() {
        const data = {
            theme: this.currentTheme,
            pinnedCards: Array.from(this.pinnedCards),
            cardSizes: Object.fromEntries(this.cardSizes),
            filters: {
                search: this.searchTerm,
                filter: this.filterValue,
                sort: this.sortValue
            }
        };

        localStorage.setItem('dashboard-settings', JSON.stringify(data));
    }

    applyCardSizes() {
        this.cardSizes.forEach((size, cardId) => {
            const card = document.querySelector(`[data-card="${cardId}"]`);
            if (card) {
                card.style.height = size + 'px';
            }
        });
    }

    loadAnalyticsData() {
        // Load analytics data from server or generate mock data
        this.analyticsData = {
            pageViews: 1250,
            uniqueVisitors: 890,
            avgSessionTime: '4:32',
            bounceRate: '23%',
            topPages: [
                { page: '/dashboard', views: 450 },
                { page: '/cases', views: 320 },
                { page: '/clients', views: 280 }
            ]
        };
    }

    renderAnalyticsWidgets(container) {
        const analyticsContainer = container || document.getElementById('analyticsContainer');
        if (!analyticsContainer) return;

        analyticsContainer.innerHTML = `
            <div class="analytics-widget">
                <h4>Page Views</h4>
                <div class="metric">${this.analyticsData.pageViews}</div>
                <div class="trend positive">+12%</div>
            </div>
            <div class="analytics-widget">
                <h4>Unique Visitors</h4>
                <div class="metric">${this.analyticsData.uniqueVisitors}</div>
                <div class="trend positive">+8%</div>
            </div>
            <div class="analytics-widget">
                <h4>Avg Session Time</h4>
                <div class="metric">${this.analyticsData.avgSessionTime}</div>
                <div class="trend neutral">0%</div>
            </div>
            <div class="analytics-widget">
                <h4>Bounce Rate</h4>
                <div class="metric">${this.analyticsData.bounceRate}</div>
                <div class="trend negative">+2%</div>
            </div>
        `;
    }

    // Utility Methods
    showNotification(message, type = 'info') {
        const notification = document.createElement('div');
        notification.className = `notification notification-${type}`;
        notification.innerHTML = `
            <div class="notification-content">
                <i class="fas ${this.getNotificationIcon(type)}"></i>
                <span>${message}</span>
            </div>
            <button class="notification-close" onclick="this.parentElement.remove()">
                <i class="fas fa-times"></i>
            </button>
        `;

        document.body.appendChild(notification);

        setTimeout(() => {
            if (notification.parentElement) {
                notification.remove();
            }
        }, 5000);
    }

    getNotificationIcon(type) {
        const icons = {
            success: 'fa-check-circle',
            error: 'fa-exclamation-circle',
            warning: 'fa-exclamation-triangle',
            info: 'fa-info-circle'
        };
        return icons[type] || 'fa-info-circle';
    }

    announceToScreenReader(message) {
        const announcement = document.createElement('div');
        announcement.setAttribute('aria-live', 'polite');
        announcement.setAttribute('aria-atomic', 'true');
        announcement.className = 'sr-only';
        announcement.textContent = message;

        document.body.appendChild(announcement);

        setTimeout(() => {
            document.body.removeChild(announcement);
        }, 1000);
    }

    escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }

    destroy() {
        if (this.refreshInterval) {
            clearInterval(this.refreshInterval);
        }

        this.chartInstances.forEach(chart => {
            if (chart && typeof chart.destroy === 'function') {
                chart.destroy();
            }
        });

        this.intersectionObserver?.disconnect();

        // Clean up event listeners
        this.cleanupEventListeners();
    }
}

// Initialize dashboard when DOM is ready
document.addEventListener('DOMContentLoaded', () => {
    window.dashboardManager = new DashboardManager();
});

// Export for module usage
if (typeof module !== 'undefined' && module.exports) {
    module.exports = DashboardManager;
}
