<script>
// Helper function untuk generate labels 12 bulan terakhir
function generateMonthLabels() {
    const labels = [];
    const now = new Date();
    for (let i = 11; i >= 0; i--) {
        const date = new Date(now.getFullYear(), now.getMonth() - i, 1);
        labels.push(date.toLocaleDateString('id-ID', { month: 'short', year: 'numeric' }));
    }
    return labels;
}

// Global chart instances untuk akses dari mana saja
window.dashboardCharts = {
    salesPurchases: null,
    profit: null,
    initialized: false
};

// Function to initialize charts (can be called multiple times safely)
function initializeDashboardCharts() {
    // Check if Chart.js is available
    if (typeof Chart === 'undefined') {
        console.warn('Chart.js not loaded yet, retrying...');
        setTimeout(initializeDashboardCharts, 100);
        return;
    }
    
    // Check if charts already initialized
    if (window.dashboardCharts.initialized && window.dashboardCharts.salesPurchases && window.dashboardCharts.profit) {
        // Just resize if already initialized
        if (window.forceRerenderDashboardCharts) {
            window.forceRerenderDashboardCharts();
        }
        return;
    }
    
    // Check if elements exist
    const salesPurchasesCtx = document.getElementById('salesPurchasesChart');
    const profitCtx = document.getElementById('profitChart');
    
    if (!salesPurchasesCtx || !profitCtx) {
        console.warn('Chart elements not found yet, retrying...');
        setTimeout(initializeDashboardCharts, 100);
        return;
    }
    
    // Proceed with initialization
    initCharts();
}

// Theme-aware colors for dark mode support
function getThemeColors() {
    const isDark = document.documentElement.classList.contains('dark') || document.body.classList.contains('dark');
    return {
        isDark,
        text: isDark ? '#e5e7eb' : '#111827',
        grid: isDark ? 'rgba(255, 255, 255, 0.12)' : 'rgba(0, 0, 0, 0.05)',
        tooltipBg: isDark ? 'rgba(17, 24, 39, 0.9)' : 'rgba(0, 0, 0, 0.8)',
        tooltipBorder: isDark ? 'rgba(255, 255, 255, 0.15)' : 'rgba(255, 255, 255, 0.1)'
    };
}

// Function to apply theme to chart
function applyThemeToChart(chart) {
        if (!chart) return;
        
        // Update theme colors
        themeColors = getThemeColors();
        
        // Update scales
        if (chart.options.scales?.x) {
            chart.options.scales.x.grid.color = themeColors.grid;
            chart.options.scales.x.ticks.color = themeColors.text;
        }
        if (chart.options.scales?.y) {
            chart.options.scales.y.grid.color = themeColors.grid;
            chart.options.scales.y.ticks.color = themeColors.text;
        }
        
        // Update plugins
        chart.options.plugins = chart.options.plugins || {};
        chart.options.plugins.legend = chart.options.plugins.legend || {};
        chart.options.plugins.legend.labels = chart.options.plugins.legend.labels || {};
        chart.options.plugins.legend.labels.color = themeColors.text;
        
        chart.options.plugins.tooltip = chart.options.plugins.tooltip || {};
        chart.options.plugins.tooltip.backgroundColor = themeColors.tooltipBg;
        chart.options.plugins.tooltip.borderColor = themeColors.tooltipBorder;
        
        // Apply Chart.js global defaults
        Chart.defaults.color = themeColors.text;
        Chart.defaults.borderColor = themeColors.grid;
        
        // Force update
        chart.update('none'); // 'none' mode for instant update
}

// Function to resize charts
function resizeCharts() {
    const salesChart = window.dashboardCharts.salesPurchases;
    const profitChartInstance = window.dashboardCharts.profit;
    
    if (salesChart) {
        try {
            salesChart.resize();
        } catch (e) {
            console.error('Error resizing salesPurchasesChart:', e);
        }
    }
    if (profitChartInstance) {
        try {
            profitChartInstance.resize();
        } catch (e) {
            console.error('Error resizing profitChart:', e);
        }
    }
}

// Function to force re-render charts (for zoom issues)
function forceRerenderCharts() {
    const salesChart = window.dashboardCharts.salesPurchases;
    const profitChartInstance = window.dashboardCharts.profit;
        
        if (salesChart) {
            try {
                // Force canvas to recalculate size
                const canvas = salesChart.canvas;
                if (!canvas) return;
                
                const container = canvas.parentElement;
                if (container) {
                    // Get actual container dimensions
                    const containerWidth = container.offsetWidth;
                    const containerHeight = container.offsetHeight;
                    
                    if (containerWidth > 0 && containerHeight > 0) {
                        // Set canvas size explicitly
                        canvas.style.width = containerWidth + 'px';
                        canvas.style.height = containerHeight + 'px';
                    }
                }
                salesChart.resize();
                salesChart.update('none');
            } catch (e) {
                console.error('Error re-rendering salesPurchasesChart:', e);
            }
        }
        if (profitChartInstance) {
            try {
                // Force canvas to recalculate size
                const canvas = profitChartInstance.canvas;
                if (!canvas) return;
                
                const container = canvas.parentElement;
                if (container) {
                    // Get actual container dimensions
                    const containerWidth = container.offsetWidth;
                    const containerHeight = container.offsetHeight;
                    
                    if (containerWidth > 0 && containerHeight > 0) {
                        // Set canvas size explicitly
                        canvas.style.width = containerWidth + 'px';
                        canvas.style.height = containerHeight + 'px';
                    }
                }
                profitChartInstance.resize();
                profitChartInstance.update('none');
            } catch (e) {
                console.error('Error re-rendering profitChart:', e);
            }
        }
    }
    
// Make functions globally accessible
window.resizeDashboardCharts = resizeCharts;
window.forceRerenderDashboardCharts = forceRerenderCharts;

// Main initialization function
function initCharts() {
    // Check if Chart.js is available
    if (typeof Chart === 'undefined') {
        console.error('Chart.js is not loaded!');
        return;
    }

    let themeColors = getThemeColors();
    
    // Chart 1: Penjualan vs Pembelian
    try {
        const salesPurchasesCtx = document.getElementById('salesPurchasesChart');
        if (!salesPurchasesCtx) {
            console.error('salesPurchasesChart element not found');
            return;
        }
        
        // Ensure canvas is ready
        const salesPurchasesCanvas = salesPurchasesCtx;
        if (salesPurchasesCanvas.width === 0 || salesPurchasesCanvas.height === 0) {
            const container = salesPurchasesCanvas.parentElement;
            if (container) {
                salesPurchasesCanvas.width = container.offsetWidth || 400;
                salesPurchasesCanvas.height = container.offsetHeight || 256;
            }
        }
        
        // Destroy existing chart if any
        if (salesPurchasesChart) {
            try {
                salesPurchasesChart.destroy();
            } catch (e) {
                console.warn('Error destroying existing salesPurchasesChart:', e);
            }
        }
        
        const salesPurchasesCtx2d = salesPurchasesCtx.getContext('2d');
        const chartHeight = salesPurchasesCanvas.height || 300;
        
        // Create gradient for sales (will be updated after chart creation)
        let salesGradient = salesPurchasesCtx2d.createLinearGradient(0, 0, 0, chartHeight);
        salesGradient.addColorStop(0, 'rgba(59, 130, 246, 0.4)');
        salesGradient.addColorStop(0.5, 'rgba(59, 130, 246, 0.2)');
        salesGradient.addColorStop(1, 'rgba(59, 130, 246, 0.05)');
        
        // Create gradient for purchases
        let purchasesGradient = salesPurchasesCtx2d.createLinearGradient(0, 0, 0, chartHeight);
        purchasesGradient.addColorStop(0, 'rgba(16, 185, 129, 0.4)');
        purchasesGradient.addColorStop(0.5, 'rgba(16, 185, 129, 0.2)');
        purchasesGradient.addColorStop(1, 'rgba(16, 185, 129, 0.05)');
        
        salesPurchasesChart = new Chart(salesPurchasesCtx2d, {
            type: 'line',
            data: {
                labels: generateMonthLabels(),
                datasets: [{
                    label: 'Penjualan (Rp)',
                    data: {!! json_encode($chartData['sales']->toArray()) !!},
                    borderColor: 'rgb(59, 130, 246)',
                    backgroundColor: salesGradient,
                    tension: 0.5,
                    fill: true,
                    pointBackgroundColor: 'rgb(59, 130, 246)',
                    pointBorderColor: '#ffffff',
                    pointBorderWidth: 3,
                    pointRadius: 0,
                    pointHoverRadius: 8,
                    pointHoverBorderWidth: 3,
                    pointHoverBackgroundColor: '#ffffff',
                    borderWidth: 3,
                    cubicInterpolationMode: 'monotone'
                }, {
                    label: 'Pembelian (Rp)',
                    data: {!! json_encode($chartData['purchases']->toArray()) !!},
                    borderColor: 'rgb(16, 185, 129)',
                    backgroundColor: purchasesGradient,
                    tension: 0.5,
                    fill: true,
                    pointBackgroundColor: 'rgb(16, 185, 129)',
                    pointBorderColor: '#ffffff',
                    pointBorderWidth: 3,
                    pointRadius: 0,
                    pointHoverRadius: 8,
                    pointHoverBorderWidth: 3,
                    pointHoverBackgroundColor: '#ffffff',
                    borderWidth: 3,
                    cubicInterpolationMode: 'monotone'
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                resizeDelay: 0,
                animation: {
                    duration: 1200,
                    easing: 'easeInOutQuart'
                },
                onResize: function(chart, size) {
                    chart.update('none');
                },
                interaction: {
                    mode: 'index',
                    intersect: false,
                },
                plugins: {
                    legend: {
                        position: 'top',
                        align: 'end',
                        labels: { 
                            color: themeColors.text,
                            usePointStyle: true,
                            pointStyle: 'circle',
                            padding: 15,
                            font: {
                                size: 12,
                                weight: '500'
                            }
                        }
                    },
                    tooltip: {
                        backgroundColor: themeColors.tooltipBg,
                        titleColor: '#ffffff',
                        bodyColor: '#ffffff',
                        borderColor: themeColors.tooltipBorder,
                        borderWidth: 1,
                        padding: 12,
                        displayColors: true,
                        usePointStyle: true,
                        boxPadding: 6,
                        titleFont: {
                            size: 13,
                            weight: '600'
                        },
                        bodyFont: {
                            size: 12,
                            weight: '500'
                        },
                        callbacks: {
                            label: function(context) {
                                return context.dataset.label + ': Rp ' + context.parsed.y.toLocaleString('id-ID');
                            }
                        }
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        grid: {
                            color: themeColors.grid,
                            drawBorder: false,
                            lineWidth: 1
                        },
                        ticks: {
                            color: themeColors.text,
                            font: {
                                size: 11
                            },
                            padding: 10,
                            callback: function(value) {
                                if (value >= 1000000) {
                                    return 'Rp ' + (value / 1000000).toFixed(1) + 'M';
                                } else if (value >= 1000) {
                                    return 'Rp ' + (value / 1000).toFixed(0) + 'K';
                                }
                                return 'Rp ' + value.toLocaleString('id-ID');
                            }
                        }
                    },
                    x: {
                        grid: {
                            display: false,
                            drawBorder: false
                        },
                        ticks: {
                            color: themeColors.text,
                            font: {
                                size: 11
                            },
                            padding: 10
                        }
                    }
                }
            }
        });
        applyThemeToChart(salesPurchasesChart);
        
        // Store in global
        window.dashboardCharts.salesPurchases = salesPurchasesChart;
    } catch (error) {
        console.error('Error creating sales vs purchases chart:', error);
    }

    // Chart 2: Profit Analysis
    try {
        const profitCtx = document.getElementById('profitChart');
        if (!profitCtx) {
            console.error('profitChart element not found');
            return;
        }
        
        // Calculate profit data from sales and purchases
        const salesData = {!! json_encode($chartData['sales']->toArray()) !!};
        const purchasesData = {!! json_encode($chartData['purchases']->toArray()) !!};
        const profitData = [];
        
        for (let i = 0; i < 12; i++) {
            const sales = salesData[i] || 0;
            const purchases = purchasesData[i] || 0;
            profitData.push(sales - purchases);
        }
        
        // Ensure canvas is ready
        const profitCanvas = profitCtx;
        if (profitCanvas.width === 0 || profitCanvas.height === 0) {
            const container = profitCanvas.parentElement;
            if (container) {
                profitCanvas.width = container.offsetWidth || 400;
                profitCanvas.height = container.offsetHeight || 256;
            }
        }
        
        // Destroy existing chart if any
        if (profitChart) {
            try {
                profitChart.destroy();
            } catch (e) {
                console.warn('Error destroying existing profitChart:', e);
            }
        }
        
        const profitCtx2d = profitCtx.getContext('2d');
        const profitChartHeight = profitCanvas.height || 300;
        
        // Create gradient for profit bars
        const profitGradient = profitCtx2d.createLinearGradient(0, 0, 0, profitChartHeight);
        profitGradient.addColorStop(0, 'rgba(34, 197, 94, 0.9)');
        profitGradient.addColorStop(1, 'rgba(34, 197, 94, 0.5)');
        
        const lossGradient = profitCtx2d.createLinearGradient(0, 0, 0, profitChartHeight);
        lossGradient.addColorStop(0, 'rgba(239, 68, 68, 0.9)');
        lossGradient.addColorStop(1, 'rgba(239, 68, 68, 0.5)');
        
        profitChart = new Chart(profitCtx2d, {
            type: 'bar',
            data: {
                labels: generateMonthLabels(),
                datasets: [{
                    label: 'Profit (Penjualan - Pembelian)',
                    data: profitData,
                    backgroundColor: function(context) {
                        const value = context.parsed.y;
                        if (value >= 0) {
                            return profitGradient;
                        } else {
                            return lossGradient;
                        }
                    },
                    borderColor: function(context) {
                        const value = context.parsed.y;
                        return value >= 0 ? 'rgb(34, 197, 94)' : 'rgb(239, 68, 68)';
                    },
                    borderWidth: 2,
                    borderRadius: {
                        topLeft: 8,
                        topRight: 8,
                        bottomLeft: 0,
                        bottomRight: 0
                    },
                    borderSkipped: false,
                    maxBarThickness: 50
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                resizeDelay: 0,
                animation: {
                    duration: 1200,
                    easing: 'easeInOutQuart'
                },
                onResize: function(chart, size) {
                    chart.update('none');
                },
                plugins: {
                    legend: {
                        position: 'top',
                        align: 'end',
                        labels: { 
                            color: themeColors.text,
                            usePointStyle: true,
                            pointStyle: 'circle',
                            padding: 15,
                            font: {
                                size: 12,
                                weight: '500'
                            }
                        }
                    },
                    tooltip: {
                        backgroundColor: themeColors.tooltipBg,
                        titleColor: '#ffffff',
                        bodyColor: '#ffffff',
                        borderColor: themeColors.tooltipBorder,
                        borderWidth: 1,
                        padding: 12,
                        displayColors: true,
                        usePointStyle: true,
                        boxPadding: 6,
                        titleFont: {
                            size: 13,
                            weight: '600'
                        },
                        bodyFont: {
                            size: 12,
                            weight: '500'
                        },
                        callbacks: {
                            label: function(context) {
                                const value = context.parsed.y;
                                const status = value >= 0 ? 'Profit' : 'Loss';
                                return status + ': Rp ' + Math.abs(value).toLocaleString('id-ID');
                            }
                        }
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        grid: {
                            color: themeColors.grid,
                            drawBorder: false,
                            lineWidth: 1
                        },
                        ticks: {
                            color: themeColors.text,
                            font: {
                                size: 11
                            },
                            padding: 10,
                            callback: function(value) {
                                if (value >= 1000000) {
                                    return 'Rp ' + (value / 1000000).toFixed(1) + 'M';
                                } else if (value >= 1000) {
                                    return 'Rp ' + (value / 1000).toFixed(0) + 'K';
                                }
                                return 'Rp ' + value.toLocaleString('id-ID');
                            }
                        }
                    },
                    x: {
                        grid: {
                            display: false,
                            drawBorder: false
                        },
                        ticks: {
                            color: themeColors.text,
                            font: {
                                size: 11
                            },
                            padding: 10
                        }
                    }
                }
            }
        });
        applyThemeToChart(profitChart);
        
        // Store in global
        window.dashboardCharts.profit = profitChart;
        window.dashboardCharts.initialized = true;
    } catch (error) {
        console.error('Error creating profit chart:', error);
    }
    
    // Setup all event listeners after charts are created
    setupEventListeners();
}

// Setup all event listeners (called after charts are initialized)
function setupEventListeners() {
    // Window resize handler with debounce - improved for zoom
    let resizeTimeout;
    let lastWindowWidth = window.innerWidth;
    let lastWindowHeight = window.innerHeight;
    let lastZoomLevel = window.devicePixelRatio || 1;
    let lastContainerWidth = {};
    
    function getContainerWidth(elementId) {
        const element = document.getElementById(elementId);
        if (element && element.parentElement) {
            return element.parentElement.offsetWidth;
        }
        return 0;
    }
    
    function handleResize() {
        // Re-check if charts are initialized
        if (!window.dashboardCharts.initialized) {
            initializeDashboardCharts();
            return;
        }
        
        const currentWidth = window.innerWidth;
        const currentHeight = window.innerHeight;
        const currentZoom = window.devicePixelRatio || 1;
        
        // Check container widths for charts
        const salesContainerWidth = getContainerWidth('salesPurchasesChart');
        const profitContainerWidth = getContainerWidth('profitChart');
        
        // Check if size actually changed (window or zoom or container)
        const sizeChanged = Math.abs(currentWidth - lastWindowWidth) > 1 || 
                           Math.abs(currentHeight - lastWindowHeight) > 1 ||
                           Math.abs(currentZoom - lastZoomLevel) > 0.01 ||
                           (salesContainerWidth > 0 && Math.abs(salesContainerWidth - (lastContainerWidth.sales || 0)) > 1) ||
                           (profitContainerWidth > 0 && Math.abs(profitContainerWidth - (lastContainerWidth.profit || 0)) > 1);
        
        if (sizeChanged) {
            lastWindowWidth = currentWidth;
            lastWindowHeight = currentHeight;
            lastZoomLevel = currentZoom;
            if (salesContainerWidth > 0) lastContainerWidth.sales = salesContainerWidth;
            if (profitContainerWidth > 0) lastContainerWidth.profit = profitContainerWidth;
            
            clearTimeout(resizeTimeout);
            resizeTimeout = setTimeout(function() {
                if (window.forceRerenderDashboardCharts) {
                    window.forceRerenderDashboardCharts();
                }
            }, 30); // Even faster for smoother experience
        }
    }
    
    // Use both resize and orientationchange events
    window.addEventListener('resize', handleResize, { passive: true });
    window.addEventListener('orientationchange', function() {
        setTimeout(handleResize, 100);
    });
    
    // Also check zoom periodically (for browser zoom with Ctrl+/Ctrl-)
    setInterval(function() {
        const currentZoom = window.devicePixelRatio || 1;
        if (Math.abs(currentZoom - lastZoomLevel) > 0.01) {
            lastZoomLevel = currentZoom;
            handleResize();
        }
    }, 150); // More frequent checking
    
    // ResizeObserver for container size changes - improved
    if (typeof ResizeObserver !== 'undefined') {
        const salesPurchasesContainer = document.getElementById('salesPurchasesChart')?.parentElement;
        const profitContainer = document.getElementById('profitChart')?.parentElement;
        
        const resizeObserverCallback = function(entries) {
            for (let entry of entries) {
                const width = entry.contentRect.width;
                const elementId = entry.target.querySelector('canvas')?.id;
                if (elementId && width > 0) {
                    // Update last known width
                    if (elementId === 'salesPurchasesChart') {
                        lastContainerWidth.sales = width;
                    } else if (elementId === 'profitChart') {
                        lastContainerWidth.profit = width;
                    }
                }
            }
            clearTimeout(resizeTimeout);
            resizeTimeout = setTimeout(function() {
                if (window.forceRerenderDashboardCharts) {
                    window.forceRerenderDashboardCharts();
                }
            }, 50); // Reduced delay
        };
        
        if (salesPurchasesContainer) {
            const salesObserver = new ResizeObserver(resizeObserverCallback);
            salesObserver.observe(salesPurchasesContainer);
        }
        
        if (profitContainer) {
            const profitObserver = new ResizeObserver(resizeObserverCallback);
            profitObserver.observe(profitContainer);
        }
        
        // Also observe the main content container
        const mainContent = document.getElementById('mainContent');
        if (mainContent) {
            const mainObserver = new ResizeObserver(resizeObserverCallback);
            mainObserver.observe(mainContent);
        }
    }

    // MutationObserver for dark mode class changes
    const observer = new MutationObserver(function(mutations) {
        mutations.forEach(function(mutation) {
            if (mutation.type === 'attributes' && mutation.attributeName === 'class') {
                // Small delay to ensure class is fully applied
                setTimeout(function() {
                    const salesChart = window.dashboardCharts.salesPurchases;
                    const profitChartInstance = window.dashboardCharts.profit;
                    if (salesChart) applyThemeToChart(salesChart);
                    if (profitChartInstance) applyThemeToChart(profitChartInstance);
                }, 50);
            }
        });
    });
    
    // Observe both html and body for dark class changes
    observer.observe(document.documentElement, { 
        attributes: true, 
        attributeFilter: ['class'] 
    });
    observer.observe(document.body, { 
        attributes: true, 
        attributeFilter: ['class'] 
    });
    
    // Listen for explicit theme toggle events from navbar
    document.addEventListener('theme:toggle', function(event) {
        // Small delay to ensure class is fully applied
        setTimeout(function() {
            const salesChart = window.dashboardCharts.salesPurchases;
            const profitChartInstance = window.dashboardCharts.profit;
            if (salesChart) applyThemeToChart(salesChart);
            if (profitChartInstance) applyThemeToChart(profitChartInstance);
        }, 50);
    });
    
    // Initial resize to ensure charts are properly sized
    // Use requestAnimationFrame for better timing
    requestAnimationFrame(function() {
        setTimeout(function() {
            if (window.forceRerenderDashboardCharts) {
                window.forceRerenderDashboardCharts();
            }
        }, 50);
    });
    
    // Also resize after a longer delay to catch any layout shifts
    setTimeout(function() {
        if (window.forceRerenderDashboardCharts) {
            window.forceRerenderDashboardCharts();
        }
    }, 200);
    
    // Listen for visual viewport changes (for mobile zoom)
    if (window.visualViewport) {
        window.visualViewport.addEventListener('resize', function() {
            setTimeout(function() {
                if (window.forceRerenderDashboardCharts) {
                    window.forceRerenderDashboardCharts();
                }
            }, 50);
        });
    }
    
    // Resize when page becomes visible (handles tab switching)
    document.addEventListener('visibilitychange', function() {
        if (!document.hidden) {
            setTimeout(function() {
                forceRerenderCharts();
            }, 100);
        }
    });
    
    // Resize on window focus (handles browser window focus)
    window.addEventListener('focus', function() {
        setTimeout(function() {
            forceRerenderCharts();
        }, 100);
    });
    
    // Handle orientation change (mobile)
    window.addEventListener('orientationchange', function() {
        setTimeout(function() {
            if (window.forceRerenderDashboardCharts) {
                window.forceRerenderDashboardCharts();
            }
        }, 300);
    });
}

// Wait for DOM to be ready
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', initializeDashboardCharts);
} else {
    // DOM already loaded, initialize immediately
    initializeDashboardCharts();
}

// Also try after window load (in case scripts load late)
window.addEventListener('load', function() {
    setTimeout(function() {
        if (!window.dashboardCharts.initialized) {
            initializeDashboardCharts();
        } else {
            if (window.forceRerenderDashboardCharts) {
                window.forceRerenderDashboardCharts();
            }
        }
    }, 100);
});
</script>

