{{-- Revenue Trends Chart (Full Width) --}}
<div class="bg-white border border-gray-200 rounded-lg shadow-xs p-6 dark:bg-gray-800 dark:border-gray-700 mb-6">
    <h5 class="text-xl font-bold leading-none text-gray-900 dark:text-white mb-4">{{ __('admin.revenue_trends') }}</h5>
    <div wire:ignore>
        <div id="revenueChart" style="min-height: 300px;"></div>
    </div>
</div>

{{-- Build Activity Chart (Full Width) --}}
<div class="bg-white border border-gray-200 rounded-lg shadow-xs p-6 dark:bg-gray-800 dark:border-gray-700 mb-6">
    <h5 class="text-xl font-bold leading-none text-gray-900 dark:text-white mb-4">{{ __('admin.build_activity') }}</h5>
    <div wire:ignore>
        <div id="buildActivityChart" style="min-height: 300px;"></div>
    </div>
</div>

@push('styles')
<style>
    /* Fix ApexCharts in dark mode */
    .dark .apexcharts-legend,
    .dark .apexcharts-legend-series,
    .dark .apexcharts-inner,
    .dark .apexcharts-canvas,
    .dark .apexcharts-svg,
    .dark .apexcharts-graphical,
    .dark .apexcharts-plot-series {
        background: transparent !important;
        background-color: transparent !important;
    }
    .dark .apexcharts-legend-text {
        color: #9CA3AF !important;
    }
    .dark .apexcharts-text,
    .dark .apexcharts-text tspan,
    .dark .apexcharts-xaxis-label,
    .dark .apexcharts-yaxis-label,
    .dark .apexcharts-yaxis-title text {
        fill: #9CA3AF !important;
    }
    .dark foreignObject {
        background: transparent !important;
        background-color: transparent !important;
    }
    .dark foreignObject * {
        background: transparent !important;
        background-color: transparent !important;
    }
</style>
@endpush

@push('scripts')
<script>
// Translations for chart labels
const chartTranslations = {
    completed: {{ Js::from(__('admin.completed')) }},
    failed: {{ Js::from(__('admin.failed')) }},
    pending: {{ Js::from(__('common.pending')) }},
    revenue: {{ Js::from(__('admin.revenue_label_short')) }},
    builds: {{ Js::from(__('admin.builds_label')) }}
};

// RTL detection
const isRTL = document.documentElement.dir === 'rtl' || document.documentElement.getAttribute('dir') === 'rtl';

document.addEventListener('livewire:navigated', function () {
    initializeCharts();
});

document.addEventListener('livewire:init', function () {
    initializeCharts();

    Livewire.on('dateRangeChanged', (event) => {
        setTimeout(() => {
            initializeCharts();
        }, 100);
    });

    Livewire.on('statsRefreshed', () => {
        setTimeout(() => {
            initializeCharts();
        }, 100);
    });
});

function initializeCharts() {
    // Check if ApexCharts is loaded
    if (typeof ApexCharts === 'undefined') {
        console.error('ApexCharts not loaded');
        return;
    }

    // Get chart data from stats (passed from Livewire)
    const revenueData = @json($stats['revenue_chart_data'] ?? null) || {labels: [], data: []};
    const buildActivityData = @json($stats['build_activity_chart_data'] ?? null) || {labels: [], completed: [], failed: [], pending: []};

    // Determine if dark mode is active
    const isDarkMode = document.documentElement.classList.contains('dark');

    // Common chart options for dark mode
    const darkModeOptions = {
        theme: {
            mode: isDarkMode ? 'dark' : 'light'
        },
        chart: {
            background: 'transparent',
            toolbar: {
                show: false
            }
        },
        grid: {
            borderColor: isDarkMode ? '#374151' : '#e5e7eb'
        }
    };

    // Revenue Trends Chart
    const revenueChartElement = document.querySelector('#revenueChart');
    if (revenueChartElement) {
        // Destroy existing chart if it exists
        if (revenueChartElement._apexChart) {
            revenueChartElement._apexChart.destroy();
        }

        const revenueChart = new ApexCharts(revenueChartElement, {
            ...darkModeOptions,
            series: [{
                name: chartTranslations.revenue || 'Revenue',
                data: revenueData.data
            }],
            chart: {
                ...darkModeOptions.chart,
                type: 'bar',
                height: 300,
                fontFamily: 'Inter, sans-serif',
                foreColor: isDarkMode ? '#9CA3AF' : '#373d3f',
            },
            plotOptions: {
                bar: {
                    borderRadius: 8,
                    columnWidth: '60%',
                }
            },
            dataLabels: {
                enabled: false
            },
            stroke: {
                show: true,
                width: 2,
                colors: ['transparent']
            },
            xaxis: {
                categories: revenueData.labels,
                labels: {
                    style: {
                        colors: isDarkMode ? '#9CA3AF' : '#6B7280'
                    }
                }
            },
            yaxis: {
                opposite: isRTL,
                title: {
                    text: '$ (USD)',
                    style: {
                        color: isDarkMode ? '#9CA3AF' : '#6B7280'
                    }
                },
                labels: {
                    formatter: function (val) {
                        if (val === null || val === undefined || isNaN(val)) {
                            return '$0.00';
                        }
                        return '$' + Number(val).toFixed(2);
                    },
                    style: {
                        colors: isDarkMode ? '#9CA3AF' : '#6B7280'
                    }
                }
            },
            fill: {
                colors: ['#8B5CF6'],
                opacity: 1
            },
            tooltip: {
                custom: function({ series, seriesIndex, dataPointIndex, w }) {
                    const value = series[seriesIndex][dataPointIndex];
                    const label = w.globals.labels[dataPointIndex];
                    const formattedValue = value !== null && value !== undefined && !isNaN(value)
                        ? '$' + Number(value).toFixed(2)
                        : '$0.00';
                    const dark = document.documentElement.classList.contains('dark');
                    const bgClass = dark ? 'bg-gray-800 border-gray-600' : 'bg-white border-gray-200';
                    const headerClass = dark ? 'bg-gray-700 border-gray-600 text-white' : 'bg-gray-100 border-gray-200 text-gray-800';
                    const labelClass = dark ? 'text-gray-400' : 'text-gray-500';
                    const valueClass = dark ? 'text-white' : 'text-gray-800';
                    return '<div class="' + bgClass + ' border rounded-lg shadow-lg overflow-hidden">' +
                        '<div class="' + headerClass + ' px-3 py-2 border-b font-semibold">' + label + '</div>' +
                        '<div class="px-3 py-2 flex items-center gap-2">' +
                        '<span class="w-2.5 h-2.5 bg-purple-500 rounded-full inline-block"></span>' +
                        '<span class="' + labelClass + '">' + (chartTranslations.revenue || 'Revenue') + ':</span>' +
                        '<span class="font-semibold ' + valueClass + '">' + formattedValue + '</span>' +
                        '</div></div>';
                }
            }
        });

        revenueChart.render();
        revenueChartElement._apexChart = revenueChart;
    }

    // Build Activity Chart
    const buildActivityChartElement = document.querySelector('#buildActivityChart');
    if (buildActivityChartElement) {
        // Destroy existing chart if it exists
        if (buildActivityChartElement._apexChart) {
            buildActivityChartElement._apexChart.destroy();
        }

        const buildActivityChart = new ApexCharts(buildActivityChartElement, {
            ...darkModeOptions,
            series: [
                {
                    name: chartTranslations.completed,
                    data: buildActivityData.completed
                },
                {
                    name: chartTranslations.failed,
                    data: buildActivityData.failed
                },
                {
                    name: chartTranslations.pending,
                    data: buildActivityData.pending
                }
            ],
            chart: {
                ...darkModeOptions.chart,
                type: 'bar',
                height: 300,
                fontFamily: 'Inter, sans-serif',
                stacked: true,
                foreColor: isDarkMode ? '#9CA3AF' : '#373d3f',
            },
            plotOptions: {
                bar: {
                    horizontal: false,
                    borderRadius: 4,
                    columnWidth: '70%',
                }
            },
            dataLabels: {
                enabled: false
            },
            xaxis: {
                categories: buildActivityData.labels,
                labels: {
                    rotate: -45,
                    rotateAlways: false,
                    style: {
                        colors: isDarkMode ? '#9CA3AF' : '#6B7280',
                        fontSize: '10px'
                    }
                }
            },
            yaxis: {
                opposite: isRTL,
                title: {
                    text: chartTranslations.builds || 'Builds',
                    style: {
                        color: isDarkMode ? '#9CA3AF' : '#6B7280'
                    }
                },
                labels: {
                    style: {
                        colors: isDarkMode ? '#9CA3AF' : '#6B7280'
                    }
                }
            },
            legend: {
                position: 'top',
                horizontalAlign: isRTL ? 'right' : 'left',
                labels: {
                    colors: isDarkMode ? '#9CA3AF' : '#6B7280'
                }
            },
            colors: ['#10B981', '#EF4444', '#F59E0B'],
            fill: {
                opacity: 1
            },
            tooltip: {
                custom: function({ series, seriesIndex, dataPointIndex, w }) {
                    const label = w.globals.labels[dataPointIndex];
                    const colorClasses = ['bg-green-500', 'bg-red-500', 'bg-yellow-500'];
                    const names = [chartTranslations.completed, chartTranslations.failed, chartTranslations.pending];
                    const dark = document.documentElement.classList.contains('dark');
                    const bgClass = dark ? 'bg-gray-800 border-gray-600' : 'bg-white border-gray-200';
                    const headerClass = dark ? 'bg-gray-700 border-gray-600 text-white' : 'bg-gray-100 border-gray-200 text-gray-800';
                    const labelClass = dark ? 'text-gray-400' : 'text-gray-500';
                    const valueClass = dark ? 'text-white' : 'text-gray-800';

                    let rows = '';
                    for (let i = 0; i < series.length; i++) {
                        const val = series[i][dataPointIndex];
                        const formattedVal = val !== null && val !== undefined && !isNaN(val) ? Number(val) : 0;
                        rows += '<div class="px-3 py-1.5 flex items-center gap-2">' +
                            '<span class="w-2.5 h-2.5 ' + colorClasses[i] + ' rounded-full inline-block"></span>' +
                            '<span class="' + labelClass + '">' + names[i] + ':</span>' +
                            '<span class="font-semibold ' + valueClass + '">' + formattedVal + '</span>' +
                            '</div>';
                    }

                    return '<div class="' + bgClass + ' border rounded-lg shadow-lg overflow-hidden">' +
                        '<div class="' + headerClass + ' px-3 py-2 border-b font-semibold">' + label + '</div>' +
                        rows +
                        '</div>';
                }
            }
        });

        buildActivityChart.render();
        buildActivityChartElement._apexChart = buildActivityChart;
    }

    // Fix legend text colors for dark mode after a short delay (ApexCharts uses inline styles)
    setTimeout(fixLegendColors, 200);
}

function fixLegendColors() {
    const isDark = document.documentElement.classList.contains('dark');
    const color = isDark ? '#9CA3AF' : '#373d3f';
    const bgColor = isDark ? 'transparent' : '#fff';

    // Fix all legend text elements - ApexCharts sets inline styles that override CSS
    document.querySelectorAll('.apexcharts-legend-text').forEach(el => {
        el.style.setProperty('color', color, 'important');
    });

    // Fix legend wrapper backgrounds - ApexCharts sets inline background styles
    document.querySelectorAll('.apexcharts-legend').forEach(el => {
        el.style.setProperty('background', 'transparent', 'important');
        el.style.setProperty('background-color', 'transparent', 'important');
    });

    // Fix all divs inside foreignObject - these can have inline backgrounds
    document.querySelectorAll('foreignObject div').forEach(el => {
        el.style.setProperty('background', 'transparent', 'important');
        el.style.setProperty('background-color', 'transparent', 'important');
    });

    // Fix SVG background rects that ApexCharts creates with white fill
    document.querySelectorAll('.apexcharts-canvas svg rect[fill="#fff"], .apexcharts-canvas svg rect[fill="#ffffff"], .apexcharts-canvas svg rect[fill="white"]').forEach(rect => {
        rect.setAttribute('fill', bgColor);
    });

    // Also fix any rect without explicit fill (defaults to black in SVG but may render as white)
    document.querySelectorAll('.apexcharts-canvas svg > rect:first-child').forEach(rect => {
        if (isDark) {
            rect.setAttribute('fill', 'transparent');
        }
    });
}

// Re-initialize charts when dark mode changes (system preference)
if (window.matchMedia) {
    window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => {
        setTimeout(() => {
            initializeCharts();
        }, 100);
    });
}

// Re-initialize charts when dark mode is toggled via button (class change)
const darkModeObserver = new MutationObserver((mutations) => {
    mutations.forEach((mutation) => {
        if (mutation.attributeName === 'class') {
            setTimeout(() => {
                initializeCharts();
            }, 100);
        }
    });
});

darkModeObserver.observe(document.documentElement, {
    attributes: true,
    attributeFilter: ['class']
});
</script>
@endpush
