@extends('layouts.admin')

@section('title', 'Admin Overview')

@push('css')
    <style>
        /* Responsive 12-col analytics grid that collapses cleanly on every device */
        .analytics-grid { display: grid; grid-template-columns: repeat(12, 1fr); gap: 16px; align-items: stretch; }
        .analytics-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;
        }
        .analytics-card .chart-body { flex: 1 1 auto; min-height: 0; width: 100%; }
        /* desktop spans */
        .a-8 { grid-column: span 8; } .a-6 { grid-column: span 6; }
        .a-4 { grid-column: span 4; } .a-12 { grid-column: span 12; }
        .analytics-head { display:flex; align-items:center; justify-content:space-between; gap:10px; margin-bottom:10px; flex-wrap:wrap; }
        .analytics-head h3 { font-size: 15px; font-weight: 800; margin: 0; color: var(--loot-text, #eafff5); }
        .analytics-head .loot-muted { font-size: 12px; }

        .analytics-mini-grid { display:grid; grid-template-columns:repeat(4,minmax(0,1fr)); gap:14px; }
        .analytics-mini {
            background: var(--loot-surface, #101a15); border:1px solid var(--loot-border, rgba(255,255,255,.07));
            display:flex; min-width:0; min-height:132px; padding:20px; flex-direction:column; justify-content:center; border-radius:14px;
        }
        .analytics-mini span { display:block; color: var(--loot-muted-color, #9fb6ac); font-size:12px; font-weight:600; }
        .analytics-mini strong { display:block; margin:7px 0 5px; color:var(--loot-text,#eafff5); font-size:clamp(1.35rem,1.9vw,2rem); font-weight:900; line-height:1.08; overflow-wrap:anywhere; font-variant-numeric:tabular-nums; }
        .analytics-trend { font-size:11px; font-weight:800; }
        .analytics-trend.up { color:#86efac; } .analytics-trend.down { color:#ff6b6b; }

        .analytics-controls { display:flex; align-items:center; gap:8px; flex-wrap:wrap; }
        .analytics-range, .analytics-type { display:inline-flex; gap:4px; background:rgba(255,255,255,.05); border-radius:10px; padding:3px; }
        .analytics-range a, .analytics-type button {
            padding:5px 11px; border-radius:8px; font-size:12px; font-weight:700; color:var(--loot-muted-color,#9fb6ac);
            text-decoration:none; border:none; background:transparent; cursor:pointer; line-height:1.4;
        }
        .analytics-range a.active, .analytics-type button.active { background:var(--loot-green,#22c55e); color:#031107; }

        /* Large desktops: give the hero chart even more room */
        @media (min-width: 1400px) { .a-8 { grid-column: span 8; } }
        /* Tablets / small laptops: two per row, hero full width */
        @media (max-width: 1199px) {
            .a-8 { grid-column: span 12; }
            .a-6 { grid-column: span 6; }
            .a-4 { grid-column: span 6; }
            .analytics-mini-grid { grid-template-columns:repeat(2,minmax(0,1fr)); }
        }
        /* Phones: one per row */
        @media (max-width: 767px) {
            .analytics-grid { gap: 12px; }
            .a-8, .a-6, .a-4, .a-12 { grid-column: span 12; }
            .analytics-head { margin-bottom: 6px; }
            .analytics-mini-grid { grid-template-columns:1fr; }
        }
    </style>
@endpush

@section('content')
    <div class="admin-dashboard-head mb-2">
        <div>
            <span class="loot-pill mb-1"><i data-feather="shield"></i> Admin command center</span>
            <h1 class="loot-section-title mb-50">Dashboard</h1>
            <p class="loot-muted mb-0">Monitor revenue, users, providers, cashouts, tickets, and callbacks from one focused view.</p>
        </div>
        <div class="admin-dashboard-actions">
            <a href="{{ route('admin.analytics') }}" class="btn btn-outline-light">
                <i data-feather="bar-chart-2" class="me-50"></i>Full analytics
            </a>
            <a href="{{ route('admin.leads') }}" class="btn btn-loot">
                <i data-feather="send" class="me-50"></i>Review leads
            </a>
        </div>
    </div>

    <div class="admin-kpi-strip mb-2">
        <div class="admin-kpi-card admin-kpi-primary">
            <span>Total profit</span>
            <strong>${{ number_format($profit['total'], 2) }}</strong>
            <p>${{ number_format($profit['today'], 2) }} earned today.</p>
        </div>
        <div class="admin-kpi-card">
            <span>Today profit</span>
            <strong>${{ number_format($profit['today'], 2) }}</strong>
            <p>Revenue credited today.</p>
        </div>
        <div class="admin-kpi-card">
            <span>Month profit</span>
            <strong>${{ number_format($profit['this_month'], 2) }}</strong>
            <p>Current month performance.</p>
        </div>
        <div class="admin-kpi-card">
            <span>Pending cashouts</span>
            <strong>{{ $withdrawals['pending'] }}</strong>
            <p>Requests waiting for review.</p>
        </div>
    </div>

    {{-- Analytics --}}
    @php $h = $analytics['headline']; @endphp
    <div class="analytics-mini-grid mb-2">
        <div class="analytics-mini">
            <span>Signups (7d)</span>
            <strong>{{ number_format($h['signups_7d']) }}</strong>
            <span class="analytics-trend {{ $h['signups_trend'] >= 0 ? 'up' : 'down' }}">
                <i data-feather="{{ $h['signups_trend'] >= 0 ? 'trending-up' : 'trending-down' }}" aria-hidden="true"></i> {{ abs($h['signups_trend']) }}% vs prev week
            </span>
        </div>
        <div class="analytics-mini">
            <span>Revenue (7d)</span>
            <strong>${{ number_format($h['revenue_7d'], 2) }}</strong>
            <span class="analytics-trend {{ $h['revenue_trend'] >= 0 ? 'up' : 'down' }}">
                <i data-feather="{{ $h['revenue_trend'] >= 0 ? 'trending-up' : 'trending-down' }}" aria-hidden="true"></i> {{ abs($h['revenue_trend']) }}% vs prev week
            </span>
        </div>
        <div class="analytics-mini">
            <span>Leads (7d)</span>
            <strong>{{ number_format($h['conversion_leads_7d']) }}</strong>
            <span class="analytics-trend {{ $h['leads_trend'] >= 0 ? 'up' : 'down' }}">
                <i data-feather="{{ $h['leads_trend'] >= 0 ? 'trending-up' : 'trending-down' }}" aria-hidden="true"></i> {{ abs($h['leads_trend']) }}% vs prev week
            </span>
        </div>
        <div class="analytics-mini">
            <span>Cashout approval</span>
            <strong>{{ $h['approval_rate'] }}%</strong>
            <span class="loot-muted" style="font-size:11px;">Avg {{ format_coins_as_usd($h['avg_cashout']) }} · {{ number_format($h['avg_cashout']) }} coins</span>
        </div>
        <div class="analytics-mini">
            <span>Paid out</span>
            <strong>{{ format_coins_as_usd($h['paid_out']) }}</strong>
            <span class="loot-muted" style="font-size:11px;">{{ number_format($h['paid_out']) }} coins · {{ format_coins_as_usd($h['pending_amount']) }} pending</span>
        </div>
        <div class="analytics-mini">
            <span>Active offerwalls</span>
            <strong>{{ number_format($h['active_offerwalls']) }}</strong>
        </div>
        <div class="analytics-mini">
            <span>Outstanding balance</span>
            <strong>{{ format_coins_as_usd($h['points_outstanding']) }}</strong>
            <span class="loot-muted" style="font-size:11px;">{{ number_format($h['points_outstanding']) }} coins</span>
        </div>
    </div>

    <div class="analytics-grid mb-2">
        <div class="analytics-card a-8">
            <div class="analytics-head">
                <h3>Growth &amp; revenue</h3>
                <div class="analytics-controls">
                    <div class="analytics-type" id="growthType" role="group" aria-label="Chart type">
                        <button type="button" data-type="area" class="active">Area</button>
                        <button type="button" data-type="line">Line</button>
                        <button type="button" data-type="bar">Bars</button>
                    </div>
                    <div class="analytics-range">
                        @foreach([7,14,30] as $r)
                            <a href="{{ route('admin.home', ['range' => $r]) }}" class="{{ $analytics['range'] === $r ? 'active' : '' }}">{{ $r }}d</a>
                        @endforeach
                    </div>
                </div>
            </div>
            <div class="chart-body" id="chartGrowth"></div>
        </div>
        <div class="analytics-card a-4">
            <div class="analytics-head"><h3>Cumulative revenue</h3><span class="loot-muted">{{ $analytics['range'] }}d</span></div>
            <div class="chart-body" id="chartCumulative"></div>
        </div>

        <div class="analytics-card a-4">
            <div class="analytics-head"><h3>Cashouts</h3><span class="loot-muted">All time</span></div>
            <div class="chart-body" id="chartCashouts"></div>
        </div>
        <div class="analytics-card a-4">
            <div class="analytics-head"><h3>Users</h3><span class="loot-muted">Composition</span></div>
            <div class="chart-body" id="chartUsers"></div>
        </div>
        <div class="analytics-card a-4">
            <div class="analytics-head"><h3>Lead status</h3><span class="loot-muted">{{ $analytics['range'] }}d</span></div>
            <div class="chart-body" id="chartLeadStatus"></div>
        </div>

        <div class="analytics-card a-4">
            <div class="analytics-head"><h3>Revenue by day</h3><span class="loot-muted">{{ $analytics['range'] }}d</span></div>
            <div class="chart-body" id="chartRevenue"></div>
        </div>
        <div class="analytics-card a-4">
            <div class="analytics-head"><h3>Top providers</h3><span class="loot-muted">Leads · 30d</span></div>
            <div class="chart-body" id="chartProviders"></div>
        </div>
        <div class="analytics-card a-4">
            <div class="analytics-head"><h3>Top countries</h3><span class="loot-muted">Leads · 30d</span></div>
            <div class="chart-body" id="chartCountries"></div>
        </div>

        <div class="analytics-card a-12">
            <div class="analytics-head"><h3>Approved conversions by weekday</h3><span class="loot-muted">Last 4 weeks</span></div>
            <div class="chart-body" id="chartWeekday"></div>
        </div>
    </div>

    <div class="admin-ops-grid mb-2">
        <a class="admin-ops-card" href="{{ route('admin.users') }}">
            <i data-feather="users"></i>
            <div>
                <span>Total users</span>
                <strong>{{ $users['count'] }}</strong>
                <p>{{ $users['new'] }} joined today.</p>
            </div>
        </a>
        <a class="admin-ops-card" href="{{ route('admin.users') }}">
            <i data-feather="user-check"></i>
            <div>
                <span>Active users</span>
                <strong>{{ $users['active'] }}</strong>
                <p>Seen in the last 24 hours.</p>
            </div>
        </a>
        <a class="admin-ops-card" href="{{ route('admin.users') }}">
            <i data-feather="slash"></i>
            <div>
                <span>Banned users</span>
                <strong>{{ $users['banned'] }}</strong>
                <p>Accounts currently restricted.</p>
            </div>
        </a>
        <a class="admin-ops-card" href="{{ route('admin.offerwalls') }}">
            <i data-feather="star"></i>
            <div>
                <span>Active offerwalls</span>
                <strong>{{ $operations['active_offerwalls'] }}/{{ $operations['total_offerwalls'] }}</strong>
                <p>Providers visible to users.</p>
            </div>
        </a>
        <a class="admin-ops-card" href="{{ route('admin.leads') }}">
            <i data-feather="send"></i>
            <div>
                <span>Leads today</span>
                <strong>{{ $operations['leads_today'] }}</strong>
                <p>Conversions received today.</p>
            </div>
        </a>
        <a class="admin-ops-card" href="{{ route('admin.tickets') }}">
            <i data-feather="inbox"></i>
            <div>
                <span>Open tickets</span>
                <strong>{{ \App\Models\SupportTicket::whereIn('status', ['open', 'pending'])->count() }}</strong>
                <p>User support awaiting admin action.</p>
            </div>
        </a>
    </div>

    <div class="loot-command-grid mb-2">
        <div class="card">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-center mb-1">
                    <h4 class="loot-section-title mb-0">Recent conversions</h4>
                    <a href="{{ route('admin.leads') }}" class="btn btn-sm btn-outline-light">Open leads</a>
                </div>
                @forelse($operations['latest_leads'] as $lead)
                    <div class="loot-table-row">
                        <div>
                            <strong>{{ $lead->offer_name ?? $lead->offer_id ?? 'Offer conversion' }}</strong>
                            <div class="loot-muted">
                                {{ $lead->user?->username ?? 'Unknown user' }} via {{ $lead->company }}
                            </div>
                        </div>
                        <span class="loot-status success">${{ number_format((float) $lead->payout, 2) }}</span>
                    </div>
                @empty
                    <div class="text-center py-2">
                        <h5 class="loot-section-title">No leads yet</h5>
                        <p class="loot-muted mb-0">Conversions will appear here as offerwalls report them.</p>
                    </div>
                @endforelse
            </div>
        </div>

        <div class="card">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-center mb-1">
                    <h4 class="loot-section-title mb-0">Top earners</h4>
                    <a href="{{ route('admin.users') }}" class="btn btn-sm btn-outline-light">Manage users</a>
                </div>
                @forelse($operations['top_users'] as $topUser)
                    <div class="loot-table-row">
                        <div>
                            <strong>{{ $topUser->username }}</strong>
                            <div class="loot-muted">{{ $topUser->email }}</div>
                        </div>
                        <span class="loot-status">{{ format_coins_as_usd($topUser->total_points) }} <small>· {{ number_format($topUser->total_points) }} coins</small></span>
                    </div>
                @empty
                    <div class="text-center py-2">
                        <h5 class="loot-section-title">No users yet</h5>
                        <p class="loot-muted mb-0">New accounts will appear after registration.</p>
                    </div>
                @endforelse
            </div>
        </div>
    </div>

    <div class="card">
        <div class="card-body">
            <div class="d-flex justify-content-between align-items-center mb-1">
                <h4 class="loot-section-title mb-0">Cashout queue</h4>
                <a href="{{ route('admin.withdrawals') }}" class="btn btn-sm btn-loot">Review withdrawals</a>
            </div>
            <div class="admin-mini-grid mb-1">
                <div class="loot-admin-card">
                    <span>Total withdrawals</span>
                    <strong>{{ $withdrawals['count'] }}</strong>
                </div>
                <div class="loot-admin-card">
                    <span>Approved</span>
                    <strong>{{ $withdrawals['paid'] }}</strong>
                </div>
                <div class="loot-admin-card">
                    <span>Rejected</span>
                    <strong>{{ $withdrawals['rejected'] }}</strong>
                </div>
            </div>

            @forelse($operations['latest_withdrawals'] as $withdrawal)
                <div class="loot-table-row">
                    <div>
                        <strong>{{ $withdrawal->user?->username ?? 'Unknown user' }}</strong>
                        <div class="loot-muted">{{ format_coins_as_usd($withdrawal->amount ?? 0) }} requested · {{ number_format($withdrawal->amount ?? 0) }} coins</div>
                    </div>
                    <span class="loot-status {{ $withdrawal->status === 'approved' ? 'success' : ($withdrawal->status === 'pending' ? 'warning' : 'danger') }}">
                        {{ ucfirst($withdrawal->status) }}
                    </span>
                </div>
            @empty
                <div class="text-center py-2">
                    <h5 class="loot-section-title">No cashout requests</h5>
                    <p class="loot-muted mb-0">Withdrawal activity will appear here when users redeem rewards.</p>
                </div>
            @endforelse
        </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 data = @json($analytics);
            const css = getComputedStyle(document.documentElement);
            const green = css.getPropertyValue('--loot-green').trim() || '#22c55e';
            const blue = css.getPropertyValue('--loot-blue').trim() || '#86efac';
            const amber = '#f7b731';
            const red = '#ff6b6b';
            const muted = '#9fb6ac';
            const grid = 'rgba(255,255,255,.06)';

            // Uniform heights keep the cards visually balanced across the grid.
            const H = 260;      // standard chart height
            const HERO = 300;   // growth chart

            const baseAxis = {
                labels: { style: { colors: muted, fontSize: '11px' } },
                axisBorder: { show: false },
                axisTicks: { show: false },
            };
            const baseGrid = { borderColor: grid, strokeDashArray: 4, padding: { left: 8, right: 8 } };
            // Charts shrink their fonts/legends on small screens.
            const responsive = [{
                breakpoint: 576,
                options: { chart: { height: 240 }, legend: { fontSize: '10px' }, dataLabels: { style: { fontSize: '9px' } } }
            }];

            const donut = (values, labels, colors, empty) => ({
                chart: { type: 'donut', height: H, fontFamily: 'inherit' },
                series: values, labels: labels, colors: colors,
                stroke: { width: 0 },
                legend: { position: 'bottom', fontSize: '11px', labels: { colors: muted }, itemMargin: { horizontal: 6 } },
                dataLabels: { enabled: true, style: { fontSize: '11px', fontWeight: 700 }, dropShadow: { enabled: false } },
                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 yet', style: { color: muted } },
                responsive,
            });

            const bar = (values, categories, color, horizontal, empty, fmt) => ({
                chart: { type: 'bar', height: H, toolbar: { show: false }, fontFamily: 'inherit' },
                series: [{ name: 'Leads', data: values }],
                colors: [color],
                plotOptions: { bar: { borderRadius: 5, horizontal: !!horizontal, columnWidth: '55%', barHeight: '62%', distributed: false } },
                dataLabels: { enabled: false },
                grid: baseGrid,
                xaxis: Object.assign({ categories: categories }, baseAxis),
                yaxis: { labels: { style: { colors: muted, fontSize: '11px' }, formatter: fmt } },
                tooltip: { theme: 'dark' },
                noData: { text: empty || 'No data yet', style: { color: muted } },
                responsive,
            });

            // --- Growth chart with area/line/bar toggle ---
            const growthEl = document.querySelector('#chartGrowth');
            let growthType = 'area';
            const growthOptions = () => ({
                chart: { type: growthType, height: HERO, toolbar: { show: false }, fontFamily: 'inherit', animations: { easing: 'easeinout', speed: 500 }, stacked: growthType === 'bar' },
                series: [
                    { name: 'Signups', data: data.daily.signups },
                    { name: 'Leads', data: data.daily.leads },
                ],
                colors: [green, blue],
                dataLabels: { enabled: false },
                stroke: { curve: 'smooth', width: growthType === 'bar' ? 0 : 2.5 },
                fill: growthType === 'area'
                    ? { type: 'gradient', gradient: { shadeIntensity: 1, opacityFrom: 0.35, opacityTo: 0.02, stops: [0, 90] } }
                    : { type: 'solid', opacity: growthType === 'bar' ? 0.9 : 1 },
                plotOptions: { bar: { borderRadius: 4, columnWidth: '55%' } },
                grid: baseGrid,
                xaxis: Object.assign({ categories: data.daily.labels }, baseAxis),
                yaxis: { labels: { style: { colors: muted, fontSize: '11px' } } },
                legend: { labels: { colors: muted }, markers: { radius: 12 } },
                tooltip: { theme: 'dark' },
                responsive,
            });
            const growthChart = new ApexCharts(growthEl, growthOptions());
            growthChart.render();

            document.querySelectorAll('#growthType button').forEach((btn) => {
                btn.addEventListener('click', () => {
                    document.querySelectorAll('#growthType button').forEach((b) => b.classList.remove('active'));
                    btn.classList.add('active');
                    growthType = btn.dataset.type;
                    growthChart.updateOptions(growthOptions(), true, true);
                });
            });

            // --- Cumulative revenue (line) ---
            new ApexCharts(document.querySelector('#chartCumulative'), {
                chart: { type: 'line', height: H, toolbar: { show: false }, fontFamily: 'inherit', sparkline: { enabled: false } },
                series: [{ name: 'Cumulative $', data: data.cumulative.values }],
                colors: [green],
                stroke: { curve: 'smooth', width: 3 },
                dataLabels: { enabled: false },
                grid: baseGrid,
                xaxis: Object.assign({ categories: data.cumulative.labels, tickAmount: 5 }, baseAxis),
                yaxis: { labels: { style: { colors: muted, fontSize: '11px' }, formatter: (v) => '$' + Number(v).toFixed(0) } },
                tooltip: { theme: 'dark', y: { formatter: (v) => '$' + Number(v).toFixed(2) } },
                responsive,
            }).render();

            // --- Donuts ---
            new ApexCharts(document.querySelector('#chartCashouts'), donut(data.cashouts.values, data.cashouts.labels, [amber, green, red], 'No cashouts yet')).render();
            new ApexCharts(document.querySelector('#chartUsers'), donut(data.users.values, data.users.labels, [green, muted, red], 'No users yet')).render();
            new ApexCharts(document.querySelector('#chartLeadStatus'), donut(data.lead_status.values, data.lead_status.labels, [green, amber, red], 'No leads yet')).render();

            // --- Bars ---
            new ApexCharts(document.querySelector('#chartRevenue'), bar(data.daily.revenue, data.daily.labels, green, false, 'No revenue yet', (v) => '$' + Number(v).toFixed(0))).render();
            new ApexCharts(document.querySelector('#chartProviders'), bar(data.providers.values, data.providers.labels, blue, true, 'No provider leads yet')).render();
            new ApexCharts(document.querySelector('#chartCountries'), bar(data.countries.values, data.countries.labels, amber, true, 'No country data yet')).render();
            new ApexCharts(document.querySelector('#chartWeekday'), bar(data.weekday.values, data.weekday.labels, green, false, 'No conversions yet')).render();
        })();
    </script>
@endpush
