<flux:main>
    <flux:heading size="xl" level="1" class="mb-6">{{ $pageTitle }}</flux:heading>

    <div class="mt-6">
        <div class="flex flex-col lg:flex-row lg:justify-between lg:items-center mb-6 gap-4">
            <div class="flex flex-col sm:flex-row flex-wrap items-start sm:items-center gap-4 w-full">
                <div class="flex items-center gap-2 w-full sm:w-auto">
                    <flux:select wire:model.live="period" class="w-full sm:w-auto">
                        <option value="all">Semua</option>
                        <option value="7">7 Hari Terakhir</option>
                        <option value="30">30 Hari Terakhir</option>
                        <option value="90">90 Hari Terakhir</option>
                        <option value="365">1 Tahun Terakhir</option>
                    </flux:select>
                </div>

                <flux:separator vertical class="hidden lg:block mx-2 my-2" />

                @if (count($outlets) > 1)
                    <div class="flex flex-wrap gap-2 w-full sm:w-auto">
                        <flux:checkbox.group wire:model.live="selectedOutletIds" variant="buttons">
                            @foreach ($outlets as $key => $value)
                                <flux:checkbox value="{{ $key }}" label="{{ $value }}" />
                            @endforeach
                        </flux:checkbox.group>
                    </div>
                    <flux:separator vertical class="hidden lg:block mx-2 my-2" />
                @endif

                <div class="w-full sm:w-auto">
                    <flux:date-picker mode="range" wire:model.live="range">
                        <x-slot name="trigger">
                            <div class="flex flex-col sm:flex-row gap-3 sm:gap-4 w-full">
                                <flux:date-picker.input />
                                <flux:date-picker.input />
                            </div>
                        </x-slot>
                    </flux:date-picker>
                </div>
            </div>
        </div>

        <flux:separator class="mb-6" />

        <flux:heading>Counting Data</flux:heading>
        <div class="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-6 gap-3 mb-6 mt-2">
            @foreach ($countingData as $item)
                <div class="rounded-lg px-6 py-4 bg-zinc-200 dark:bg-zinc-700">
                    <flux:subheading>{{ $item['title'] }}</flux:subheading>
                    <flux:heading size="xl" class="mb-2">{{ $item['value'] }}</flux:heading>
                </div>
            @endforeach
        </div>

        <flux:heading>Order</flux:heading>
        <div class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 xl:grid-cols-4 gap-4 mb-6 mt-2">
            @foreach ($orders as $order)
                <div class="rounded-lg px-6 py-4 bg-zinc-200 dark:bg-zinc-700">
                    <flux:subheading>{{ $order['title'] }}</flux:subheading>
                    <flux:heading size="xl" class="mb-2">{{ $order['value'] }}</flux:heading>
                </div>
            @endforeach
        </div>

        <flux:heading>Pengeluaran</flux:heading>
        <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6 mt-2">
            @foreach ($expenses as $expense)
                <div class="rounded-lg px-6 py-4 bg-zinc-200 dark:bg-zinc-700">
                    <flux:subheading>{{ $expense['title'] }}</flux:subheading>
                    <flux:heading size="xl" class="mb-2">{{ $expense['value'] }}</flux:heading>
                </div>
            @endforeach
        </div>

        <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-8" x-data="analysisCharts">
            <!-- 1. Revenue & Profit Trend -->
            <flux:card wire:ignore>
                <flux:heading class="mb-4">Trend Pendapatan & Laba (30 Hari Terakhir)</flux:heading>
                <div class="h-80"><canvas id="revenueTrendChart"></canvas></div>
            </flux:card>

            <!-- 6. Member Growth (Area Chart) - Cumulative -->
            <flux:card wire:ignore>
                <flux:heading class="mb-4">Pertumbuhan Member (Akumulasi)</flux:heading>
                <div class="h-80"><canvas id="memberGrowthChart"></canvas></div>
            </flux:card>

            <!-- 2. busiest hour -->
            <flux:card wire:ignore>
                <flux:heading class="mb-4">Jam Sibuk (Total Order per Jam)</flux:heading>
                <div class="h-80"><canvas id="hourlySalesChart"></canvas></div>
            </flux:card>

            <!-- 5. Outlet Performance -->
            <flux:card wire:ignore>
                <flux:heading class="mb-4">Performa Outlet (Pendapatan)</flux:heading>
                <div class="h-80"><canvas id="outletPerformanceChart"></canvas></div>
            </flux:card>

            <!-- 3. Product Category Distribution -->
            <flux:card wire:ignore>
                <flux:heading class="mb-4">Distribusi Penjualan</flux:heading>
                <div class="h-80 flex items-center justify-center">
                    <canvas id="categoryDistributionChart"></canvas>
                </div>
            </flux:card>

            <!-- 4. Payment Method -->
            <flux:card wire:ignore>
                <flux:heading class="mb-4">Metode Pembayaran</flux:heading>
                <div class="h-80 flex items-center justify-center">
                    <canvas id="paymentMethodChart"></canvas>
                </div>
            </flux:card>

            <!-- 7. Day of Week Sales -->
            <flux:card wire:ignore>
                <flux:heading class="mb-4">Performa Penjualan per Hari</flux:heading>
                <div class="h-80"><canvas id="dayOfWeekSalesChart"></canvas></div>
            </flux:card>

            <!-- 8. Customer Type Distribution -->
            <flux:card wire:ignore>
                <flux:heading class="mb-4">Segmentasi Pelanggan (Member vs Guest)</flux:heading>
                <div class="h-80 flex items-center justify-center">
                    <canvas id="customerTypeChart"></canvas>
                </div>
            </flux:card>

            <!-- 9. Transaction Trend -->
            <flux:card wire:ignore>
                <flux:heading class="mb-4">Trend Volume Transaksi (30 Hari)</flux:heading>
                <div class="h-80"><canvas id="transactionTrendChart"></canvas></div>
            </flux:card>

            <!-- 10. AOV Trend -->
            <flux:card wire:ignore>
                <flux:heading class="mb-4">Trend Rata-rata Belanja (AOV)</flux:heading>
                <div class="h-80"><canvas id="aovTrendChart"></canvas></div>
            </flux:card>

            <!-- 11. Expense Breakdown -->
            <flux:card wire:ignore>
                <flux:heading class="mb-4">Komposisi Biaya Operasional</flux:heading>
                <div class="h-80 flex items-center justify-center">
                    <canvas id="expenseBreakdownChart"></canvas>
                </div>
            </flux:card>

            <!-- 12. Revenue vs Cost -->
            <flux:card wire:ignore>
                <flux:heading class="mb-4">Omzet vs Total Biaya</flux:heading>
                <div class="h-80 flex items-center justify-center">
                    <canvas id="revenueVsCostChart"></canvas>
                </div>
            </flux:card>

            <!-- 13. Customer Retention -->
            <flux:card wire:ignore>
                <flux:heading class="mb-4">Analisa Pelanggan (Baru vs Lama)</flux:heading>
                <div class="h-80 flex items-center justify-center">
                    <canvas id="customerRetentionChart"></canvas>
                </div>
            </flux:card>

            <!-- 14. Voucher Activity -->
            <flux:card wire:ignore>
                <flux:heading class="mb-4">Efektivitas Voucher</flux:heading>
                <div class="h-80"><canvas id="voucherUsageTrendChart"></canvas></div>
            </flux:card>
        </div>

        <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6 mt-2">
            <div>
                <flux:heading>Top 5 Parfum</flux:heading>
                <flux:card class="mb-6 mt-2 bg-zinc-200 dark:bg-zinc-700">
                    <flux:table>
                        <flux:table.columns>
                            <flux:table.column>No</flux:table.column>
                            <flux:table.column>Nama</flux:table.column>
                            <flux:table.column>Harga</flux:table.column>
                            <flux:table.column>Terjual</flux:table.column>
                            <flux:table.column>Total</flux:table.column>
                        </flux:table.columns>

                        <flux:table.rows>
                            @foreach ($topPerfumes as $topPerfume)
                                <flux:table.row>
                                    <flux:table.cell>{{ $loop->iteration }}</flux:table.cell>
                                    <flux:table.cell>{{ $topPerfume['name'] }}</flux:table.cell>
                                    <flux:table.cell>{{ $topPerfume['sale_price'] }}</flux:table.cell>
                                    <flux:table.cell>{{ $topPerfume['total_sold'] }}</flux:table.cell>
                                    <flux:table.cell variant="strong">{{ $topPerfume['total_sales'] }}
                                    </flux:table.cell>
                                </flux:table.row>
                            @endforeach
                        </flux:table.rows>
                    </flux:table>
                </flux:card>
            </div>

            <div>
                <flux:heading>Top 5 Produk</flux:heading>
                <flux:card class="mb-6 mt-2 bg-zinc-200 dark:bg-zinc-700">
                    <flux:table>
                        <flux:table.columns>
                            <flux:table.column>No</flux:table.column>
                            <flux:table.column>Nama</flux:table.column>
                            <flux:table.column>Harga</flux:table.column>
                            <flux:table.column>Terjual</flux:table.column>
                            <flux:table.column>Total</flux:table.column>
                        </flux:table.columns>

                        <flux:table.rows>
                            @foreach ($topProducts as $topProduct)
                                <flux:table.row>
                                    <flux:table.cell>{{ $loop->iteration }}</flux:table.cell>
                                    <flux:table.cell>{{ $topProduct['name'] }}</flux:table.cell>
                                    <flux:table.cell>{{ $topProduct['sale_price'] }}</flux:table.cell>
                                    <flux:table.cell>{{ $topProduct['total_sold'] }}</flux:table.cell>
                                    <flux:table.cell variant="strong">{{ $topProduct['total_sales'] }}
                                    </flux:table.cell>
                                </flux:table.row>
                            @endforeach
                        </flux:table.rows>
                    </flux:table>
                </flux:card>
            </div>

            <div>
                <flux:heading>Top 5 Botol</flux:heading>
                <flux:card class="mb-6 mt-2 bg-zinc-200 dark:bg-zinc-700">
                    <flux:table>
                        <flux:table.columns>
                            <flux:table.column>No</flux:table.column>
                            <flux:table.column>Nama</flux:table.column>
                            <flux:table.column>Harga</flux:table.column>
                            <flux:table.column>Terjual</flux:table.column>
                            <flux:table.column>Total</flux:table.column>
                        </flux:table.columns>

                        <flux:table.rows>
                            @foreach ($topBottles as $topBottle)
                                <flux:table.row>
                                    <flux:table.cell>{{ $loop->iteration }}</flux:table.cell>
                                    <flux:table.cell>{{ $topBottle['name'] }}</flux:table.cell>
                                    <flux:table.cell>{{ $topBottle['sale_price'] }}</flux:table.cell>
                                    <flux:table.cell>{{ $topBottle['total_sold'] }}</flux:table.cell>
                                    <flux:table.cell variant="strong">{{ $topBottle['total_sales'] }}</flux:table.cell>
                                </flux:table.row>
                            @endforeach
                        </flux:table.rows>
                    </flux:table>
                </flux:card>
            </div>
        </div>
    </div>
</flux:main>

@assets
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
@endassets

@script
    <script>
        Alpine.data('analysisCharts', () => ({
            charts: {},

            init() {
                // Memastikan DOM siap dan library tersedia sebelum inisialisasi awal
                const start = () => {
                    if (typeof Chart !== 'undefined') {
                        this.initAll();
                    } else {
                        setTimeout(start, 50);
                    }
                };

                this.$nextTick(() => start());

                // Watchers untuk pembaruan data reaktif
                this.$watch('$wire.revenueTrendChart', () => this.updateRevenueTrend());
                this.$watch('$wire.memberGrowthChart', () => this.updateMemberGrowth());
                this.$watch('$wire.hourlySalesChart', () => this.updateHourlySales());
                this.$watch('$wire.outletPerformanceChart', () => this.updateOutletPerformance());
                this.$watch('$wire.categoryDistributionChart', () => this.updateCategoryDistribution());
                this.$watch('$wire.paymentMethodChart', () => this.updatePaymentMethod());
                this.$watch('$wire.dayOfWeekSalesChart', () => this.updateDayOfWeekSales());
                this.$watch('$wire.customerTypeChart', () => this.updateCustomerType());
                this.$watch('$wire.transactionTrendChart', () => this.updateTransactionTrend());
                this.$watch('$wire.aovTrendChart', () => this.updateAovTrend());
                this.$watch('$wire.expenseBreakdownChart', () => this.updateExpenseBreakdown());
                this.$watch('$wire.revenueVsCostChart', () => this.updateRevenueVsCost());
                this.$watch('$wire.customerRetentionChart', () => this.updateCustomerRetention());
                this.$watch('$wire.voucherUsageTrendChart', () => this.updateVoucherUsage());
            },

            initAll() {
                console.log('Rendering Analysis Charts...');
                this.initRevenueTrend();
                this.initMemberGrowth();
                this.initHourlySales();
                this.initOutletPerformance();
                this.initCategoryDistribution();
                this.initPaymentMethod();
                this.initDayOfWeekSales();
                this.initCustomerType();
                this.initTransactionTrend();
                this.initAovTrend();
                this.initExpenseBreakdown();
                this.initRevenueVsCost();
                this.initCustomerRetention();
                this.initVoucherUsage();

                this.isInitialized = true;
            },

            initRevenueTrend() {
                const ctx = document.getElementById('revenueTrendChart');
                if (!ctx) return;

                const data = $wire.revenueTrendChart;
                if (!data || !data.labels) return;

                this.charts.revenue = new Chart(ctx, {
                    type: 'line',
                    data: this.getRevenueData(),
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        plugins: {
                            legend: {
                                position: 'top'
                            }
                        },
                        scales: {
                            y: {
                                beginAtZero: true
                            }
                        }
                    }
                });
            },
            getRevenueData() {
                const data = $wire.revenueTrendChart;
                return {
                    labels: data.labels || [],
                    datasets: [{
                            label: 'Pendapatan',
                            data: data.revenue || [],
                            borderColor: '#10b981',
                            backgroundColor: 'rgba(16, 185, 129, 0.1)',
                            tension: 0.4,
                            fill: true
                        },
                        {
                            label: 'Laba Bersih',
                            data: data.profit || [],
                            borderColor: '#3b82f6',
                            backgroundColor: 'rgba(59, 130, 246, 0.1)',
                            tension: 0.4,
                            fill: true
                        }
                    ]
                };
            },
            updateRevenueTrend() {
                if (this.charts.revenue) {
                    this.charts.revenue.data = this.getRevenueData();
                    this.charts.revenue.update();
                } else {
                    this.initRevenueTrend();
                }
            },

            initMemberGrowth() {
                const ctx = document.getElementById('memberGrowthChart');
                if (!ctx) return;
                const data = $wire.memberGrowthChart;
                if (!data || !data.labels) return;

                this.charts.memberGrowth = new Chart(ctx, {
                    type: 'line',
                    data: this.getMemberGrowthData(),
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        scales: {
                            y: {
                                beginAtZero: true
                            }
                        }
                    }
                });
            },
            getMemberGrowthData() {
                const data = $wire.memberGrowthChart;
                return {
                    labels: data.labels || [],
                    datasets: [{
                        label: 'Total Member',
                        data: data.data || [],
                        borderColor: '#8b5cf6',
                        backgroundColor: 'rgba(139, 92, 246, 0.1)',
                        fill: true,
                        tension: 0.2
                    }]
                };
            },
            updateMemberGrowth() {
                if (this.charts.memberGrowth) {
                    this.charts.memberGrowth.data = this.getMemberGrowthData();
                    this.charts.memberGrowth.update();
                } else {
                    this.initMemberGrowth();
                }
            },

            initHourlySales() {
                const ctx = document.getElementById('hourlySalesChart');
                if (!ctx) return;
                const data = $wire.hourlySalesChart;
                if (!data || !data.labels) return;

                this.charts.hourlySales = new Chart(ctx, {
                    type: 'bar',
                    data: this.getHourlySalesData(),
                    options: {
                        responsive: true,
                        maintainAspectRatio: false
                    }
                });
            },
            getHourlySalesData() {
                const data = $wire.hourlySalesChart;
                return {
                    labels: data.labels || [],
                    datasets: [{
                        label: 'Jumlah Order',
                        data: data.data || [],
                        backgroundColor: '#f59e0b'
                    }]
                };
            },
            updateHourlySales() {
                if (this.charts.hourlySales) {
                    this.charts.hourlySales.data = this.getHourlySalesData();
                    this.charts.hourlySales.update();
                } else {
                    this.initHourlySales();
                }
            },

            initOutletPerformance() {
                const ctx = document.getElementById('outletPerformanceChart');
                if (!ctx) return;
                const data = $wire.outletPerformanceChart;
                if (!data || !data.labels) return;

                this.charts.outletPerformance = new Chart(ctx, {
                    type: 'bar',
                    data: this.getOutletPerformanceData(),
                    options: {
                        indexAxis: 'y',
                        responsive: true,
                        maintainAspectRatio: false
                    }
                });
            },
            getOutletPerformanceData() {
                const data = $wire.outletPerformanceChart;
                return {
                    labels: data.labels || [],
                    datasets: [{
                        label: 'Pendapatan',
                        data: data.data || [],
                        backgroundColor: '#ef4444'
                    }]
                };
            },
            updateOutletPerformance() {
                if (this.charts.outletPerformance) {
                    this.charts.outletPerformance.data = this.getOutletPerformanceData();
                    this.charts.outletPerformance.update();
                } else {
                    this.initOutletPerformance();
                }
            },

            initCategoryDistribution() {
                const ctx = document.getElementById('categoryDistributionChart');
                if (!ctx) return;
                const data = $wire.categoryDistributionChart;
                if (!data || !data.labels) return;

                this.charts.categoryDist = new Chart(ctx, {
                    type: 'doughnut',
                    data: this.getCategoryDistributionData(),
                    options: {
                        responsive: true,
                        maintainAspectRatio: false
                    }
                });
            },
            getCategoryDistributionData() {
                const data = $wire.categoryDistributionChart;
                return {
                    labels: data.labels || [],
                    datasets: [{
                        data: data.data || [],
                        backgroundColor: ['#10b981', '#3b82f6', '#f59e0b']
                    }]
                };
            },
            updateCategoryDistribution() {
                if (this.charts.categoryDist) {
                    this.charts.categoryDist.data = this.getCategoryDistributionData();
                    this.charts.categoryDist.update();
                } else {
                    this.initCategoryDistribution();
                }
            },

            initPaymentMethod() {
                const ctx = document.getElementById('paymentMethodChart');
                if (!ctx) return;
                const data = $wire.paymentMethodChart;
                if (!data || !data.labels) return;

                this.charts.paymentMethod = new Chart(ctx, {
                    type: 'pie',
                    data: this.getPaymentMethodData(),
                    options: {
                        responsive: true,
                        maintainAspectRatio: false
                    }
                });
            },
            getPaymentMethodData() {
                const data = $wire.paymentMethodChart;
                return {
                    labels: data.labels || [],
                    datasets: [{
                        data: data.data || [],
                        backgroundColor: ['#10b981', '#3b82f6', '#8b5cf6', '#6b7280']
                    }]
                };
            },
            updatePaymentMethod() {
                if (this.charts.paymentMethod) {
                    this.charts.paymentMethod.data = this.getPaymentMethodData();
                    this.charts.paymentMethod.update();
                } else {
                    this.initPaymentMethod();
                }
            },

            initDayOfWeekSales() {
                const ctx = document.getElementById('dayOfWeekSalesChart');
                if (!ctx) return;
                const data = $wire.dayOfWeekSalesChart;
                if (!data || !data.labels) return;

                this.charts.dayOfWeek = new Chart(ctx, {
                    type: 'bar',
                    data: this.getDayOfWeekData(),
                    options: {
                        responsive: true,
                        maintainAspectRatio: false
                    }
                });
            },
            getDayOfWeekData() {
                const data = $wire.dayOfWeekSalesChart;
                return {
                    labels: data.labels || [],
                    datasets: [{
                        label: 'Pendapatan',
                        data: data.data || [],
                        backgroundColor: '#6366f1'
                    }]
                };
            },
            updateDayOfWeekSales() {
                if (this.charts.dayOfWeek) {
                    this.charts.dayOfWeek.data = this.getDayOfWeekData();
                    this.charts.dayOfWeek.update();
                } else {
                    this.initDayOfWeekSales();
                }
            },

            initCustomerType() {
                const ctx = document.getElementById('customerTypeChart');
                if (!ctx) return;
                const data = $wire.customerTypeChart;
                if (!data || !data.labels) return;

                this.charts.customerType = new Chart(ctx, {
                    type: 'doughnut',
                    data: this.getCustomerTypeData(),
                    options: {
                        responsive: true,
                        maintainAspectRatio: false
                    }
                });
            },
            getCustomerTypeData() {
                const data = $wire.customerTypeChart;
                return {
                    labels: data.labels || [],
                    datasets: [{
                        data: data.data || [],
                        backgroundColor: ['#8b5cf6', '#94a3b8']
                    }]
                };
            },
            updateCustomerType() {
                if (this.charts.customerType) {
                    this.charts.customerType.data = this.getCustomerTypeData();
                    this.charts.customerType.update();
                } else {
                    this.initCustomerType();
                }
            },

            initTransactionTrend() {
                const ctx = document.getElementById('transactionTrendChart');
                if (!ctx) return;
                const data = $wire.transactionTrendChart;
                if (!data || !data.labels) return;

                this.charts.transactionTrend = new Chart(ctx, {
                    type: 'line',
                    data: this.getTransactionTrendData(),
                    options: {
                        responsive: true,
                        maintainAspectRatio: false
                    }
                });
            },
            getTransactionTrendData() {
                const data = $wire.transactionTrendChart;
                return {
                    labels: data.labels || [],
                    datasets: [{
                        label: 'Jumlah Transaksi',
                        data: data.data || [],
                        borderColor: '#f43f5e',
                        backgroundColor: 'rgba(244, 63, 94, 0.1)',
                        fill: true,
                        tension: 0.3
                    }]
                };
            },
            updateTransactionTrend() {
                if (this.charts.transactionTrend) {
                    this.charts.transactionTrend.data = this.getTransactionTrendData();
                    this.charts.transactionTrend.update();
                } else {
                    this.initTransactionTrend();
                }
            },

            initAovTrend() {
                const ctx = document.getElementById('aovTrendChart');
                if (!ctx) return;
                const data = $wire.aovTrendChart;
                if (!data || !data.labels) return;

                this.charts.aovTrend = new Chart(ctx, {
                    type: 'line',
                    data: this.getAovTrendData(),
                    options: {
                        responsive: true,
                        maintainAspectRatio: false
                    }
                });
            },
            getAovTrendData() {
                const data = $wire.aovTrendChart;
                return {
                    labels: data.labels || [],
                    datasets: [{
                        label: 'Rata-rata Keranjang (AOV)',
                        data: data.data || [],
                        borderColor: '#0ea5e9',
                        backgroundColor: 'rgba(14, 165, 233, 0.1)',
                        fill: true,
                        tension: 0.3
                    }]
                };
            },
            updateAovTrend() {
                if (this.charts.aovTrend) {
                    this.charts.aovTrend.data = this.getAovTrendData();
                    this.charts.aovTrend.update();
                } else {
                    this.initAovTrend();
                }
            },

            initExpenseBreakdown() {
                const ctx = document.getElementById('expenseBreakdownChart');
                if (!ctx) return;
                const data = $wire.expenseBreakdownChart;
                if (!data || !data.labels) return;

                this.charts.expenseBreakdown = new Chart(ctx, {
                    type: 'doughnut',
                    data: this.getExpenseBreakdownData(),
                    options: {
                        responsive: true,
                        maintainAspectRatio: false
                    }
                });
            },
            getExpenseBreakdownData() {
                const data = $wire.expenseBreakdownChart;
                return {
                    labels: data.labels || [],
                    datasets: [{
                        data: data.data || [],
                        backgroundColor: ['#fb923c', '#4ade80']
                    }]
                };
            },
            updateExpenseBreakdown() {
                if (this.charts.expenseBreakdown) {
                    this.charts.expenseBreakdown.data = this.getExpenseBreakdownData();
                    this.charts.expenseBreakdown.update();
                } else {
                    this.initExpenseBreakdown();
                }
            },

            initRevenueVsCost() {
                const ctx = document.getElementById('revenueVsCostChart');
                if (!ctx) return;
                const data = $wire.revenueVsCostChart;
                if (!data || !data.labels) return;

                this.charts.revenueVsCost = new Chart(ctx, {
                    type: 'bar',
                    data: this.getRevenueVsCostData(),
                    options: {
                        responsive: true,
                        maintainAspectRatio: false
                    }
                });
            },
            getRevenueVsCostData() {
                const data = $wire.revenueVsCostChart;
                return {
                    labels: data.labels || [],
                    datasets: [{
                        label: 'Total Nilai',
                        data: data.data || [],
                        backgroundColor: ['#10b981', '#ef4444']
                    }]
                };
            },
            updateRevenueVsCost() {
                if (this.charts.revenueVsCost) {
                    this.charts.revenueVsCost.data = this.getRevenueVsCostData();
                    this.charts.revenueVsCost.update();
                } else {
                    this.initRevenueVsCost();
                }
            },

            initCustomerRetention() {
                const ctx = document.getElementById('customerRetentionChart');
                if (!ctx) return;
                const data = $wire.customerRetentionChart;
                if (!data || !data.labels) return;

                this.charts.customerRetention = new Chart(ctx, {
                    type: 'bar',
                    data: this.getCustomerRetentionData(),
                    options: {
                        responsive: true,
                        maintainAspectRatio: false
                    }
                });
            },
            getCustomerRetentionData() {
                const data = $wire.customerRetentionChart;
                return {
                    labels: data.labels || [],
                    datasets: [{
                        label: 'Jumlah Pelanggan',
                        data: data.data || [],
                        backgroundColor: ['#8b5cf6', '#ec4899']
                    }]
                };
            },
            updateCustomerRetention() {
                if (this.charts.customerRetention) {
                    this.charts.customerRetention.data = this.getCustomerRetentionData();
                    this.charts.customerRetention.update();
                } else {
                    this.initCustomerRetention();
                }
            },

            initVoucherUsage() {
                const ctx = document.getElementById('voucherUsageTrendChart');
                if (!ctx) return;
                const data = $wire.voucherUsageTrendChart;
                if (!data || !data.labels) return;

                this.charts.voucherUsage = new Chart(ctx, {
                    type: 'line',
                    data: this.getVoucherUsageData(),
                    options: {
                        responsive: true,
                        maintainAspectRatio: false
                    }
                });
            },
            getVoucherUsageData() {
                const data = $wire.voucherUsageTrendChart;
                return {
                    labels: data.labels || [],
                    datasets: [{
                        label: 'Voucher Terpakai',
                        data: data.data || [],
                        borderColor: '#f59e0b',
                        backgroundColor: 'rgba(245, 158, 11, 0.1)',
                        fill: true,
                        tension: 0.3
                    }]
                };
            },
            updateVoucherUsage() {
                if (this.charts.voucherUsage) {
                    this.charts.voucherUsage.data = this.getVoucherUsageData();
                    this.charts.voucherUsage.update();
                } else {
                    this.initVoucherUsage();
                }
            }
        }));
    </script>
@endscript
