<div class="web-analytics-container container-fluid p-0">
    <style>
        .web-analytics-container {
            background-color: #f8f9fa;
            min-height: 100vh;
        }
        .premium-card {
            border: none;
            border-radius: 16px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.03);
            transition: all 0.3s ease;
            margin-bottom: 24px;
            background: #fff;
            overflow: hidden;
        }
        .premium-card:hover {
            transform: translateY(-4px);
            box-shadow: 0 15px 35px rgba(0,0,0,0.06);
        }
        .icon-box {
            width: 56px;
            height: 56px;
            border-radius: 14px;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-bottom: 20px;
            font-size: 1.5rem;
            transition: transform 0.3s ease;
        }
        .premium-card:hover .icon-box {
            transform: scale(1.1);
        }
        .metric-value {
            font-size: 2.2rem;
            font-weight: 700;
            color: #1e293b;
            line-height: 1.2;
            margin-bottom: 4px;
            font-family: 'Poppins', sans-serif;
        }
        .metric-label {
            font-size: 0.85rem;
            color: #64748b;
            text-transform: uppercase;
            letter-spacing: 0.75px;
            font-weight: 600;
        }
        .chart-container {
            min-height: 380px;
        }
        .filter-header {
            background: #fff;
            padding: 24px;
            border-radius: 16px;
            border: 1px solid rgba(226, 232, 240, 0.8);
            margin-bottom: 30px;
        }
        .source-pill {
            padding: 6px 12px;
            border-radius: 30px;
            font-size: 0.75rem;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            display: inline-block;
        }
        .source-direct { background: #e0f2fe; color: #0369a1; }
        .source-searchengine { background: #dcfce7; color: #15803d; }
        .source-social { background: #fef9c3; color: #a16207; }
        .source-referral { background: #f3e8ff; color: #7e22ce; }
        .source-video { background: #fee2e2; color: #b91c1c; }
        .source-ad { background: #ffedd5; color: #c2410c; }
        
        .progress-bar-custom {
            height: 8px;
            border-radius: 4px;
            background-color: #f1f5f9;
            overflow: hidden;
            margin-top: 6px;
        }
        .progress-bar-fill {
            height: 100%;
            border-radius: 4px;
            transition: width 0.6s ease;
        }
    </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" style="color: #0f172a; font-family: 'Poppins', sans-serif;">Web Analytics & Traffic Report</h1>
            <p class="text-muted small mb-0">Monitor visitors, page views, bounce rate, session duration, and traffic sources in real-time</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 bg-light border-end-0"><i class="bi bi-calendar3"></i></span>
                <input type="date" wire:model.live="startDate" class="form-control bg-light border-start-0 ps-0">
                <input type="date" wire:model.live="endDate" class="form-control bg-light border-start-0 ps-0">
            </div>
            <select wire:model.live="filter" class="form-select form-select-sm bg-light" 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 rounded-3" wire:click="loadData">
                <i class="bi bi-arrow-clockwise me-1"></i> Refresh
            </button>
            <a href="{{ route('admin.analytics.download-pdf', ['start_date' => $startDate, 'end_date' => $endDate, 'filter' => $filter]) }}" target="_blank" class="btn btn-danger btn-sm px-4 rounded-3">
                <i class="bi bi-file-earmark-pdf me-1"></i> Export PDF
            </a>
        </div>
    </div>

    <!-- Main Metrics -->
    <div class="row">
        <!-- Metric 1: Visitors -->
        <div class="col-xl-3 col-md-6">
            <div class="card premium-card p-4">
                <div class="d-flex justify-content-between align-items-start">
                    <div>
                        <div class="metric-label">Unique Visitors</div>
                        <div class="metric-value mt-2">{{ number_format($metrics['visitors']) }}</div>
                    </div>
                    <div class="icon-box" style="background: #eff6ff; color: #2563eb;">
                        <i class="bi bi-people-fill"></i>
                    </div>
                </div>
                <div class="mt-2 small text-muted">
                    <span class="text-success fw-bold"><i class="bi bi-arrow-up-right me-1"></i>Active</span> users on website
                </div>
            </div>
        </div>

        <!-- Metric 2: Page Views -->
        <div class="col-xl-3 col-md-6">
            <div class="card premium-card p-4">
                <div class="d-flex justify-content-between align-items-start">
                    <div>
                        <div class="metric-label">Page Views</div>
                        <div class="metric-value mt-2">{{ number_format($metrics['pageViews']) }}</div>
                    </div>
                    <div class="icon-box" style="background: #ecfdf5; color: #10b981;">
                        <i class="bi bi-eye-fill"></i>
                    </div>
                </div>
                <div class="mt-2 small text-muted">
                    Avg. <span class="fw-semibold text-dark">{{ $metrics['visitors'] > 0 ? round($metrics['pageViews'] / $metrics['visitors'], 1) : 0 }}</span> views per visitor
                </div>
            </div>
        </div>

        <!-- Metric 3: Bounce Rate -->
        <div class="col-xl-3 col-md-6">
            <div class="card premium-card p-4">
                <div class="d-flex justify-content-between align-items-start">
                    <div>
                        <div class="metric-label">Bounce Rate</div>
                        <div class="metric-value mt-2">{{ $metrics['bounceRate'] }}%</div>
                    </div>
                    <div class="icon-box" style="background: #fff7ed; color: #f97316;">
                        <i class="bi bi-arrow-down-left-circle-fill"></i>
                    </div>
                </div>
                <div class="mt-2 small text-muted">
                    Single-page session percentage
                </div>
            </div>
        </div>

        <!-- Metric 4: Session Duration -->
        <div class="col-xl-3 col-md-6">
            <div class="card premium-card p-4">
                <div class="d-flex justify-content-between align-items-start">
                    <div>
                        <div class="metric-label">Avg. Session Duration</div>
                        <div class="metric-value mt-2">{{ $metrics['avgSessionDuration'] }}</div>
                    </div>
                    <div class="icon-box" style="background: #faf5ff; color: #8b5cf6;">
                        <i class="bi bi-clock-fill"></i>
                    </div>
                </div>
                <div class="mt-2 small text-muted">
                    Total active time on site
                </div>
            </div>
        </div>
    </div>

    <!-- Charts Section -->
    <div class="row">
        <!-- Traffic Trend Chart -->
        <div class="col-lg-8">
            <div class="card premium-card p-4">
                <div class="d-flex justify-content-between align-items-center mb-4">
                    <div>
                        <h5 class="fw-bold text-dark mb-1">Traffic Overview & Volume</h5>
                        <p class="text-muted small mb-0">Compare unique visitors and total page views over time</p>
                    </div>
                    <span class="badge bg-light text-dark text-capitalize px-3 py-2 rounded-pill">{{ $filter }} View</span>
                </div>
                <div class="card-body p-0">
                    <div id="webTrafficChart" class="chart-container" wire:ignore></div>
                </div>
            </div>
        </div>

        <!-- Traffic Sources Chart -->
        <div class="col-lg-4">
            <div class="card premium-card p-4">
                <div class="mb-4">
                    <h5 class="fw-bold text-dark mb-1">Traffic Sources</h5>
                    <p class="text-muted small mb-0">Understand where your audience originates</p>
                </div>
                <div class="card-body p-0 d-flex flex-column align-items-center justify-content-center">
                    <div id="webSourcesChart" style="min-height: 280px; width: 100%;" wire:ignore></div>
                </div>
            </div>
        </div>
    </div>

    <!-- Tables Section -->
    <div class="row">
        <!-- Traffic Sources Breakdown -->
        <div class="col-lg-6">
            <div class="card premium-card">
                <div class="card-header bg-transparent border-0 pt-4 px-4 pb-2">
                    <h5 class="fw-bold text-dark mb-1">Traffic Sources Breakdown</h5>
                    <p class="text-muted small mb-0">Detailed metrics of user acquisition methods</p>
                </div>
                <div class="card-body px-4">
                    <div class="table-responsive">
                        <table class="table table-hover align-middle mb-0">
                            <thead>
                                <tr class="text-muted small" style="border-bottom: 2px solid #f1f5f9;">
                                    <th>Acquisition Source</th>
                                    <th class="text-center">Total Sessions</th>
                                    <th class="text-end">Percentage Share</th>
                                </tr>
                            </thead>
                            <tbody>
                                @php
                                    $sourceLabels = [
                                        'direct' => 'Direct Traffic',
                                        'searchengine' => 'Search Engine',
                                        'social' => 'Social Media',
                                        'referral' => 'Referrals',
                                        'video' => 'Video Traffic',
                                        'ad' => 'Paid Advertising'
                                    ];
                                @endphp
                                @forelse($trafficSources as $src)
                                    @php
                                        $pct = $metrics['visitors'] > 0 ? round(($src['count'] / $metrics['visitors']) * 100, 1) : 0;
                                        $color = '#2563eb';
                                        if($src['source'] == 'searchengine') $color = '#10b981';
                                        if($src['source'] == 'social') $color = '#eab308';
                                        if($src['source'] == 'referral') $color = '#a855f7';
                                        if($src['source'] == 'video') $color = '#ef4444';
                                        if($src['source'] == 'ad') $color = '#f97316';
                                    @endphp
                                    <tr>
                                        <td>
                                            <span class="source-pill source-{{ $src['source'] }}">
                                                {{ $sourceLabels[$src['source']] ?? ucfirst($src['source']) }}
                                            </span>
                                        </td>
                                        <td class="text-center fw-bold text-dark">{{ number_format($src['count']) }}</td>
                                        <td class="text-end">
                                            <div class="d-flex align-items-center justify-content-end gap-3">
                                                <span class="fw-bold text-dark">{{ $pct }}%</span>
                                                <div class="progress-bar-custom" style="width: 80px;">
                                                    <div class="progress-bar-fill" style="width: {{ $pct }}%; background-color: {{ $color }};"></div>
                                                </div>
                                            </div>
                                        </td>
                                    </tr>
                                @empty
                                    <tr>
                                        <td colspan="3" class="text-center py-4 text-muted small">No traffic source data available</td>
                                    </tr>
                                @endforelse
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>

        <!-- Top Referring Domains -->
        <div class="col-lg-6">
            <div class="card premium-card">
                <div class="card-header bg-transparent border-0 pt-4 px-4 pb-2">
                    <h5 class="fw-bold text-dark mb-1">Top Referring Domains</h5>
                    <p class="text-muted small mb-0">Websites driving external referral traffic to your store</p>
                </div>
                <div class="card-body px-4">
                    <div class="table-responsive" style="max-height: 380px; overflow-y: auto;">
                        <table class="table table-hover align-middle mb-0">
                            <thead>
                                <tr class="text-muted small" style="border-bottom: 2px solid #f1f5f9;">
                                    <th>Referring Website</th>
                                    <th class="text-end">Total Referrals</th>
                                </tr>
                            </thead>
                            <tbody>
                                @forelse($topReferrers as $ref)
                                    <tr>
                                        <td>
                                            <div class="d-flex align-items-center">
                                                <div class="bg-light text-primary rounded-3 p-2 me-3 d-flex align-items-center justify-content-center" style="width: 38px; height: 38px;">
                                                    <i class="bi bi-globe"></i>
                                                </div>
                                                <div>
                                                    <div class="fw-bold text-dark small">{{ $ref['host'] }}</div>
                                                    <a href="{{ $ref['url'] }}" target="_blank" class="text-muted font-monospace small text-truncate d-inline-block" style="max-width: 250px; font-size: 0.75rem;">
                                                        {{ $ref['url'] }}
                                                    </a>
                                                </div>
                                            </div>
                                        </td>
                                        <td class="text-end fw-bold text-success">{{ number_format($ref['count']) }}</td>
                                    </tr>
                                @empty
                                    <tr>
                                        <td colspan="2" class="text-center py-4 text-muted small">No referring domains logged for this period</td>
                                    </tr>
                                @endforelse
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>

    @script
    <script>
        let webTrafficChart, webSourcesChart;

        function initWebCharts(trafficData, sourcesData) {
            // Theme setup
            const chartTheme = {
                fontFamily: "'Poppins', sans-serif"
            };

            // 1. Traffic History Area Chart
            const trafficOptions = {
                series: [
                    { name: 'Unique Visitors', data: trafficData.visitors },
                    { name: 'Page Views', data: trafficData.page_views }
                ],
                chart: {
                    type: 'area',
                    height: 350,
                    fontFamily: chartTheme.fontFamily,
                    toolbar: { show: false },
                    zoom: { enabled: false }
                },
                dataLabels: { enabled: false },
                stroke: { curve: 'smooth', width: [3, 3] },
                colors: ['#2563eb', '#10b981'],
                fill: {
                    type: 'gradient',
                    gradient: {
                        shadeIntensity: 1,
                        opacityFrom: [0.3, 0.2],
                        opacityTo: [0.05, 0.02],
                        stops: [0, 90, 100]
                    }
                },
                xaxis: {
                    categories: trafficData.labels,
                    axisBorder: { show: false },
                    axisTicks: { show: false }
                },
                grid: {
                    borderColor: '#f1f5f9',
                    strokeDashArray: 4
                },
                yaxis: {
                    labels: {
                        formatter: (val) => Math.round(val).toLocaleString()
                    }
                },
                tooltip: {
                    x: { show: true }
                }
            };

            // 2. Traffic Sources Donut Chart
            const sourceLabels = {
                'direct': 'Direct',
                'searchengine': 'Search Engine',
                'social': 'Social Media',
                'referral': 'Referral',
                'video': 'Video',
                'ad': 'Paid Ads'
            };

            const sourceColors = {
                'direct': '#2563eb',
                'searchengine': '#10b981',
                'social': '#eab308',
                'referral': '#a855f7',
                'video': '#ef4444',
                'ad': '#f97316'
            };

            const seriesData = [];
            const labelData = [];
            const colorData = [];

            sourcesData.forEach(item => {
                seriesData.push(item.count);
                labelData.push(sourceLabels[item.source] || item.source);
                colorData.push(sourceColors[item.source] || '#64748b');
            });

            // Fallback for empty sources
            if (seriesData.length === 0) {
                seriesData.push(1);
                labelData.push('No Data');
                colorData.push('#cbd5e1');
            }

            const sourcesOptions = {
                series: seriesData,
                labels: labelData,
                chart: {
                    type: 'donut',
                    height: 280,
                    fontFamily: chartTheme.fontFamily
                },
                colors: colorData,
                legend: {
                    position: 'bottom',
                    fontSize: '12px'
                },
                plotOptions: {
                    pie: {
                        donut: {
                            size: '70%',
                            labels: {
                                show: true,
                                total: {
                                    show: true,
                                    label: 'Total Sessions',
                                    formatter: (w) => {
                                        const sum = w.globals.seriesTotals.reduce((a, b) => a + b, 0);
                                        return sum.toLocaleString();
                                    }
                                }
                            }
                        }
                    }
                },
                dataLabels: { enabled: false },
                tooltip: {
                    y: {
                        formatter: (val) => val.toLocaleString() + ' sessions'
                    }
                }
            };

            // Destroy existing charts to reload
            if (webTrafficChart) webTrafficChart.destroy();
            if (webSourcesChart) webSourcesChart.destroy();

            webTrafficChart = new ApexCharts(document.querySelector("#webTrafficChart"), trafficOptions);
            webSourcesChart = new ApexCharts(document.querySelector("#webSourcesChart"), sourcesOptions);

            webTrafficChart.render();
            webSourcesChart.render();
        }

        // Initial setup
        document.addEventListener("DOMContentLoaded", () => {
            initWebCharts($wire.chartData, $wire.trafficSources);
        });

        // Listen for updates from Livewire
        $wire.on('refreshWebCharts', (data) => {
            initWebCharts(data[0].traffic, data[0].sources);
        });
    </script>
    @endscript
</div>
