/**
 * Dashboard Application
 * Main application logic for the Prolex Legal Dashboard
 */

const DashboardApp = (function() {
    'use strict';

    // Configuration
    const config = {
        newsSearchDelay: 500, // Debounce delay for search
        apiEndpoint: '/api/dashboard/search-news'
    };

    // State management
    const state = {
        activeTaskTab: 'daily',
        searchTimeout: null,
        lastSearchQuery: ''
    };

    /**
     * Initialize the dashboard application
     */
    function init(serverData = {}) {
        initTaskTabs();
        initTaskCheckboxes();
        initNewsSearch();
        initCharts(serverData);
        initKeyboardNavigation();
        announcePageLoad();
    }

    /**
     * Initialize task tab switching
     */
    function initTaskTabs() {
        const tabs = document.querySelectorAll('.task-tab');
        
        tabs.forEach(tab => {
            tab.addEventListener('click', handleTabClick);
            tab.addEventListener('keydown', handleTabKeydown);
        });
    }

    /**
     * Handle task tab clicks
     */
    function handleTabClick(event) {
        const tab = event.currentTarget;
        const tabName = tab.dataset.tab;
        
        switchTaskTab(tabName);
    }

    /**
     * Handle keyboard navigation for tabs
     */
    function handleTabKeydown(event) {
        const tab = event.currentTarget;
        const tabs = Array.from(document.querySelectorAll('.task-tab'));
        const currentIndex = tabs.indexOf(tab);

        let newIndex;

        switch(event.key) {
            case 'ArrowLeft':
                event.preventDefault();
                newIndex = currentIndex > 0 ? currentIndex - 1 : tabs.length - 1;
                tabs[newIndex].focus();
                tabs[newIndex].click();
                break;
            case 'ArrowRight':
                event.preventDefault();
                newIndex = currentIndex < tabs.length - 1 ? currentIndex + 1 : 0;
                tabs[newIndex].focus();
                tabs[newIndex].click();
                break;
            case 'Home':
                event.preventDefault();
                tabs[0].focus();
                tabs[0].click();
                break;
            case 'End':
                event.preventDefault();
                tabs[tabs.length - 1].focus();
                tabs[tabs.length - 1].click();
                break;
        }
    }

    /**
     * Switch between task tabs
     */
    function switchTaskTab(tabName) {
        const tabs = document.querySelectorAll('.task-tab');
        const panels = {
            daily: document.getElementById('daily-tasks'),
            overdue: document.getElementById('overdue-tasks')
        };

        // Update tabs
        tabs.forEach(tab => {
            const isActive = tab.dataset.tab === tabName;
            tab.classList.toggle('active', isActive);
            tab.setAttribute('aria-selected', isActive);
        });

        // Update panels
        Object.keys(panels).forEach(key => {
            const panel = panels[key];
            if (!panel) return;

            const isVisible = key === tabName;
            if (isVisible) {
                panel.removeAttribute('hidden');
                panel.style.display = 'block';
            } else {
                panel.setAttribute('hidden', '');
                panel.style.display = 'none';
            }
        });

        state.activeTaskTab = tabName;
    }

    /**
     * Initialize task checkbox functionality
     */
    function initTaskCheckboxes() {
        const checkboxes = document.querySelectorAll('.task-checkbox');
        
        checkboxes.forEach(checkbox => {
            checkbox.addEventListener('change', handleTaskCheckboxChange);
        });
    }

    /**
     * Handle task checkbox changes with animation
     */
    function handleTaskCheckboxChange(event) {
        const checkbox = event.target;
        const taskItem = checkbox.closest('.task-item');
        const taskTitle = taskItem.querySelector('.task-title');
        
        if (checkbox.checked) {
            taskItem.style.opacity = '0.5';
            taskTitle.style.textDecoration = 'line-through';
            
            // Announce completion to screen readers
            announceToScreenReader('Task marked as complete');
            
            // Optional: Send completion to server
            // markTaskComplete(checkbox.id);
        } else {
            taskItem.style.opacity = '1';
            taskTitle.style.textDecoration = 'none';
            
            announceToScreenReader('Task marked as incomplete');
        }
    }

    /**
     * Initialize news search functionality
     */
    function initNewsSearch() {
        const searchInput = document.getElementById('newsSearch');
        
        if (!searchInput) return;

        // Handle Enter key
        searchInput.addEventListener('keypress', (event) => {
            if (event.key === 'Enter') {
                event.preventDefault();
                searchNews();
            }
        });

        // Optional: Real-time search with debounce
        searchInput.addEventListener('input', (event) => {
            clearTimeout(state.searchTimeout);
            
            const query = event.target.value.trim();
            
            if (query.length >= 3) {
                state.searchTimeout = setTimeout(() => {
                    // searchNews(); // Uncomment for real-time search
                }, config.newsSearchDelay);
            }
        });
    }

    /**
     * Load default Zimbabwe legal news on page load
     */
    async function loadDefaultNews() {
        const resultsContainer = document.getElementById('newsResults');
        
        if (!resultsContainer) return;

        // Show loading state
        showLoadingState(resultsContainer);

        try {
            // Use the default Zimbabwe legal news query (empty q triggers default in controller)
            const response = await fetch(config.apiEndpoint + '?q=');
            
            if (!response.ok) {
                throw new Error('Search failed');
            }

            const data = await response.json();

            if (data.articles && data.articles.length > 0) {
                displaySearchResults(resultsContainer, data.articles);
                announceToScreenReader('Loaded ' + data.articles.length + ' legal news articles');
            } else {
                showEmptyState(resultsContainer, 'no-results');
            }
        } catch (error) {
            console.error('Default news load error:', error);
            showEmptyState(resultsContainer, 'error');
        }
    }

    /**
     * Search for legal news
     */
    async function searchNews() {
        const searchInput = document.getElementById('newsSearch');
        const resultsContainer = document.getElementById('newsResults');
        
        if (!searchInput || !resultsContainer) return;

        const query = searchInput.value.trim();

        if (!query) {
            showEmptyState(resultsContainer, 'empty');
            return;
        }

        // Prevent duplicate searches
        if (query === state.lastSearchQuery) return;
        state.lastSearchQuery = query;

        // Show loading state
        showLoadingState(resultsContainer);

        try {
            const response = await fetch(config.apiEndpoint + '?q=' + encodeURIComponent(query));
            
            if (!response.ok) {
                throw new Error('Search failed');
            }

            const data = await response.json();

            if (data.articles && data.articles.length > 0) {
                displaySearchResults(resultsContainer, data.articles);
                announceToScreenReader('Found ' + data.articles.length + ' results for ' + query);
            } else {
                showEmptyState(resultsContainer, 'no-results');
                announceToScreenReader('No results found for ' + query);
            }
        } catch (error) {
            console.error('News search error:', error);

            // Show error state instead of mock results
            showEmptyState(resultsContainer, 'error');
            announceToScreenReader('Failed to load news results. Please try again.');
        }
    }

    /**
     * Show loading state
     */
    function showLoadingState(container) {
        container.innerHTML = '<div class="loading-spinner" role="status" aria-live="polite"><div class="spinner" aria-hidden="true"></div><p style="margin-top: 16px; font-weight: 600;">Searching legal databases...</p><span class="sr-only">Loading search results</span></div>';
    }

    /**
     * Show empty state
     */
    function showEmptyState(container, type) {
        const messages = {
            empty: {
                icon: 'fa-search',
                title: 'Search for legal news and articles',
                subtitle: 'Enter keywords to find relevant legal updates, case law, and industry news'
            },
            'no-results': {
                icon: 'fa-search-minus',
                title: 'No results found',
                subtitle: 'Try different keywords or check your spelling'
            },
            'error': {
                icon: 'fa-exclamation-triangle',
                title: 'Unable to load news',
                subtitle: 'Please check your connection and try again'
            }
        };

        const message = messages[type] || messages.empty;

        container.innerHTML = '<div class="empty-state"><i class="fas ' + message.icon + '" aria-hidden="true"></i><p class="empty-state-title">' + message.title + '</p><p class="empty-state-subtitle">' + message.subtitle + '</p></div>';
    }

    /**
     * Display search results
     */
    function displaySearchResults(container, articles) {
        container.innerHTML = articles.map(function(article) {
            return '<article class="news-item" onclick="window.open(\'' + escapeHtml(article.url) + '\', \'_\blank\')" role="button" tabindex="0" aria-label="Open article: ' + escapeHtml(article.title) + '"><h3 class="news-item-title">' + escapeHtml(article.title) + '</h3><div class="news-item-meta"><span><i class="fas fa-newspaper" aria-hidden="true"></i> ' + escapeHtml(article.source) + '</span><span><i class="fas fa-calendar" aria-hidden="true"></i> ' + escapeHtml(article.publishedAt) + '</span>' + (article.category ? '<span><i class="fas fa-tag" aria-hidden="true"></i> ' + escapeHtml(article.category) + '</span>' : '') + '</div><p class="news-item-excerpt">' + escapeHtml(article.description || article.excerpt) + '</p></article>';
        }).join('');
    }

    /**
     * Initialize charts with server data
     */
    function initCharts(serverData) {
        // Check if DashboardCharts is available globally
        if (typeof window.DashboardCharts !== 'undefined') {
            window.DashboardCharts.init(serverData.charts || {});
        } else {
            console.warn('DashboardCharts not available');
        }
    }

    /**
     * Initialize keyboard navigation enhancements
     */
    function initKeyboardNavigation() {
        // Add keyboard support for clickable items
        document.addEventListener('keydown', function(event) {
            const target = event.target;
            
            // Handle Enter and Space for elements with onclick
            if ((event.key === 'Enter' || event.key === ' ') && 
                target.hasAttribute('onclick') && 
                !target.matches('button, a, input')) {
                event.preventDefault();
                target.click();
            }
        });
    }

    /**
     * Announce to screen readers
     */
    function announceToScreenReader(message) {
        const announcement = document.createElement('div');
        announcement.setAttribute('role', 'status');
        announcement.setAttribute('aria-live', 'polite');
        announcement.className = 'sr-only';
        announcement.textContent = message;
        
        document.body.appendChild(announcement);
        
        setTimeout(function() {
            document.body.removeChild(announcement);
        }, 1000);
    }

    /**
     * Announce page load to screen readers
     */
    function announcePageLoad() {
        announceToScreenReader('Dashboard loaded. Press Tab to navigate through sections.');
    }

    /**
     * Escape HTML to prevent XSS
     */
    function escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }

    /**
     * Refresh dashboard data
     */
    async function refreshData() {
        try {
            const response = await fetch('/api/dashboard/refresh');
            const data = await response.json();
            
            // Update charts
            if (data.charts && typeof window.DashboardCharts !== 'undefined') {
                Object.keys(data.charts).forEach(function(chartName) {
                    window.DashboardCharts.update(chartName, data.charts[chartName]);
                });
            }
            
            announceToScreenReader('Dashboard data refreshed');
        } catch (error) {
            console.error('Failed to refresh dashboard:', error);
            announceToScreenReader('Failed to refresh dashboard data');
        }
    }

    /**
     * Export dashboard as PDF
     */
    function exportToPDF() {
        window.print();
    }

    // Public API
    return {
        init: init,
        searchNews: searchNews,
        loadDefaultNews: loadDefaultNews,
        switchTaskTab: switchTaskTab,
        refreshData: refreshData,
        exportToPDF: exportToPDF
    };
})();

// Expose DashboardApp globally for blade template access
window.DashboardApp = DashboardApp;

// Auto-initialize when DOM is ready
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', function() {
        // Will be initialized from blade template with server data
    });
}
