<div class="analytics-container container-fluid p-0">
    <style>
        .analytics-container {
            background-color: #f8f9fa;
            min-height: 100vh;
        }
        .premium-card {
            border: none;
            border-radius: 12px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.05);
            transition: transform 0.3s ease;
            margin-bottom: 24px;
            background: #fff;
        }
        .premium-card:hover { transform: translateY(-3px); }
        .icon-box {
            width: 48px;
            height: 48px;
            border-radius: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-bottom: 15px;
        }
        .metric-value { font-size: 1.8rem; font-weight: 700; color: #2c3e50; }
        .metric-label { font-size: 0.9rem; color: #7f8c8d; text-transform: uppercase; letter-spacing: 0.5px; }
        .chart-container { min-height: 350px; }
        .filter-header {
            background: #fff;
            padding: 20px;
            border-bottom: 1px solid #edf2f7;
            margin-bottom: 30px;
            border-radius: 12px;
        }
        .status-badge {
            padding: 5px 12px;
            border-radius: 20px;
            font-size: 0.75rem;
            font-weight: 600;
        }
        .product-img {
            width: 40px;
            height: 40px;
            border-radius: 8px;
            object-fit: cover;
        }
    </style>

    <!-- Header & Filters -->
    <div class="filter-header d-flex flex-wrap justify-content-between align-items-center shadow-sm">
        <div>
            <h1 class="h3 fw-bold mb-1">Business Analytics</h1>
            <p class="text-muted small mb-0">Deep dive into your store's performance metrics</p>
        </div>
        <div class="d-flex gap-3 align-items-center mt-3 mt-md-0">
            <div class="input-group input-group-sm">
                <span class="input-group-text"><i class="bi bi-calendar3"></i></span>
                <input type="date" wire:model.live="startDate" class="form-control">
                <input type="date" wire:model.live="endDate" class="form-control">
            </div>
            <select wire:model.live="filter" class="form-select form-select-sm" style="width: auto;">
                <option value="daily">Last 30 Days</option>
                <option value="monthly">Last 12 Months</option>
                <option value="custom">Custom Range</option>
            </select>
            <button class="btn btn-primary btn-sm px-4" wire:click="loadData">
                <i class="bi bi-arrow-clockwise me-1"></i> Refresh
            </button>
        </div>
    </div>

    <!-- Main Metrics -->
    <div class="row px-3">
        @php
            $cards = [
                ['label' => 'Total Revenue', 'value' => 'LKR ' . number_format($metrics['totalSales'], 2), 'icon' => 'bi-currency-dollar', 'bg' => '#e3f2fd', 'color' => '#1976d2'],
                ['label' => 'Total Orders', 'value' => $metrics['totalOrders'], 'icon' => 'bi-cart-check', 'bg' => '#e8f5e9', 'color' => '#388e3c'],
                ['label' => 'Avg Order Value', 'value' => 'LKR ' . number_format($metrics['avgOrderValue'], 2), 'icon' => 'bi-basket', 'bg' => '#f3e5f5', 'color' => '#7b1fa2'],
                ['label' => 'Est. Profit', 'value' => 'LKR ' . number_format($metrics['totalProfit'], 2), 'icon' => 'bi-graph-up-arrow', 'bg' => '#fff3e0', 'color' => '#f57c00'],
            ];
        @endphp

        @foreach($cards as $card)
        <div class="col-xl-3 col-md-6">
            <div class="card premium-card p-3">
                <div class="icon-box" style="background: {{ $card['bg'] }}; color: {{ $card['color'] }};">
                    <i class="bi {{ $card['icon'] }} fs-4"></i>
                </div>
                <div class="metric-label">{{ $card['label'] }}</div>
                <div class="metric-value">{{ $card['value'] }}</div>
            </div>
        </div>
        @endforeach
    </div>

    <!-- Charts Section -->
    <div class="row px-3">
        <div class="col-lg-8">
            <div class="card premium-card">
                <div class="card-header bg-transparent border-0 pt-4 px-4 d-flex justify-content-between">
                    <h5 class="fw-bold mb-0">Revenue Trend</h5>
                    <div class="badge bg-light text-dark text-capitalize">{{ $filter }} View</div>
                </div>
                <div class="card-body">
                    <div id="salesChart" class="chart-container"></div>
                </div>
            </div>
        </div>
        <div class="col-lg-4">
            <div class="card premium-card">
                <div class="card-header bg-transparent border-0 pt-4 px-4">
                    <h5 class="fw-bold mb-0">Profit & Margin</h5>
                </div>
                <div class="card-body">
                    <div id="profitChart" class="chart-container"></div>
                </div>
            </div>
        </div>
    </div>

    <!-- Products Section -->
    <div class="row px-3">
        <div class="col-12">
            <div class="card premium-card overflow-hidden">
                <div class="card-header bg-transparent py-4 px-4 d-flex justify-content-between align-items-center">
                    <h5 class="fw-bold mb-0">Top Performing Products</h5>
                    <a href="{{ route('admin.analytics.products-report') }}?filter={{ $filter }}&start_date={{ $startDate }}&end_date={{ $endDate }}" class="btn btn-sm btn-outline-primary">View Full Report</a>
                </div>
                <div class="table-responsive">
                    <table class="table table-hover align-middle mb-0">
                        <thead class="bg-light text-muted">
                            <tr>
                                <th class="ps-4">Product Details</th>
                                <th>Category</th>
                                <th>Units Sold</th>
                                <th>Revenue Generated</th>
                                <th>Growth</th>
                                <th class="pe-4 text-center">Trend</th>
                            </tr>
                        </thead>
                        <tbody>
                            @forelse($topProducts as $item)
                            <tr>
                                <td class="ps-4">
                                    <div class="d-flex align-items-center">
                                        <div class="product-img bg-light me-3 d-flex align-items-center justify-content-center">
                                            <i class="bi bi-box-seam text-primary"></i>
                                        </div>
                                        <div>
                                            <div class="fw-bold text-dark">{{ $item->productData->product_name ?? 'Product #'.$item->product_id }}</div>
                                            <div class="text-muted small">SKU: {{ $item->productData->sku ?? 'N/A' }}</div>
                                        </div>
                                    </div>
                                </td>
                                <td><span class="status-badge bg-info-subtle text-info">Electronics</span></td>
                                <td class="fw-bold">{{ $item->total_sold }}</td>
                                <td>LKR {{ number_format($item->revenue, 2) }}</td>
                                <td><span class="text-success"><i class="bi bi-caret-up-fill me-1"></i>12%</span></td>
                                <td class="pe-4 text-center">
                                    <div class="spinner-grow spinner-grow-sm text-primary" role="status"></div>
                                </td>
                            </tr>
                            @empty
                            <tr>
                                <td colspan="6" class="text-center py-5 text-muted">No sales data recorded for this period</td>
                            </tr>
                            @endforelse
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    @script
    <script>
        let salesChart, profitChart;

        function initCharts(salesData, profitData) {
            const chartOptions = {
                chart: { type: 'area', height: 350, toolbar: { show: false }, zoom: { enabled: false } },
                dataLabels: { enabled: false },
                stroke: { curve: 'smooth', width: 3 },
                xaxis: { categories: salesData.labels, axisBorder: { show: false }, axisTicks: { show: false } },
                grid: { borderColor: '#edf2f7', strokeDashArray: 4 },
                yaxis: { labels: { formatter: (val) => 'LKR ' + val.toLocaleString() } },
                colors: ['#0061f2'],
                fill: { type: 'gradient', gradient: { shadeIntensity: 1, opacityFrom: 0.4, opacityTo: 0.1, stops: [0, 90, 100] } }
            };

            const profitOptions = {
                ...chartOptions,
                chart: { ...chartOptions.chart, type: 'bar' },
                colors: ['#f57c00'],
                xaxis: { categories: profitData.labels, axisBorder: { show: false }, axisTicks: { show: false } },
                yaxis: { labels: { formatter: (val) => 'LKR ' + val.toLocaleString() } },
            };

            if (salesChart) salesChart.destroy();
            if (profitChart) profitChart.destroy();

            salesChart = new ApexCharts(document.querySelector("#salesChart"), {
                ...chartOptions,
                series: [{ name: 'Revenue', data: salesData.series }]
            });
            profitChart = new ApexCharts(document.querySelector("#profitChart"), {
                ...profitOptions,
                series: [{ name: 'Est. Profit', data: profitData.series }]
            });

            salesChart.render();
            profitChart.render();
        }

        // Initial call
        initCharts($wire.salesChartData, $wire.profitChartData);

        // Listen for updates
        $wire.on('refreshCharts', (data) => {
            initCharts(data[0].sales, data[0].profit);
        });
    </script>
    @endscript
</div>
