<!DOCTYPE html>
<html lang="en">
<head>
    @php
        $seo = \App\Models\SeoSetting::current();

        $pageTitle = trim($__env->yieldContent('title', 'Admin Panel'));
        $siteName = $seo->site_name ?: 'Hisab Seba';
        $fullTitle = $pageTitle ? $pageTitle . ' - ' . $siteName : $siteName;

        $faviconUrl = !empty($seo?->favicon) ? asset($seo->favicon) : asset('hisabseba-favicon.png');
    @endphp

    <meta charset="UTF-8">
    <title>{{ $fullTitle }}</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">

    {{-- Favicon --}}
    <link rel="icon" href="{{ $faviconUrl }}">
    <link rel="shortcut icon" href="{{ $faviconUrl }}">

    {{-- Tailwind CSS CDN --}}
    <script src="https://cdn.tailwindcss.com"></script>

    {{-- Alpine.js --}}
    <script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"></script>

    <style>
        body {
            font-family: Inter, sans-serif;
            background: #f8fafc;
        }

        ::-webkit-scrollbar {
            width: 7px;
            height: 7px;
        }

        ::-webkit-scrollbar-thumb {
            background: #94a3b8;
            border-radius: 999px;
        }

        ::-webkit-scrollbar-track {
            background: #e2e8f0;
        }
    </style>

    @stack('styles')
</head>
<body class="min-h-screen bg-slate-50 text-slate-800">

    @php
        use App\Models\SubscriptionRequest;

        $admin = auth('admin')->user();
        $pendingRequestCount = SubscriptionRequest::where('status', 'pending')->count();
        $isSubscriptionRequestPage = request()->routeIs('admin.subscription-requests.*');

        $adminPhotoUrl = !empty($admin?->photo) ? asset($admin->photo) : null;
        $adminInitial = strtoupper(substr($admin->name ?? 'A', 0, 1));
    @endphp

    <div class="flex min-h-screen">

        {{-- Sidebar --}}
        @include('admin.partials.sidebar')

        {{-- Main Area --}}
        <div class="flex min-h-screen flex-1 flex-col">

            {{-- Top Navbar --}}
            <nav class="sticky top-0 z-40 border-b border-slate-200 bg-white/80 backdrop-blur-lg">
                <div class="flex items-center justify-between px-4 py-4 sm:px-6 lg:px-8">

                    {{-- Left --}}
                    <div>
                        <h1 class="text-xl font-bold text-slate-800 md:text-2xl">
                            @yield('title', 'Dashboard')
                        </h1>
                    </div>

                    {{-- Right --}}
                    <div class="flex items-center gap-3 sm:gap-4">

                        {{-- Notification Bell --}}
                        <a href="{{ route('admin.subscription-requests.index', ['status' => 'pending']) }}"
                           class="relative inline-flex h-11 w-11 items-center justify-center rounded-2xl border border-slate-200 bg-white shadow-sm transition duration-200 hover:bg-slate-50 hover:shadow-md"
                           title="Pending Subscription Requests">

                            <svg xmlns="http://www.w3.org/2000/svg"
                                 class="h-5 w-5 text-slate-600"
                                 fill="none"
                                 viewBox="0 0 24 24"
                                 stroke="currentColor"
                                 stroke-width="1.8">
                                <path stroke-linecap="round" stroke-linejoin="round"
                                      d="M14.857 17H9.143m9.714 0A2.143 2.143 0 0 1 16.714 19H7.286a2.143 2.143 0 0 1-2.143-2m13.714 0V11.643a6.857 6.857 0 1 0-13.714 0V17m13.714 0H5.143" />
                            </svg>

                            <span
                                id="request-badge"
                                class="absolute -right-1.5 -top-1.5 inline-flex min-h-[22px] min-w-[22px] items-center justify-center rounded-full bg-rose-600 px-1.5 text-[11px] font-bold text-white ring-2 ring-white {{ (!$isSubscriptionRequestPage && $pendingRequestCount > 0) ? 'flex' : 'hidden' }}"
                            >
                                {{ $pendingRequestCount > 99 ? '99+' : $pendingRequestCount }}
                            </span>
                        </a>

                        {{-- Profile Dropdown --}}
                        <div class="relative" x-data="{ open: false }">
                            <button
                                type="button"
                                @click="open = !open"
                                class="flex items-center gap-3 rounded-2xl border border-slate-200 bg-white px-3 py-2 shadow-sm transition hover:bg-slate-50 focus:outline-none"
                            >
                                @if($adminPhotoUrl)
                                    <img
                                        class="h-10 w-10 rounded-full border-2 border-slate-200 object-cover"
                                        src="{{ $adminPhotoUrl }}"
                                        alt="Admin Photo"
                                    >
                                @else
                                    <div class="flex h-10 w-10 items-center justify-center rounded-full border-2 border-slate-200 bg-slate-100 text-sm font-bold text-slate-600">
                                        {{ $adminInitial }}
                                    </div>
                                @endif

                                <div class="hidden text-left sm:block">
                                    <div class="text-sm font-semibold text-slate-700">
                                        {{ $admin->name ?? 'Admin' }}
                                    </div>
                                    <div class="text-xs text-slate-500">
                                        Administrator
                                    </div>
                                </div>

                                <svg class="h-4 w-4 text-slate-500" fill="none" stroke="currentColor" stroke-width="2"
                                     viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                                    <path stroke-linecap="round" stroke-linejoin="round"
                                          d="M19 9l-7 7-7-7"></path>
                                </svg>
                            </button>

                            {{-- Dropdown Menu --}}
                            <div
                                x-show="open"
                                x-transition
                                @click.away="open = false"
                                class="absolute right-0 mt-3 w-64 overflow-hidden rounded-2xl border border-slate-200 bg-white shadow-xl"
                                style="display: none;"
                            >
                                <div class="border-b border-slate-100 px-4 py-3">
                                    <div class="text-sm font-semibold text-slate-800">
                                        {{ $admin->name ?? 'Admin' }}
                                    </div>
                                    <div class="text-xs text-slate-500 break-all">
                                        {{ $admin->email ?? '' }}
                                    </div>
                                </div>

                                <a href="{{ route('admin.profile') }}"
                                   class="block px-4 py-3 text-sm font-medium text-slate-700 transition hover:bg-indigo-50 hover:text-indigo-700">
                                    My Profile
                                </a>

                                <a href="{{ route('admin.subscription-requests.index', ['status' => 'pending']) }}"
                                   class="flex items-center justify-between px-4 py-3 text-sm font-medium text-slate-700 transition hover:bg-amber-50 hover:text-amber-700">
                                    <span>Pending Requests</span>

                                    <span id="dropdown-request-badge"
                                          class="inline-flex min-w-[22px] items-center justify-center rounded-full bg-amber-500 px-2 py-0.5 text-[11px] font-bold text-white {{ $pendingRequestCount > 0 ? 'inline-flex' : 'hidden' }}">
                                        {{ $pendingRequestCount > 99 ? '99+' : $pendingRequestCount }}
                                    </span>
                                </a>

                                <form method="POST" action="{{ route('admin.logout') }}">
                                    @csrf
                                    <button type="submit"
                                            class="block w-full px-4 py-3 text-left text-sm font-medium text-red-600 transition hover:bg-red-50">
                                        Logout
                                    </button>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>
            </nav>

            {{-- Content Area --}}
            <main class="flex-1 px-4 py-6 sm:px-6 lg:px-8">
                @yield('content')
            </main>

            {{-- Footer --}}
            <footer class="border-t border-slate-200 bg-white/70 px-4 py-4 text-center text-xs text-slate-500 sm:px-6 lg:px-8">
                © {{ date('Y') }} {{ $siteName }} — Admin Panel
            </footer>
        </div>
    </div>

    {{-- SweetAlert2 --}}
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

    {{-- Session Success Toast --}}
    @if(session('success'))
        <script>
            Swal.fire({
                toast: true,
                position: 'top-end',
                icon: 'success',
                title: @json(session('success')),
                showConfirmButton: false,
                timer: 2500,
                timerProgressBar: true,
            });
        </script>
    @endif

    {{-- Session Error Toast --}}
    @if(session('error'))
        <script>
            Swal.fire({
                toast: true,
                position: 'top-end',
                icon: 'error',
                title: @json(session('error')),
                showConfirmButton: false,
                timer: 2200,
                timerProgressBar: true,
            });
        </script>
    @endif

    {{-- Live Polling Notification Script --}}
    <script>
        let previousPendingCount = {{ (int) $pendingRequestCount }};
        const isSubscriptionRequestPage = @json($isSubscriptionRequestPage);

        function updateNotificationBadges(count) {
            const topBadge = document.getElementById('request-badge');
            const dropdownBadge = document.getElementById('dropdown-request-badge');

            if (topBadge) {
                if (!isSubscriptionRequestPage && count > 0) {
                    topBadge.textContent = count > 99 ? '99+' : count;
                    topBadge.classList.remove('hidden');
                    topBadge.classList.add('flex');
                } else {
                    topBadge.classList.add('hidden');
                    topBadge.classList.remove('flex');
                }
            }

            if (dropdownBadge) {
                if (count > 0) {
                    dropdownBadge.textContent = count > 99 ? '99+' : count;
                    dropdownBadge.classList.remove('hidden');
                    dropdownBadge.classList.add('inline-flex');
                } else {
                    dropdownBadge.classList.add('hidden');
                    dropdownBadge.classList.remove('inline-flex');
                }
            }
        }

        function showNewRequestToast() {
            Swal.fire({
                toast: true,
                position: 'top-end',
                icon: 'info',
                title: 'New subscription request received',
                showConfirmButton: false,
                timer: 2200,
                timerProgressBar: true,
            });
        }

        async function fetchPendingRequestCount() {
            try {
                const response = await fetch("{{ route('admin.notifications.pending') }}", {
                    method: 'GET',
                    headers: {
                        'X-Requested-With': 'XMLHttpRequest',
                        'Accept': 'application/json'
                    }
                });

                if (!response.ok) {
                    throw new Error('Request failed with status ' + response.status);
                }

                const data = await response.json();
                const count = Number(data.count ?? 0);

                updateNotificationBadges(count);

                if (count > previousPendingCount) {
                    showNewRequestToast();
                }

                previousPendingCount = count;
            } catch (error) {
                console.log('Notification polling error:', error);
            }
        }

        updateNotificationBadges(previousPendingCount);
        setInterval(fetchPendingRequestCount, 5000);
    </script>

    @stack('scripts')
</body>
</html>