@extends('admin.layouts.app')

@section('title', 'Dashboard')
@section('subtitle', 'Track visitors, manage responses, and keep the site profile healthy from one compact workspace.')

@section('content')
    @php
        $lateThreshold = now()->subHours(24);
    @endphp

    <section class="admin-grid admin-grid--stats">
        @foreach($stats as $stat)
            @include('admin.partials.stat-card', $stat)
        @endforeach
    </section>

    <section class="mt-6 admin-fiverr-grid">
        <div class="admin-card admin-card--feature">
            <div class="admin-toolbar">
                <div>
                    <p class="admin-section-title">Manage Responses</p>
                </div>
                <a href="{{ route('admin.contacts.index') }}" class="admin-button admin-button--secondary">Open inbox</a>
            </div>

            <div class="admin-response-tabs">
                @foreach($response_statuses as $status)
                    <a href="{{ route('admin.contacts.index', ['status' => $status['class'] === 'late' ? 'late' : $status['class']]) }}" class="admin-response-tab admin-response-tab--{{ $status['class'] }}">
                        <span>{{ $status['label'] }}</span>
                        <strong>{{ $status['value'] }}</strong>
                    </a>
                @endforeach
            </div>

            <div class="admin-response-table">
                <table>
                    <thead>
                        <tr>
                            <th>Visitor</th>
                            <th>Received</th>
                            <th>Status</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        @forelse($recent_contacts as $contact)
                            @php
                                $isLate = in_array($contact->status, ['new', 'read'], true) && $contact->created_at->lte($lateThreshold);
                                $statusLabel = $isLate ? 'Late' : ucfirst($contact->status);
                                $statusClass = $isLate ? 'late' : $contact->status;
                            @endphp
                            <tr>
                                <td>
                                    <div class="admin-table-person">
                                        <strong>{{ $contact->name }}</strong>
                                        <span>{{ $contact->email }}</span>
                                        <p>{{ \Illuminate\Support\Str::limit($contact->message, 72) }}</p>
                                    </div>
                                </td>
                                <td>{{ $contact->created_at->diffForHumans() }}</td>
                                <td><span class="admin-badge admin-badge--{{ $statusClass }}">{{ $statusLabel }}</span></td>
                                <td><a href="{{ route('admin.contacts.show', $contact) }}" class="admin-button admin-button--ghost">Review</a></td>
                            </tr>
                        @empty
                            <tr>
                                <td colspan="4" class="admin-empty">No contact messages yet.</td>
                            </tr>
                        @endforelse
                    </tbody>
                </table>
            </div>
        </div>

        <div class="admin-sidebar-stack">
            <div class="admin-card">
                <div class="admin-toolbar">
                    <div>
                        <p class="admin-section-title">Profile Strength</p>
                        <p class="admin-section-subtitle">Complete the brand setup so the CMS is ready for clients and leads.</p>
                    </div>
                    <span class="admin-score">{{ $profile_strength['completed'] }}/{{ $profile_strength['total'] }}</span>
                </div>

                <div class="admin-progress">
                    <span class="admin-progress__bar" style="width: {{ $profile_strength['percent'] }}%"></span>
                </div>

                <div class="admin-checklist">
                    @foreach($profile_strength['items'] as $label => $completed)
                        <div class="admin-checklist__item">
                            <span class="admin-checklist__dot {{ $completed ? 'is-complete' : '' }}"></span>
                            <span>{{ $label }}</span>
                        </div>
                    @endforeach
                </div>

                <a href="{{ route('profile.edit') }}" class="admin-button mt-4">Complete profile</a>
            </div>

            <div class="admin-card">
                <div class="admin-toolbar">
                    <div>
                        <p class="admin-section-title">Track Your Performance</p>
                        <p class="admin-section-subtitle">Quick system totals and traffic hotspots.</p>
                    </div>
                </div>

                <div class="admin-mini-stats">
                    @foreach($site_totals as $item)
                        <div class="admin-mini-stat">
                            <span>{{ $item['label'] }}</span>
                            <strong>{{ $item['value'] }}</strong>
                        </div>
                    @endforeach
                </div>

                <div class="admin-list mt-4">
                    @forelse($top_countries as $country)
                        <div class="admin-list__item">
                            <div>
                                <p class="font-semibold">{{ $country['country'] }}</p>
                                <p class="text-sm text-slate-500">{{ $country['unique'] }} unique visitors</p>
                            </div>
                            <span class="admin-chip">{{ $country['visits'] }} visits</span>
                        </div>
                    @empty
                        <div class="admin-empty">Country data will appear after visitors browse the public site.</div>
                    @endforelse
                </div>

                <div class="mt-5">
                    <p class="admin-section-title">Traffic sources</p>
                    <div class="admin-list mt-3">
                        @forelse($top_sources as $source)
                            <div class="admin-list__item">
                                <div>
                                    <p class="font-semibold">{{ ucfirst($source['source']) }}</p>
                                    <p class="text-sm text-slate-500">{{ ucfirst($source['medium']) }} | {{ $source['unique'] }} unique visitors</p>
                                </div>
                                <span class="admin-chip">{{ $source['visits'] }} visits</span>
                            </div>
                        @empty
                            <div class="admin-empty">Source tracking appears after users arrive from search, campaigns, or referrals.</div>
                        @endforelse
                    </div>
                </div>
            </div>
        </div>
    </section>

    <section class="mt-6 admin-grid admin-grid--three">
        <div class="admin-card admin-chart-card">
            <div class="admin-toolbar">
                <div>
                    <p class="admin-section-title">Visitor Trend</p>
                    <p class="admin-section-subtitle">Compact 7-day view of visits and unique visitors.</p>
                </div>
            </div>
            <div class="admin-chart-canvas">
                <canvas id="visitsChart" height="96"></canvas>
            </div>
        </div>

        <div class="admin-card">
            <div class="admin-toolbar">
                <div>
                    <p class="admin-section-title">Top Pages</p>
                    <p class="admin-section-subtitle">Which public URLs are attracting attention.</p>
                </div>
            </div>

            <div class="admin-list">
                @forelse($top_pages as $page)
                    <div class="admin-list__item">
                        <div>
                            <p class="font-semibold">{{ $page['path'] }}</p>
                            <p class="text-sm text-slate-500">{{ $page['unique'] }} unique visitors</p>
                        </div>
                        <span class="admin-chip">{{ $page['visits'] }} visits</span>
                    </div>
                @empty
                    <div class="admin-empty">No visit data yet.</div>
                @endforelse
            </div>
        </div>

        <div class="admin-card">
            <div class="admin-toolbar">
                <div>
                    <p class="admin-section-title">Recent Activity</p>
                    <p class="admin-section-subtitle">Last saved records across the CMS.</p>
                </div>
            </div>

            <div class="admin-list">
                @forelse($recent_activity as $activity)
                    <div class="admin-list__item">
                        <div>
                            <p class="font-semibold">{{ class_basename($activity->auditable_type) }} {{ $activity->event }}</p>
                            <p class="text-sm text-slate-500">{{ $activity->user?->name ?? 'System' }} on {{ $activity->created_at->format('M j, Y g:i A') }}</p>
                        </div>
                        <span class="admin-chip">#{{ $activity->auditable_id }}</span>
                    </div>
                @empty
                    <div class="admin-empty">No audit activity found yet.</div>
                @endforelse
            </div>
        </div>
    </section>
@endsection

@push('head')
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
@endpush

@push('scripts')
    <script>
        const ctx = document.getElementById('visitsChart');

        if (ctx) {
            new Chart(ctx, {
                type: 'line',
                data: {
                    labels: @json($visits_chart['labels']),
                    datasets: [
                        {
                            label: @json($visits_chart['datasets'][0]['label']),
                            data: @json($visits_chart['datasets'][0]['data']),
                            borderColor: '#1dbf73',
                            backgroundColor: 'rgba(29, 191, 115, 0.12)',
                            tension: 0.35,
                            fill: true,
                            borderWidth: 2,
                        },
                        {
                            label: @json($visits_chart['datasets'][1]['label']),
                            data: @json($visits_chart['datasets'][1]['data']),
                            borderColor: '#2563eb',
                            backgroundColor: 'rgba(37, 99, 235, 0.08)',
                            tension: 0.35,
                            fill: true,
                            borderWidth: 2,
                        }
                    ],
                },
                options: {
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            position: 'bottom',
                        }
                    },
                    scales: {
                        y: {
                            beginAtZero: true,
                            ticks: {
                                precision: 0,
                            }
                        }
                    }
                }
            });
        }
    </script>
@endpush
