@extends('layouts.admin')

@section('title', 'Analytics')

@push('css')
    <style>
        .an-grid { display: grid; grid-template-columns: repeat(12, 1fr); gap: 16px; align-items: stretch; }
        .an-card { background: var(--loot-surface, #101a15); border: 1px solid var(--loot-border, rgba(255,255,255,.07)); border-radius: 16px; padding: 16px 18px; display: flex; flex-direction: column; min-width: 0; }
        .an-card .chart-body { flex: 1 1 auto; min-height: 0; width: 100%; }
        .an-8 { grid-column: span 8; } .an-6 { grid-column: span 6; } .an-4 { grid-column: span 4; } .an-12 { grid-column: span 12; }
        .an-head { display:flex; align-items:center; justify-content:space-between; gap:10px; margin-bottom:10px; flex-wrap:wrap; }
        .an-head h3 { font-size:15px; font-weight:800; margin:0; color: var(--loot-text,#eafff5); }
        .an-head .loot-muted { font-size:12px; }

        .an-kpi-grid { display:grid; grid-template-columns:repeat(4,minmax(0,1fr)); gap:14px; }
        .an-kpi { display:flex; min-width:0; min-height:132px; padding:20px; flex-direction:column; justify-content:center; background:var(--loot-surface,#101a15); border:1px solid var(--loot-border,rgba(255,255,255,.07)); border-radius:14px; }
        .an-kpi span { display:block; color:#9fb6ac; font-size:12px; font-weight:700; }
        .an-kpi strong { display:block; margin-top:7px; color:var(--loot-text,#eafff5); font-size:clamp(1.4rem,2vw,2.05rem); font-weight:900; line-height:1.08; overflow-wrap:anywhere; font-variant-numeric:tabular-nums; }

        .an-filters { display:flex; align-items:flex-end; gap:12px; flex-wrap:wrap; }
        .an-filters .field { display:flex; flex-direction:column; gap:4px; }
        .an-filters label { font-size:11px; color:#9fb6ac; font-weight:700; }
        .an-filters input[type=date] { background:rgba(255,255,255,.05); border:1px solid var(--loot-border, rgba(255,255,255,.1)); color: var(--loot-text,#eafff5); border-radius:10px; padding:8px 10px; font-size:13px; color-scheme: dark; }
        .an-presets { display:inline-flex; gap:4px; flex-wrap:wrap; }
        .an-presets a { padding:7px 12px; border-radius:9px; font-size:12px; font-weight:700; color:#9fb6ac; text-decoration:none; background:rgba(255,255,255,.05); }
        .an-presets a:hover { color:var(--loot-text,#eafff5); }

        .an-table-wrap { overflow-x:auto; }
        table.an-table { width:100%; border-collapse:collapse; font-size:13px; }
        table.an-table th, table.an-table td { padding:9px 12px; text-align:left; white-space:nowrap; border-bottom:1px solid rgba(255,255,255,.05); }
        table.an-table th { color:#9fb6ac; font-weight:700; font-size:11px; text-transform:uppercase; letter-spacing:.4px; }
        table.an-table td { color: var(--loot-text,#eafff5); }
        table.an-table tbody tr:hover { background: rgba(255,255,255,.03); }
        .an-bar { height:6px; border-radius:4px; background: var(--loot-green,#22c55e); display:inline-block; vertical-align:middle; }

        @media (max-width: 1199px) { .an-8 { grid-column: span 12; } .an-6 { grid-column: span 6; } .an-4 { grid-column: span 6; } .an-kpi-grid { grid-template-columns:repeat(2,minmax(0,1fr)); } }
        @media (max-width: 767px) { .an-grid { gap:12px; } .an-8, .an-6, .an-4, .an-12 { grid-column: span 12; } .an-kpi-grid { grid-template-columns:1fr; } }
    </style>
@endpush

@section('content')
    <div class="d-flex flex-wrap justify-content-between align-items-center gap-1 mb-2">
        <div>
            <span class="loot-pill mb-1"><i data-feather="bar-chart-2"></i> Insights</span>
            <h1 class="loot-section-title mb-25">Analytics</h1>
            <p class="loot-muted mb-0">Date-range analytics for users, leads, offers, offerwalls, revenue, cashouts and more.</p>
        </div>
        <a class="btn btn-loot" href="{{ route('admin.export.all') }}"
           title="Download a ZIP with a lifetime CSV of every table: users, leads, withdrawals, logs, analytics and more.">
            <i data-feather="database" class="me-50"></i>Export all data (lifetime)
        </a>
    </div>

    {{-- Date range --}}
    <div class="an-card mb-2">
        <form method="GET" action="{{ route('admin.analytics') }}" class="an-filters">
            <div class="field">
                <label for="from">From</label>
                <input type="date" id="from" name="from" value="{{ $a['range']['from'] }}" max="{{ now()->toDateString() }}">
            </div>
            <div class="field">
                <label for="to">To</label>
                <input type="date" id="to" name="to" value="{{ $a['range']['to'] }}" max="{{ now()->toDateString() }}">
            </div>
            <button class="btn btn-loot"><i data-feather="filter" class="me-50"></i>Apply</button>
            <div class="an-presets">
                @php
                    $presets = [
                        '7 days' => [now()->subDays(6), now()],
                        '30 days' => [now()->subDays(29), now()],
                        '90 days' => [now()->subDays(89), now()],
                        'This month' => [now()->startOfMonth(), now()],
                        'Last month' => [now()->subMonthNoOverflow()->startOfMonth(), now()->subMonthNoOverflow()->endOfMonth()],
                        'This year' => [now()->startOfYear(), now()],
                    ];
                @endphp
                @foreach($presets as $name => [$pf, $pt])
                    <a href="{{ route('admin.analytics', ['from' => $pf->toDateString(), 'to' => $pt->toDateString()]) }}">{{ $name }}</a>
                @endforeach
            </div>
        </form>
        <div class="loot-muted mt-1" style="font-size:12px;">Showing {{ $a['range']['days'] }} day(s): {{ $a['range']['from'] }} → {{ $a['range']['to'] }}</div>
    </div>

    {{-- KPIs --}}
    @php $s = $a['summary']; @endphp
    <div class="an-kpi-grid mb-2">
        <div class="an-kpi"><span>Signups</span><strong>{{ number_format($s['signups']) }}</strong></div>
        <div class="an-kpi"><span>Active users</span><strong>{{ number_format($s['active_users']) }}</strong></div>
        <div class="an-kpi"><span>Leads</span><strong>{{ number_format($s['leads']) }}</strong></div>
        <div class="an-kpi"><span>Approved leads</span><strong>{{ number_format($s['approved_leads']) }}</strong></div>
        <div class="an-kpi"><span>Revenue</span><strong>${{ number_format($s['revenue'], 2) }}</strong></div>
        <div class="an-kpi"><span>Coins awarded</span><strong>{{ number_format($s['coins_awarded']) }}</strong></div>
        <div class="an-kpi"><span>Offer clicks</span><strong>{{ number_format($s['clicks']) }}</strong></div>
        <div class="an-kpi"><span>Cashout requested</span><strong>{{ number_format($s['cashout_requested']) }}</strong></div>
        <div class="an-kpi"><span>Cashout paid</span><strong>{{ number_format($s['cashout_paid']) }}</strong></div>
        <div class="an-kpi"><span>Cashout requests</span><strong>{{ number_format($s['new_cashouts']) }}</strong></div>
    </div>

    {{-- Charts --}}
    <div class="an-grid mb-2">
        <div class="an-card an-8">
            <div class="an-head"><h3>Signups, leads &amp; revenue</h3><span class="loot-muted">{{ $a['range']['days'] }} days</span></div>
            <div class="chart-body" id="anTrend"></div>
        </div>
        <div class="an-card an-4">
            <div class="an-head"><h3>Lead status</h3></div>
            <div class="chart-body" id="anLeadStatus"></div>
        </div>
        <div class="an-card an-4">
            <div class="an-head"><h3>Cashouts</h3></div>
            <div class="chart-body" id="anCashouts"></div>
        </div>
        <div class="an-card an-8">
            <div class="an-head"><h3>Top countries</h3><span class="loot-muted">by leads</span></div>
            <div class="chart-body" id="anCountries"></div>
        </div>
    </div>

    {{-- Offerwall performance --}}
    <div class="an-card mb-2">
        <div class="an-head">
            <h3>Offerwall performance</h3>
            <a class="btn btn-sm btn-outline-light" href="{{ route('admin.analytics.export.offerwalls', ['from' => $a['range']['from'], 'to' => $a['range']['to']]) }}">
                <i data-feather="download" class="me-50"></i>Export CSV
            </a>
        </div>
        <div class="an-table-wrap">
            <table class="an-table">
                <thead><tr><th>Offerwall</th><th>Type</th><th>Clicks</th><th>Leads</th><th>Approved</th><th>Conversion</th><th>Revenue</th><th>Coins</th></tr></thead>
                <tbody>
                    @php $maxRev = max(1, $a['offerwalls']->max('revenue')); @endphp
                    @forelse($a['offerwalls'] as $w)
                        <tr>
                            <td><strong>{{ $w['name'] }}</strong> @unless($w['is_active'])<span class="badge badge-light-secondary">off</span>@endunless</td>
                            <td class="text-capitalize">{{ $w['type'] ?? '—' }}</td>
                            <td>{{ number_format($w['clicks']) }}</td>
                            <td>{{ number_format($w['leads']) }}</td>
                            <td>{{ number_format($w['approved']) }}</td>
                            <td>{{ $w['conversion'] }}%</td>
                            <td>
                                <span class="an-bar" style="width: {{ max(4, (int) round(($w['revenue'] / $maxRev) * 90)) }}px"></span>
                                ${{ number_format($w['revenue'], 2) }}
                            </td>
                            <td>{{ number_format($w['coins']) }}</td>
                        </tr>
                    @empty
                        <tr><td colspan="8" class="text-center loot-muted py-3">No offerwall activity in this range.</td></tr>
                    @endforelse
                </tbody>
            </table>
        </div>
    </div>

    {{-- Top offers + top users --}}
    <div class="an-grid">
        <div class="an-card an-6">
            <div class="an-head">
                <h3>Top offers</h3>
                <a class="btn btn-sm btn-outline-light" href="{{ route('admin.analytics.export.offers', ['from' => $a['range']['from'], 'to' => $a['range']['to']]) }}">
                    <i data-feather="download" class="me-50"></i>Export CSV
                </a>
            </div>
            <div class="an-table-wrap">
                <table class="an-table">
                    <thead><tr><th>Offer</th><th>Provider</th><th>Conv.</th><th>Revenue</th></tr></thead>
                    <tbody>
                        @forelse($a['top_offers'] as $o)
                            <tr>
                                <td>{{ \Str::limit($o['offer'], 40) }}</td>
                                <td>{{ $o['provider'] }}</td>
                                <td>{{ number_format($o['conversions']) }}</td>
                                <td>${{ number_format($o['revenue'], 2) }}</td>
                            </tr>
                        @empty
                            <tr><td colspan="4" class="text-center loot-muted py-3">No offer conversions in this range.</td></tr>
                        @endforelse
                    </tbody>
                </table>
            </div>
        </div>
        <div class="an-card an-6">
            <div class="an-head"><h3>Top earners</h3><span class="loot-muted">approved conversions</span></div>
            <div class="an-table-wrap">
                <table class="an-table">
                    <thead><tr><th>User</th><th>Conv.</th><th>Coins</th><th>Revenue</th></tr></thead>
                    <tbody>
                        @forelse($a['top_users'] as $u)
                            <tr>
                                <td>{{ $u['username'] }}</td>
                                <td>{{ number_format($u['conversions']) }}</td>
                                <td>{{ number_format($u['coins']) }}</td>
                                <td>${{ number_format($u['revenue'], 2) }}</td>
                            </tr>
                        @empty
                            <tr><td colspan="4" class="text-center loot-muted py-3">No earners in this range.</td></tr>
                        @endforelse
                    </tbody>
                </table>
            </div>
        </div>
    </div>
@endsection

@push('scripts')
    <script src="{{ asset('app-assets/vendors/js/charts/apexcharts.min.js') }}"></script>
    <script>
        (function () {
            if (typeof ApexCharts === 'undefined') return;
            const a = @json($a);
            const css = getComputedStyle(document.documentElement);
            const green = css.getPropertyValue('--loot-green').trim() || '#22c55e';
            const blue = css.getPropertyValue('--loot-blue').trim() || '#86efac';
            const amber = '#f7b731', red = '#ff6b6b', muted = '#9fb6ac', grid = 'rgba(255,255,255,.06)';
            const H = 260;
            const baseAxis = { labels: { style: { colors: muted, fontSize: '11px' } }, axisBorder: { show: false }, axisTicks: { show: false } };
            const responsive = [{ breakpoint: 576, options: { chart: { height: 240 }, legend: { fontSize: '10px' } } }];

            new ApexCharts(document.querySelector('#anTrend'), {
                chart: { type: 'area', height: 300, toolbar: { show: false }, fontFamily: 'inherit', stacked: false },
                series: [
                    { name: 'Signups', type: 'area', data: a.series.signups },
                    { name: 'Leads', type: 'area', data: a.series.leads },
                    { name: 'Revenue $', type: 'line', data: a.series.revenue },
                ],
                colors: [green, blue, amber],
                stroke: { curve: 'smooth', width: [2, 2, 3] },
                fill: { type: ['gradient', 'gradient', 'solid'], gradient: { opacityFrom: 0.3, opacityTo: 0.02 } },
                dataLabels: { enabled: false },
                grid: { borderColor: grid, strokeDashArray: 4, padding: { left: 8, right: 8 } },
                xaxis: Object.assign({ categories: a.series.labels, tickAmount: 8 }, baseAxis),
                yaxis: [
                    { seriesName: 'Signups', labels: { style: { colors: muted, fontSize: '11px' } } },
                    { seriesName: 'Signups', show: false },
                    { opposite: true, labels: { style: { colors: muted, fontSize: '11px' }, formatter: (v) => '$' + Number(v).toFixed(0) } },
                ],
                legend: { labels: { colors: muted } },
                tooltip: { theme: 'dark' },
                responsive,
            }).render();

            const donut = (values, labels, colors, empty) => ({
                chart: { type: 'donut', height: H, fontFamily: 'inherit' },
                series: values, labels, colors, stroke: { width: 0 },
                legend: { position: 'bottom', fontSize: '11px', labels: { colors: muted } },
                dataLabels: { enabled: true, style: { fontSize: '11px', fontWeight: 700 } },
                plotOptions: { pie: { donut: { size: '64%', labels: { show: true, total: { show: true, color: muted, fontSize: '12px', label: 'Total' } } } } },
                tooltip: { theme: 'dark' }, noData: { text: empty || 'No data', style: { color: muted } }, responsive,
            });
            new ApexCharts(document.querySelector('#anLeadStatus'), donut(a.lead_status.values, a.lead_status.labels, [green, amber, red], 'No leads')).render();
            new ApexCharts(document.querySelector('#anCashouts'), donut(a.cashouts.values, a.cashouts.labels, [amber, green, red], 'No cashouts')).render();

            new ApexCharts(document.querySelector('#anCountries'), {
                chart: { type: 'bar', height: H, toolbar: { show: false }, fontFamily: 'inherit' },
                series: [{ name: 'Leads', data: a.countries.values }],
                colors: [blue],
                plotOptions: { bar: { borderRadius: 5, horizontal: true, barHeight: '60%' } },
                dataLabels: { enabled: false },
                grid: { borderColor: grid, strokeDashArray: 4 },
                xaxis: Object.assign({ categories: a.countries.labels }, baseAxis),
                yaxis: { labels: { style: { colors: muted, fontSize: '11px' } } },
                tooltip: { theme: 'dark' }, noData: { text: 'No country data', style: { color: muted } }, responsive,
            }).render();
        })();
    </script>
@endpush
