/**
 * NexusBoard Dashboard Template - JavaScript
 * Analytics dashboard functionality
 */

(function() {
    'use strict';

    // ============================================
    // INITIALIZATION
    // ============================================

    document.addEventListener('DOMContentLoaded', function() {
        initYearUpdate();
        initKPICards();
        initCharts();
        initSmartTable();
        initNotifications();
        initTaskCheckboxes();
        initSearchPanel();
        initUserMenu();
    });

    // ============================================
    // YEAR UPDATE
    // ============================================

    function initYearUpdate() {
        var yearElements = document.querySelectorAll('.current-year');
        var currentYear = new Date().getFullYear();

        yearElements.forEach(function(el) {
            el.textContent = currentYear;
        });
    }

    // ============================================
    // KPI CARDS - Initialize with RSL component
    // ============================================

    function initKPICards() {
        // RSL.KPICards.init() handles initialization
        // This function sets up any custom data if needed

        if (window.RSL && window.RSL.KPICards) {
            window.RSL.KPICards.init();
        }
    }

    // ============================================
    // CHARTS - Initialize with RSL Charts
    // ============================================

    function initCharts() {
        if (window.RSL && window.RSL.Charts) {
            window.RSL.Charts.init();
        }
    }

    // ============================================
    // SMART TABLE - Initialize and handle actions
    // ============================================

    function initSmartTable() {
        if (window.RSL && window.RSL.SmartTable) {
            window.RSL.SmartTable.init();
        }

        // Add action button handlers
        var actionButtons = document.querySelectorAll('.nexus-action-btn');
        actionButtons.forEach(function(btn) {
            btn.addEventListener('click', function(e) {
                e.stopPropagation();
                var action = this.getAttribute('title');
                var row = this.closest('tr');
                var projectName = row ? row.querySelector('td:first-child').textContent.trim() : '';

                if (action === 'View Details') {
                    showProjectDetails(projectName);
                } else if (action === 'Edit Project') {
                    editProject(projectName);
                }
            });
        });
    }

    function showProjectDetails(projectName) {
        if (window.RSL && window.RSL.Toast) {
            window.RSL.Toast.show({
                header: 'Project Details',
                body: 'Viewing details for: ' + projectName,
                position: 'top-right',
                autoClose: 3000
            });
        }
    }

    function editProject(projectName) {
        if (window.RSL && window.RSL.Toast) {
            window.RSL.Toast.show({
                header: 'Edit Project',
                body: 'Opening editor for: ' + projectName,
                position: 'top-right',
                autoClose: 3000
            });
        }
    }

    // ============================================
    // NOTIFICATIONS PANEL
    // ============================================

    function initNotifications() {
        var notificationItems = document.querySelectorAll('.nexus-notification-item');

        notificationItems.forEach(function(item) {
            item.addEventListener('click', function() {
                // Mark as read
                this.classList.remove('unread');

                // Update notification count
                updateNotificationCount();
            });
        });

        // Mark all as read button
        var markAllBtn = document.querySelector('.nexus-mark-all-read');
        if (markAllBtn) {
            markAllBtn.addEventListener('click', function() {
                notificationItems.forEach(function(item) {
                    item.classList.remove('unread');
                });
                updateNotificationCount();
            });
        }
    }

    function updateNotificationCount() {
        var unreadCount = document.querySelectorAll('.nexus-notification-item.unread').length;
        var badge = document.querySelector('.nexus-notification-badge');

        if (badge) {
            if (unreadCount > 0) {
                badge.textContent = unreadCount;
                badge.style.display = 'flex';
            } else {
                badge.style.display = 'none';
            }
        }
    }

    // ============================================
    // TASK CHECKBOXES
    // ============================================

    function initTaskCheckboxes() {
        var taskCheckboxes = document.querySelectorAll('.nexus-task-checkbox');

        taskCheckboxes.forEach(function(checkbox) {
            checkbox.addEventListener('change', function() {
                var taskItem = this.closest('.nexus-task-item');
                var taskText = taskItem ? taskItem.querySelector('.nexus-task-text') : null;

                if (this.checked) {
                    if (taskText) {
                        taskText.style.textDecoration = 'line-through';
                        taskText.style.opacity = '0.6';
                    }

                    if (window.RSL && window.RSL.Toast) {
                        window.RSL.Toast.show({
                            header: 'Task Completed',
                            body: 'Great job! Task marked as complete.',
                            position: 'bottom-right',
                            autoClose: 2000
                        });
                    }
                } else {
                    if (taskText) {
                        taskText.style.textDecoration = 'none';
                        taskText.style.opacity = '1';
                    }
                }

                // Update tasks progress
                updateTasksProgress();
            });
        });
    }

    function updateTasksProgress() {
        var total = document.querySelectorAll('.nexus-task-checkbox').length;
        var completed = document.querySelectorAll('.nexus-task-checkbox:checked').length;
        var percentage = total > 0 ? Math.round((completed / total) * 100) : 0;

        var progressText = document.querySelector('.nexus-tasks-progress');
        if (progressText) {
            progressText.textContent = completed + ' of ' + total + ' completed (' + percentage + '%)';
        }
    }

    // ============================================
    // SEARCH PANEL
    // ============================================

    function initSearchPanel() {
        var searchInput = document.querySelector('.nexus-search-input');
        var searchResults = document.querySelector('.nexus-search-results');

        if (searchInput && searchResults) {
            searchInput.addEventListener('input', function() {
                var query = this.value.trim().toLowerCase();

                if (query.length >= 2) {
                    performSearch(query, searchResults);
                } else {
                    searchResults.innerHTML = '<p class="nexus-search-hint">Type at least 2 characters to search...</p>';
                }
            });

            // Focus search input when panel opens
            var searchPanel = document.getElementById('search-panel');
            if (searchPanel) {
                var observer = new MutationObserver(function(mutations) {
                    mutations.forEach(function(mutation) {
                        if (mutation.attributeName === 'class' && searchPanel.classList.contains('open')) {
                            setTimeout(function() {
                                searchInput.focus();
                            }, 300);
                        }
                    });
                });

                observer.observe(searchPanel, { attributes: true });
            }
        }
    }

    function performSearch(query, resultsContainer) {
        // Demo search results
        var demoResults = [
            { type: 'Project', title: 'Website Redesign', icon: 'fas fa-project-diagram' },
            { type: 'Project', title: 'Mobile App Development', icon: 'fas fa-mobile-alt' },
            { type: 'Task', title: 'Review design mockups', icon: 'fas fa-tasks' },
            { type: 'User', title: 'Sarah Johnson', icon: 'fas fa-user' },
            { type: 'Report', title: 'Q4 Analytics Report', icon: 'fas fa-chart-bar' }
        ];

        var filtered = demoResults.filter(function(result) {
            return result.title.toLowerCase().includes(query) ||
                   result.type.toLowerCase().includes(query);
        });

        if (filtered.length > 0) {
            var html = filtered.map(function(result) {
                return '<div class="nexus-search-result-item">' +
                    '<i class="' + result.icon + '"></i>' +
                    '<div class="nexus-search-result-content">' +
                        '<span class="nexus-search-result-type">' + result.type + '</span>' +
                        '<span class="nexus-search-result-title">' + result.title + '</span>' +
                    '</div>' +
                '</div>';
            }).join('');

            resultsContainer.innerHTML = html;

            // Add click handlers
            resultsContainer.querySelectorAll('.nexus-search-result-item').forEach(function(item) {
                item.addEventListener('click', function() {
                    var title = this.querySelector('.nexus-search-result-title').textContent;
                    if (window.RSL && window.RSL.Toast) {
                        window.RSL.Toast.show({
                            header: 'Search Result',
                            body: 'Selected: ' + title,
                            position: 'top-right',
                            autoClose: 2000
                        });
                    }
                    // Close search panel
                    if (window.RSL && window.RSL.OffCanvas) {
                        window.RSL.OffCanvas.close('search-panel');
                    }
                });
            });
        } else {
            resultsContainer.innerHTML = '<p class="nexus-no-results">No results found for "' + query + '"</p>';
        }
    }

    // ============================================
    // USER MENU
    // ============================================

    function initUserMenu() {
        var menuLinks = document.querySelectorAll('.nexus-user-menu-link');

        menuLinks.forEach(function(link) {
            link.addEventListener('click', function(e) {
                e.preventDefault();
                var action = this.textContent.trim();

                if (window.RSL && window.RSL.Toast) {
                    window.RSL.Toast.show({
                        header: 'Navigation',
                        body: 'Navigating to: ' + action,
                        position: 'top-right',
                        autoClose: 2000
                    });
                }

                // Close user panel
                if (window.RSL && window.RSL.OffCanvas) {
                    window.RSL.OffCanvas.close('user-panel');
                }
            });
        });
    }

    // ============================================
    // QUICK ACTIONS
    // ============================================

    window.NexusBoard = {
        // Refresh dashboard data
        refresh: function() {
            if (window.RSL && window.RSL.Toast) {
                window.RSL.Toast.show({
                    header: 'Refreshing...',
                    body: 'Dashboard data is being updated',
                    position: 'top-right',
                    autoClose: 2000
                });
            }

            // Re-initialize components
            setTimeout(function() {
                initKPICards();
                initCharts();
                initSmartTable();

                if (window.RSL && window.RSL.Toast) {
                    window.RSL.Toast.show({
                        header: 'Success',
                        body: 'Dashboard refreshed successfully',
                        position: 'top-right',
                        autoClose: 2000
                    });
                }
            }, 1000);
        },

        // Export report (demo)
        exportReport: function() {
            if (window.RSL && window.RSL.Toast) {
                window.RSL.Toast.show({
                    header: 'Export Started',
                    body: 'Generating PDF report...',
                    position: 'top-right',
                    autoClose: 3000
                });
            }
        },

        // Open settings (demo)
        openSettings: function() {
            if (window.RSL && window.RSL.OffCanvas) {
                window.RSL.OffCanvas.open('user-panel');
            }
        }
    };

    // ============================================
    // KEYBOARD SHORTCUTS
    // ============================================

    document.addEventListener('keydown', function(e) {
        // Ctrl/Cmd + K for search
        if ((e.ctrlKey || e.metaKey) && e.key === 'k') {
            e.preventDefault();
            if (window.RSL && window.RSL.OffCanvas) {
                window.RSL.OffCanvas.open('search-panel');
            }
        }

        // Escape to close panels
        if (e.key === 'Escape') {
            if (window.RSL && window.RSL.OffCanvas) {
                window.RSL.OffCanvas.close('search-panel');
                window.RSL.OffCanvas.close('notifications-panel');
                window.RSL.OffCanvas.close('user-panel');
            }
        }
    });

})();
