@extends('admin.layouts.app')
@section('title', 'Statistics')
@section('page-title', 'Statistics')

@section('content')
@php
    $maxViews   = max(1, $chart->max('views'));
    $chartDates = $chart->keys();
@endphp

<div class="space-y-6">

    {{-- Period selector --}}
    <div class="flex items-center justify-between flex-wrap gap-3">
        <p class="text-sm text-gray-500 dark:text-gray-400">
            {{ $start->format('M j, Y') }} – {{ $end->format('M j, Y') }}
        </p>
        {{-- dropdown trigger — uses statsChart Alpine component defined on the chart card below --}}
        <div x-data="statsChart()" style="position:relative;">
            <button @click="togglePicker()"
                    class="flex items-center gap-2 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 text-sm font-medium text-gray-700 dark:text-gray-200 px-4 py-2 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors">
                {{ $periodLabel }}
                <x-admin-icon name="chevron-down" class="w-4 h-4 text-gray-400" />
            </button>

            <div x-show="showPicker" @click.outside="closePicker()" x-cloak
                 style="position:absolute; right:0; top:calc(100% + 6px); z-index:40; min-width:190px; background:#fff; border:1px solid #e5e7eb; border-radius:12px; box-shadow:0 8px 24px rgba(0,0,0,.1); overflow:hidden;">
                @foreach($periods as $key => $label)
                <a href="?period={{ $key }}" @click="closePicker()"
                   style="display:flex; align-items:center; justify-content:space-between; padding:10px 16px; font-size:14px; text-decoration:none; color:{{ $period === $key ? '#1d4ed8' : '#374151' }}; background:{{ $period === $key ? '#eff6ff' : 'transparent' }};"
                   onmouseover="if('{{ $period }}' !== '{{ $key }}') this.style.background='#f9fafb'"
                   onmouseout="if('{{ $period }}' !== '{{ $key }}') this.style.background='transparent'">
                    <span>{{ $label }}</span>
                    @if($period === $key)
                    <svg style="width:14px;height:14px;" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M5 13l4 4L19 7"/></svg>
                    @endif
                </a>
                @endforeach
            </div>
        </div>
    </div>

    {{-- Summary cards --}}
    <div class="grid grid-cols-2 gap-4">
        @foreach([
            ['label' => 'Views',    'value' => $totalViews,    'delta' => $viewsDelta,    'icon' => 'eye',   'color' => 'indigo'],
            ['label' => 'Visitors', 'value' => $totalVisitors, 'delta' => $visitorsDelta, 'icon' => 'users', 'color' => 'purple'],
        ] as $card)
        <div class="bg-white dark:bg-gray-800 rounded-xl shadow-sm p-5">
            <div class="flex items-start justify-between">
                <div>
                    <p class="text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wide mb-1">{{ $card['label'] }}</p>
                    <p class="text-3xl font-bold text-gray-900 dark:text-white">{{ number_format($card['value']) }}</p>
                </div>
                <div class="p-2 bg-{{ $card['color'] }}-50 dark:bg-{{ $card['color'] }}-900/20 rounded-lg">
                    <x-admin-icon name="{{ $card['icon'] }}" class="w-5 h-5 text-{{ $card['color'] }}-600 dark:text-{{ $card['color'] }}-400" />
                </div>
            </div>
            @if($card['delta'] !== null)
            <div class="mt-3 flex items-center gap-1 text-xs font-medium
                {{ $card['delta'] >= 0 ? 'text-green-600 dark:text-green-400' : 'text-red-500 dark:text-red-400' }}">
                @if($card['delta'] >= 0)
                <svg class="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M5 15l7-7 7 7"/></svg>
                @else
                <svg class="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M19 9l-7 7-7-7"/></svg>
                @endif
                {{ abs($card['delta']) }}% vs previous period
            </div>
            @else
            <p class="mt-3 text-xs text-gray-400 dark:text-gray-500">No previous period data</p>
            @endif
        </div>
        @endforeach
    </div>

    {{-- Bar chart --}}
    <div class="bg-white dark:bg-gray-800 rounded-xl shadow-sm p-6" x-data="statsChart()">
        <div class="flex items-center gap-5 mb-5">
            <h3 class="text-sm font-semibold text-gray-900 dark:text-white flex-1">Views &amp; Visitors</h3>
            <div class="flex items-center gap-4 text-xs text-gray-500 dark:text-gray-400">
                <span class="flex items-center gap-1.5">
                    <span class="w-2.5 h-2.5 rounded-sm inline-block" style="background:#5b8de0;"></span> Views
                </span>
                <span class="flex items-center gap-1.5">
                    <span class="w-2.5 h-2.5 rounded-sm inline-block" style="background:#1e4fad;"></span> Visitors
                </span>
            </div>
        </div>

        {{-- bars + tooltip wrapper --}}
        <div style="position:relative;">
            <div x-ref="chartArea" class="flex items-end gap-1" style="height:160px;">
                @foreach($chart as $date => $row)
                @php
                    $viewsPct    = $maxViews > 0 ? max(3, round(($row['views']    / $maxViews) * 130)) : 3;
                    $visitorsPct = $maxViews > 0 ? max(3, round(($row['visitors'] / $maxViews) * 130)) : 3;
                    $visitorsPct = min($visitorsPct, $viewsPct);
                    if ($type === 'year') {
                        $label     = $date;
                        $dateLabel = $date;
                    } elseif ($type === 'month') {
                        $label     = \Carbon\Carbon::createFromFormat('Y-m', $date)->format('M Y');
                        $dateLabel = \Carbon\Carbon::createFromFormat('Y-m', $date)->format('F Y');
                    } else {
                        $label     = \Carbon\Carbon::parse($date)->format('j M');
                        $dateLabel = \Carbon\Carbon::parse($date)->format('j M Y');
                    }
                @endphp
                <div class="flex-1 flex flex-col items-center gap-1" style="cursor:pointer;"
                     @mouseenter="showTooltip({ date: '{{ $dateLabel }}', views: {{ $row['views'] }}, visitors: {{ $row['visitors'] }} }, $event)"
                     @mouseleave="hideTooltip()">
                    <div style="width:100%; position:relative; border-radius:3px 3px 0 0; height:{{ $viewsPct }}px; background:#5b8de0;">
                        <div style="position:absolute; bottom:0; left:20%; width:60%; height:{{ $visitorsPct }}px; background:#1e4fad; border-radius:3px 3px 0 0;"></div>
                    </div>
                    <span style="font-size:10px; color:#9ca3af; line-height:1; white-space:nowrap;">{{ $label }}</span>
                </div>
                @endforeach
            </div>

            {{-- Tooltip — appears below chart labels --}}
            <div x-show="tooltip !== null" x-cloak
                 :style="{ left: tooltip ? (tooltip.x - 112) + 'px' : '0' }"
                 style="position:absolute; top:168px; z-index:30; width:224px; background:#1f2937; color:#fff; border-radius:12px; padding:16px; box-shadow:0 10px 30px rgba(0,0,0,.3);">
                {{-- arrow pointing up toward the bar --}}
                <div :style="{ left: tooltip ? tooltip.arrowLeft + 'px' : '50%' }"
                     style="position:absolute; top:-7px; transform:translateX(-50%); width:0; height:0; border-left:7px solid transparent; border-right:7px solid transparent; border-bottom:7px solid #1f2937;"></div>

                <p style="font-size:13px; font-weight:700; margin-bottom:12px;" x-text="tooltip ? tooltip.date : ''"></p>

                <div style="display:flex; flex-direction:column; gap:8px; font-size:13px;">
                    <div style="display:flex; align-items:center; gap:10px;">
                        <svg style="width:16px;height:16px;flex-shrink:0;opacity:.7" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"/></svg>
                        <span style="flex:1; opacity:.85;">Views</span>
                        <span style="font-weight:600;" x-text="tooltip ? tooltip.views : ''"></span>
                    </div>
                    <div style="display:flex; align-items:center; gap:10px;">
                        <svg style="width:16px;height:16px;flex-shrink:0;opacity:.7" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4.354a4 4 0 110 5.292M15 21H3v-1a6 6 0 0112 0v1zm0 0h6v-1a6 6 0 00-9-5.197M13 7a4 4 0 11-8 0 4 4 0 018 0z"/></svg>
                        <span style="flex:1; opacity:.85;">Visitors</span>
                        <span style="font-weight:600;" x-text="tooltip ? tooltip.visitors : ''"></span>
                    </div>
                    <div style="display:flex; align-items:center; gap:10px; padding-top:6px; border-top:1px solid rgba(255,255,255,.1);">
                        <svg style="width:16px;height:16px;flex-shrink:0;opacity:.7" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"/></svg>
                        <span style="flex:1; opacity:.85;">Views per Visitor</span>
                        <span style="font-weight:600;" x-text="tooltip ? tooltip.vpv : '—'"></span>
                    </div>
                </div>
            </div>
        </div>
    </div>

    {{-- Most viewed + Referrers --}}
    <div class="grid grid-cols-1 sm:grid-cols-2 gap-6">

        {{-- Most viewed posts --}}
        <div class="bg-white dark:bg-gray-800 rounded-xl shadow-sm p-6">
            <h3 class="text-sm font-semibold text-gray-900 dark:text-white mb-4">Most Viewed</h3>
            @php $maxPostViews = max(1, $mostViewed->max('views') ?? 1); @endphp
            @forelse($mostViewed as $item)
            <div class="mb-3 last:mb-0">
                <div class="flex items-center justify-between text-xs mb-1 gap-2">
                    <a href="{{ $item['url'] }}" target="_blank"
                       class="font-medium text-gray-700 dark:text-gray-200 hover:text-indigo-600 dark:hover:text-indigo-400 truncate flex-1">
                        {{ $item['title'] }}
                    </a>
                    <span class="text-gray-500 dark:text-gray-400 flex-shrink-0 font-mono">{{ number_format($item['views']) }}</span>
                </div>
                <div class="w-full bg-gray-100 dark:bg-gray-700 rounded-full h-1.5">
                    <div class="bg-indigo-500 h-1.5 rounded-full transition-all"
                         style="width: {{ round(($item['views'] / $maxPostViews) * 100) }}%"></div>
                </div>
            </div>
            @empty
            <p class="text-sm text-gray-400 dark:text-gray-500">No post views recorded yet.</p>
            @endforelse
        </div>

        {{-- Referrers --}}
        <div class="bg-white dark:bg-gray-800 rounded-xl shadow-sm p-6">
            <h3 class="text-sm font-semibold text-gray-900 dark:text-white mb-4">Referrers</h3>
            @forelse($referrers as $ref)
            <div class="mb-3 last:mb-0">
                <div class="flex items-center justify-between text-xs mb-1 gap-2">
                    <span class="font-medium text-gray-700 dark:text-gray-200 truncate flex-1">{{ $ref->referrer }}</span>
                    <span class="text-gray-500 dark:text-gray-400 flex-shrink-0 font-mono">{{ number_format($ref->views) }}</span>
                </div>
                <div class="w-full bg-gray-100 dark:bg-gray-700 rounded-full h-1.5">
                    <div class="bg-purple-500 h-1.5 rounded-full transition-all"
                         style="width: {{ round(($ref->views / $maxReferrerViews) * 100) }}%"></div>
                </div>
            </div>
            @empty
            <p class="text-sm text-gray-400 dark:text-gray-500">No referrers recorded yet.</p>
            @endforelse
        </div>

    </div>

</div>
@endsection
