/**
 * Sentinel Dashboard JavaScript
 * 
 * Handles dashboard charts and interactive elements.
 */

document.addEventListener('DOMContentLoaded', function() {
    // Check if Chart.js is loaded
    if (typeof Chart === 'undefined') {
        console.error('Chart.js is not loaded!');
        return;
    }
    
    // Check if data is available
    if (!window.sentinelDashboardData) {
        console.error('Dashboard data not available');
        return;
    }
    
    console.log('Dashboard data loaded:', window.sentinelDashboardData);
    
    // Initialize all charts
    initializeCharts();
    
    function initializeCharts() {
        // Activity Timeline Chart
        const activityCanvas = document.getElementById('activityChart');
        if (activityCanvas) {
            const activityData = window.sentinelDashboardData.activityData;
            if (activityData && activityData.length > 0) {
                const chart = new Chart(activityCanvas.getContext('2d'), {
                    type: 'line',
                    data: {
                        labels: activityData.map(item => item.date),
                        datasets: [{
                            label: 'Activity Count',
                            data: activityData.map(item => item.count),
                            borderColor: '#0073aa',
                            backgroundColor: 'rgba(0, 115, 170, 0.1)',
                            tension: 0.4,
                            fill: true,
                            pointBackgroundColor: '#0073aa',
                            pointBorderColor: '#fff',
                            pointBorderWidth: 2,
                            pointRadius: 4,
                            pointHoverRadius: 6
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        plugins: {
                            legend: {
                                display: false
                            },
                            tooltip: {
                                backgroundColor: 'rgba(0, 0, 0, 0.8)',
                                titleColor: '#fff',
                                bodyColor: '#fff',
                                borderColor: '#0073aa',
                                borderWidth: 1,
                                cornerRadius: 6,
                                displayColors: false
                            }
                        },
                        scales: {
                            y: {
                                beginAtZero: true,
                                ticks: {
                                    stepSize: 1,
                                    color: '#666',
                                    font: {
                                        size: 11
                                    }
                                },
                                grid: {
                                    color: 'rgba(0, 0, 0, 0.1)',
                                    drawBorder: false
                                }
                            },
                            x: {
                                ticks: {
                                    color: '#666',
                                    font: {
                                        size: 11
                                    }
                                },
                                grid: {
                                    display: false
                                }
                            }
                        },
                        interaction: {
                            intersect: false,
                            mode: 'index'
                        }
                    }
                });
            }
        }

        // Event Distribution Chart
        const eventCanvas = document.getElementById('eventChart');
        if (eventCanvas) {
            const eventData = window.sentinelDashboardData.eventData;
            if (eventData && eventData.length > 0) {
                const chart = new Chart(eventCanvas.getContext('2d'), {
                    type: 'doughnut',
                    data: {
                        labels: eventData.map(item => item.event_key),
                        datasets: [{
                            data: eventData.map(item => item.count),
                            backgroundColor: [
                                '#0073aa', '#00a32a', '#d63638', '#f56e28', '#8c8f94',
                                '#72aee6', '#00ba9c', '#dba617', '#385df6', '#e65054'
                            ],
                            borderWidth: 2,
                            borderColor: '#fff',
                            hoverBorderWidth: 3,
                            hoverBorderColor: '#fff'
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        plugins: {
                            legend: {
                                position: 'bottom',
                                labels: {
                                    boxWidth: 10,
                                    padding: 8,
                                    usePointStyle: true,
                                    pointStyle: 'circle',
                                    color: '#666',
                                    font: {
                                        size: 11
                                    }
                                }
                            },
                            tooltip: {
                                backgroundColor: 'rgba(0, 0, 0, 0.8)',
                                titleColor: '#fff',
                                bodyColor: '#fff',
                                borderColor: '#0073aa',
                                borderWidth: 1,
                                cornerRadius: 6,
                                callbacks: {
                                    label: function(context) {
                                        const label = context.label || '';
                                        const value = context.raw;
                                        const total = context.dataset.data.reduce((a, b) => a + b, 0);
                                        const percentage = total > 0 ? ((value / total) * 100).toFixed(1) : 0;
                                        return `${label}: ${value} (${percentage}%)`;
                                    }
                                }
                            }
                        },
                        cutout: '60%'
                    }
                });
            }
        }

        // Recent Errors Chart
        const errorCanvas = document.getElementById('errorChart');
        if (errorCanvas) {
            const errorData = window.sentinelDashboardData.errorData;
            if (errorData && errorData.length > 0) {
                const chart = new Chart(errorCanvas.getContext('2d'), {
                    type: 'pie',
                    data: {
                        labels: errorData.map(item => item.event_key),
                        datasets: [{
                            data: errorData.map(item => item.count),
                            backgroundColor: [
                                '#d63638', '#f56e28', '#8c8f94', '#385df6', '#e65054',
                                '#0073aa', '#00a32a', '#dba617', '#00ba9c', '#72aee6'
                            ],
                            borderWidth: 2,
                            borderColor: '#fff',
                            hoverBorderWidth: 3,
                            hoverBorderColor: '#fff'
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        plugins: {
                            legend: {
                                position: 'bottom',
                                labels: {
                                    boxWidth: 10,
                                    padding: 8,
                                    usePointStyle: true,
                                    pointStyle: 'circle',
                                    color: '#666',
                                    font: {
                                        size: 11
                                    }
                                }
                            },
                            tooltip: {
                                backgroundColor: 'rgba(0, 0, 0, 0.8)',
                                titleColor: '#fff',
                                bodyColor: '#fff',
                                borderColor: '#d63638',
                                borderWidth: 1,
                                cornerRadius: 6,
                                callbacks: {
                                    label: function(context) {
                                        const label = context.label || '';
                                        const value = context.raw;
                                        const total = context.dataset.data.reduce((a, b) => a + b, 0);
                                        const percentage = total > 0 ? ((value / total) * 100).toFixed(1) : 0;
                                        return `${label}: ${value} (${percentage}%)`;
                                    }
                                }
                            }
                        }
                    }
                });
            }
        }

        // Custom Hourly Activity Heatmap
        const matrixCanvas = document.getElementById('activityHeatmap');
        if (matrixCanvas) {
            const heatmapData = window.sentinelDashboardData.heatmapData;
            if (heatmapData && heatmapData.length > 0) {
                console.log('Creating custom heatmap with data:', heatmapData);
                
                // Get the chart container (parent of canvas)
                const container = matrixCanvas.parentElement;
                
                // Preserve the title
                const title = container.querySelector('h3');
                
                // Clear container but preserve title
                container.innerHTML = '';
                if (title) {
                    container.appendChild(title);
                }
                
                // Create heatmap container
                const heatmapDiv = document.createElement('div');
                heatmapDiv.className = 'sentinel-heatmap';
                
                // Add hour labels (top row)
                const emptyCorner = document.createElement('div');
                emptyCorner.className = 'sentinel-heatmap-label';
                heatmapDiv.appendChild(emptyCorner);
                
                for (let hour = 0; hour < 24; hour++) {
                    const hourLabel = document.createElement('div');
                    hourLabel.className = 'sentinel-heatmap-label';
                    hourLabel.textContent = hour % 4 === 0 ? hour + 'h' : '';
                    heatmapDiv.appendChild(hourLabel);
                }
                
                // Add day rows
                heatmapData.forEach((dayData, dayIndex) => {
                    // Day label
                    const dayLabel = document.createElement('div');
                    dayLabel.className = 'sentinel-heatmap-label';
                    dayLabel.textContent = dayData.date.substring(5); // MM-DD format
                    heatmapDiv.appendChild(dayLabel);
                    
                    // Hour cells
                    dayData.hours.forEach((count, hour) => {
                        const cell = document.createElement('div');
                        cell.className = 'sentinel-heatmap-cell';
                        cell.style.backgroundColor = getHeatmapColor(count);
                        
                        // Add hover effect and tooltip
                        cell.addEventListener('mouseenter', function() {
                            // Clear any existing tooltips first
                            const existingTooltips = heatmapDiv.querySelectorAll('.sentinel-heatmap-tooltip');
                            existingTooltips.forEach(tooltip => {
                                tooltip.remove();
                            });
                            
                            // Create tooltip
                            const tooltip = document.createElement('div');
                            tooltip.className = 'sentinel-heatmap-tooltip';
                            tooltip.textContent = `${dayData.date} at ${hour.toString().padStart(2, '0')}:00 - ${count} events`;
                            this.appendChild(tooltip);
                            
                            // Trigger fade-in animation
                            setTimeout(() => {
                                if (tooltip.parentNode) {
                                    tooltip.classList.add('show');
                                }
                            }, 10);
                        });
                        
                        cell.addEventListener('mouseleave', function() {
                            // Remove tooltip with fade-out
                            const tooltip = this.querySelector('.sentinel-heatmap-tooltip');
                            if (tooltip) {
                                tooltip.classList.remove('show');
                                setTimeout(() => {
                                    if (tooltip && tooltip.parentNode) {
                                        tooltip.remove();
                                    }
                                }, 300); // Match CSS transition duration
                            }
                        });
                        
                        heatmapDiv.appendChild(cell);
                    });
                });
                
                container.appendChild(heatmapDiv);
                
                // Add global cleanup for any stray tooltips
                heatmapDiv.addEventListener('mouseleave', function() {
                    // Clean up any remaining tooltips when mouse leaves the heatmap
                    setTimeout(() => {
                        const strayTooltips = heatmapDiv.querySelectorAll('.sentinel-heatmap-tooltip');
                        strayTooltips.forEach(tooltip => {
                            tooltip.remove();
                        });
                    }, 50);
                });
                
                // GitHub-style color function
                function getHeatmapColor(value) {
                    if (value === 0) return '#ebedf0';
                    if (value <= 2) return '#9be9a8';
                    if (value <= 5) return '#40c463';
                    if (value <= 10) return '#30a14e';
                    return '#216e39';
                }
                
                console.log('Custom heatmap created successfully');
            } else {
                console.log('No heatmap data available');
            }
        }
    }

    // Activity feed interactions
    const activityItems = document.querySelectorAll('.sentinel-activity-item');
    activityItems.forEach(item => {
        item.addEventListener('click', function() {
            // Add subtle hover effect
            this.style.backgroundColor = '#f8f9fa';
            setTimeout(() => {
                this.style.backgroundColor = '';
            }, 200);
        });
    });

    // Chart container hover effects
    const chartContainers = document.querySelectorAll('.sentinel-chart-container');
    chartContainers.forEach(container => {
        container.addEventListener('mouseenter', function() {
            this.style.transform = 'translateY(-2px)';
            this.style.boxShadow = '0 4px 16px rgba(0,0,0,0.10)';
        });
        
        container.addEventListener('mouseleave', function() {
            this.style.transform = 'translateY(0)';
            this.style.boxShadow = '0 2px 8px rgba(0,0,0,0.06)';
        });
    });
}); 