/**
 * 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/legal-news/search'
    };

    // 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);
            }
        });
    }

    /**
     * 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);
            
            // Display mock results for demonstration
            displayMockResults(resultsContainer);
            announceToScreenReader('Displaying sample results');
        }
    }

    /**
     * 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 = 'empty') {
        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'
            }
        };

        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(article => `
            <article class="news-item" 
                     onclick="window.open('${escapeHtml(article.url)}', '_blank')"
                     role="button"
                     tabindex="0"
                     onkeydown="if(event.key==='Enter'||event.key===' ') window.open('${escapeHtml(article.url)}', '_blank')"
                     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('');
    }

    /**
     * Display mock results for demonstration
     */
    function displayMockResults(container) {
        const mockArticles = [
            {
                title: 'Supreme Court Rules on Corporate Liability Standards',
                source: 'Legal Times',
                publishedAt: 'January 15, 2026',
                category: 'Corporate Law',
                description: 'In a landmark decision, the Supreme Court has established new precedents for corporate liability in cases involving environmental violations and stakeholder responsibilities.',
                url: '#'
            },
            {
                title: 'New Data Privacy Regulations Take Effect Next Month',
                source: 'Law Journal',
                publishedAt: 'January 14, 2026',
                category: 'Privacy Law',
                description: 'Businesses must prepare for comprehensive data privacy requirements as new federal regulations come into force, imposing stricter compliance obligations across all industries.',
                url: '#'
            },
            {
                title: 'International Arbitration Trends in Commercial Disputes',
                source: 'Global Legal Review',
                publishedAt: 'January 13, 2026',
                category: 'Arbitration',
                description: 'Analysis of emerging trends in international commercial arbitration reveals shifting preferences toward hybrid resolution mechanisms and accelerated proceedings.',
                url: '#'
            }
        ];

        displaySearchResults(container, mockArticles);
    }

    /**
     * Initialize charts with server data
     */
    function initCharts(serverData) {
        const timeTrackingData = serverData.timeTrackingData;
        const financialData = serverData.financialData;

        DashboardCharts.init(timeTrackingData, financialData);
    }

    /**
     * Initialize keyboard navigation enhancements
     */
    function initKeyboardNavigation() {
        // Add keyboard support for clickable items
        document.addEventListener('keydown', (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(() => {
            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) {
                Object.keys(data.charts).forEach(chartName => {
                    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,
        searchNews,
        switchTaskTab,
        refreshData,
        exportToPDF
    };
})();

// Make searchNews globally accessible for inline onclick handlers (backward compatibility)
window.DashboardApp = DashboardApp;

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