<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="csrf-token" content="{{ csrf_token() }}">
        <title>{{ config('app.name', 'SaaS Admin') }}</title>
        @vite(['resources/css/app.css', 'resources/js/app.js'])
        <script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"></script>
        <script>
            // Function to safely fetch unread counts with error handling
            function fetchUnreadCount(routeName, targetElement) {
                fetch(routeName)
                    .then(response => {
                        if (!response.ok) {
                            throw new Error('Network response was not ok');
                        }
                        return response.json();
                    })
                    .then(data => {
                        if (targetElement && targetElement.__x) {
                            targetElement.__x.unreadCount = data.count || 0;
                        }
                    })
                    .catch(error => {
                        console.warn('Failed to fetch unread count for ' + routeName + ':', error);
                        // Set count to 0 on error
                        if (targetElement && targetElement.__x) {
                            targetElement.__x.unreadCount = 0;
                        }
                    });
            }

            // Auto-refresh badge counts every 30 seconds
            setInterval(() => {
                // Refresh chat unread count
                const chatElement = document.querySelector('[x-data*="chat"]');
                if (chatElement) {
                    fetchUnreadCount('{{ route('admin.chat.unread-count') }}', chatElement);
                }
                
                // Refresh notification unread count
                const notificationElement = document.querySelector('[x-data*="notifications"]');
                if (notificationElement) {
                    fetchUnreadCount('{{ route('admin.notifications.unread-count') }}', notificationElement);
                }
            }, 30000);

            // Initial load
            document.addEventListener('DOMContentLoaded', function() {
                const chatElement = document.querySelector('[x-data*="chat"]');
                const notificationElement = document.querySelector('[x-data*="notifications"]');
                
                if (chatElement) {
                    fetchUnreadCount('{{ route('admin.chat.unread-count') }}', chatElement);
                }
                if (notificationElement) {
                    fetchUnreadCount('{{ route('admin.notifications.unread-count') }}', notificationElement);
                }
            });
        </script>
        <style>
            [x-cloak] { display: none !important; }
        </style>
    </head>
    <body class="font-sans antialiased text-gray-900 bg-gray-100" x-data="{ sidebarOpen: true }">
        <div class="flex h-screen overflow-hidden">
            <!-- Sidebar -->
            <div :class="sidebarOpen ? 'w-64' : 'w-20'" class="bg-indigo-900 text-white flex-shrink-0 flex flex-col h-full transition-all duration-300">
                <div class="flex-shrink-0 flex items-center" :class="sidebarOpen ? 'p-6 justify-between' : 'p-4 justify-center'">
                    <div x-show="sidebarOpen" class="overflow-hidden whitespace-nowrap">
                        <h1 class="text-2xl font-bold text-white">SaaS Admin</h1>
                        <p class="text-xs text-indigo-300 mt-1">Super Admin Console</p>
                    </div>
                    <button @click="sidebarOpen = !sidebarOpen" class="text-indigo-300 hover:text-white focus:outline-none" :class="sidebarOpen ? '' : 'mb-4'">
                        <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h16M4 18h16" />
                        </svg>
                    </button>
                </div>
                
                <!-- Scrollable Navigation -->
                <div class="flex-1 overflow-y-auto scrollbar-thin scrollbar-thumb-indigo-700 scrollbar-track-indigo-900">
                    <nav class="mt-2 space-y-1 px-2 pb-4">
                        <a href="{{ route('dashboard') }}" class="block py-3 rounded transition flex items-center {{ request()->routeIs('dashboard') ? 'bg-indigo-800 text-white' : 'text-indigo-200 hover:bg-indigo-800 hover:text-white' }}" :class="sidebarOpen ? 'px-4' : 'px-2 justify-center'" :title="!sidebarOpen ? 'Dashboard' : ''">
                            <span class="inline-block w-5 text-center text-xl" :class="sidebarOpen ? 'mr-2' : ''">📊</span> 
                            <span x-show="sidebarOpen" class="whitespace-nowrap">Dashboard</span>
                        </a>

                        @if(auth()->user()->hasRole(['Admin', 'Developer']) || auth()->user()->hasPermissionTo('manage-tenants'))
                        <a href="{{ route('admin.tenants.index') }}" class="block py-3 rounded transition flex items-center {{ request()->routeIs('admin.tenants.*') ? 'bg-indigo-800 text-white' : 'text-indigo-200 hover:bg-indigo-800 hover:text-white' }}" :class="sidebarOpen ? 'px-4' : 'px-2 justify-center'" :title="!sidebarOpen ? 'Tenants' : ''">
                            <span class="inline-block w-5 text-center text-xl" :class="sidebarOpen ? 'mr-2' : ''">🏢</span>
                            <span x-show="sidebarOpen" class="whitespace-nowrap">Tenants</span>
                        </a>
                        <a href="{{ route('admin.tenant-categories.index') }}" class="block py-3 rounded transition flex items-center {{ request()->routeIs('admin.tenant-categories.*') ? 'bg-indigo-800 text-white' : 'text-indigo-200 hover:bg-indigo-800 hover:text-white' }}" :class="sidebarOpen ? 'px-4' : 'px-2 justify-center'" :title="!sidebarOpen ? 'Tenant Categories' : ''">
                            <span class="inline-block w-5 text-center text-xl" :class="sidebarOpen ? 'mr-2' : ''">📁</span>
                            <span x-show="sidebarOpen" class="whitespace-nowrap">Tenant Categories</span>
                        </a>
                        @endif

                        @if(auth()->user()->hasRole(['Admin', 'Developer']) || auth()->user()->hasPermissionTo('manage-plans'))
                        <a href="{{ route('admin.subscriptions.index') }}" class="block py-3 rounded transition flex items-center {{ request()->routeIs('admin.subscriptions.*') ? 'bg-indigo-800 text-white' : 'text-indigo-200 hover:bg-indigo-800 hover:text-white' }}" :class="sidebarOpen ? 'px-4' : 'px-2 justify-center'" :title="!sidebarOpen ? 'Subscriptions' : ''">
                            <span class="inline-block w-5 text-center text-xl" :class="sidebarOpen ? 'mr-2' : ''">💳</span>
                            <span x-show="sidebarOpen" class="whitespace-nowrap">Subscriptions</span>
                        </a>
                        <a href="{{ route('admin.plans.index') }}" class="block py-3 rounded transition flex items-center {{ request()->routeIs('admin.plans.*') ? 'bg-indigo-800 text-white' : 'text-indigo-200 hover:bg-indigo-800 hover:text-white' }}" :class="sidebarOpen ? 'px-4' : 'px-2 justify-center'" :title="!sidebarOpen ? 'Plans' : ''">
                            <span class="inline-block w-5 text-center text-xl" :class="sidebarOpen ? 'mr-2' : ''">📋</span>
                            <span x-show="sidebarOpen" class="whitespace-nowrap">Plans</span>
                        </a>
                        @endif

                        @if(auth()->user()->hasRole(['Admin', 'Developer']) || auth()->user()->hasPermissionTo('manage-users'))
                        <a href="{{ route('admin.users.index') }}" class="block py-3 rounded transition flex items-center {{ request()->routeIs('admin.users.*') ? 'bg-indigo-800 text-white' : 'text-indigo-200 hover:bg-indigo-800 hover:text-white' }}" :class="sidebarOpen ? 'px-4' : 'px-2 justify-center'" :title="!sidebarOpen ? 'Users' : ''">
                            <span class="inline-block w-5 text-center text-xl" :class="sidebarOpen ? 'mr-2' : ''">👥</span>
                            <span x-show="sidebarOpen" class="whitespace-nowrap">Users</span>
                        </a>
                        @endif

                        @if(auth()->user()->hasRole(['Admin', 'Developer']) || auth()->user()->hasPermissionTo('manage-roles'))
                        <a href="{{ route('admin.roles.index') }}" class="block py-3 rounded transition flex items-center {{ request()->routeIs('admin.roles.*') ? 'bg-indigo-800 text-white' : 'text-indigo-200 hover:bg-indigo-800 hover:text-white' }}" :class="sidebarOpen ? 'px-4' : 'px-2 justify-center'" :title="!sidebarOpen ? 'Roles & Permissions' : ''">
                            <span class="inline-block w-5 text-center text-xl" :class="sidebarOpen ? 'mr-2' : ''">🛡️</span>
                            <span x-show="sidebarOpen" class="whitespace-nowrap">Roles & Permissions</span>
                        </a>
                        @endif

                        @if(auth()->user()->hasRole(['Admin', 'Developer']) || auth()->user()->hasPermissionTo('manage-settings'))
                        <a href="{{ route('admin.security.index') }}" class="block py-3 rounded transition flex items-center {{ request()->routeIs('admin.security.*') ? 'bg-indigo-800 text-white' : 'text-indigo-200 hover:bg-indigo-800 hover:text-white' }}" :class="sidebarOpen ? 'px-4' : 'px-2 justify-center'" :title="!sidebarOpen ? 'Security' : ''">
                            <span class="inline-block w-5 text-center text-xl" :class="sidebarOpen ? 'mr-2' : ''">🔒</span>
                            <span x-show="sidebarOpen" class="whitespace-nowrap">Security</span>
                        </a>
                        <a href="{{ route('admin.settings.index') }}" class="block py-3 rounded transition flex items-center {{ request()->routeIs('admin.settings.*') ? 'bg-indigo-800 text-white' : 'text-indigo-200 hover:bg-indigo-800 hover:text-white' }}" :class="sidebarOpen ? 'px-4' : 'px-2 justify-center'" :title="!sidebarOpen ? 'Site Settings' : ''">
                            <span class="inline-block w-5 text-center text-xl" :class="sidebarOpen ? 'mr-2' : ''">⚙️</span>
                            <span x-show="sidebarOpen" class="whitespace-nowrap">Site Settings</span>
                        </a>
                        @endif

                        @if(auth()->user()->hasRole(['Admin', 'Developer', 'Guest']) || auth()->user()->hasPermissionTo('view-reports'))
                        <div x-show="sidebarOpen" class="px-4 py-2 text-xs font-semibold text-indigo-300 uppercase tracking-wider mt-2">
                            Reports
                        </div>
                        <a href="{{ route('admin.reports.index') }}" class="block py-3 rounded transition flex items-center {{ request()->routeIs('admin.reports.*') ? 'bg-indigo-800 text-white' : 'text-indigo-200 hover:bg-indigo-800 hover:text-white' }}" :class="sidebarOpen ? 'px-4' : 'px-2 justify-center'" :title="!sidebarOpen ? 'Reports Dashboard' : ''">
                            <span class="inline-block w-5 text-center text-xl" :class="sidebarOpen ? 'mr-2' : ''">📈</span>
                            <span x-show="sidebarOpen" class="whitespace-nowrap">Reports Dashboard</span>
                        </a>
                        @endif
                        @if(auth()->user()->hasRole(['Admin', 'Developer']) || auth()->user()->hasPermissionTo('manage-settings'))
                        <a href="{{ route('admin.payment.index') }}" class="block py-3 rounded transition flex items-center {{ request()->routeIs('admin.payment.*') ? 'bg-indigo-800 text-white' : 'text-indigo-200 hover:bg-indigo-800 hover:text-white' }}" :class="sidebarOpen ? 'px-4' : 'px-2 justify-center'" :title="!sidebarOpen ? 'Payment Settings' : ''">
                            <span class="inline-block w-5 text-center text-xl" :class="sidebarOpen ? 'mr-2' : ''">💰</span>
                            <span x-show="sidebarOpen" class="whitespace-nowrap">Payment Settings</span>
                        </a>
                        @endif

                        <div x-show="sidebarOpen" class="px-4 py-2 text-xs font-semibold text-indigo-300 uppercase tracking-wider mt-2">
                            Communication
                        </div>
                        <a href="{{ route('admin.chat.index') }}" class="block py-3 rounded transition flex items-center text-indigo-200 hover:bg-indigo-800 hover:text-white px-4" :class="sidebarOpen ? 'px-4' : 'px-2 justify-center'" :title="!sidebarOpen ? 'Live Chat' : ''" x-data="{ unreadCount: 0 }">
                            <span class="inline-block w-5 text-center text-xl" :class="sidebarOpen ? 'mr-2' : ''">💬</span>
                            <span x-show="sidebarOpen" class="whitespace-nowrap">Live Chat</span>
                            <span x-show="unreadCount > 0" class="ml-2 inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-red-100 text-red-800" x-text="unreadCount"></span>
                        </a>
                        <a href="{{ route('admin.notifications.index') }}" class="block py-3 rounded transition flex items-center {{ request()->routeIs('admin.notifications.*') ? 'bg-indigo-800 text-white' : 'text-indigo-200 hover:bg-indigo-800 hover:text-white' }}" :class="sidebarOpen ? 'px-4' : 'px-2 justify-center'" :title="!sidebarOpen ? 'Notifications' : ''" x-data="{ unreadCount: 0 }">
                            <span class="inline-block w-5 text-center text-xl" :class="sidebarOpen ? 'mr-2' : ''">🔔</span>
                            <span x-show="sidebarOpen" class="whitespace-nowrap">Notifications</span>
                            <span x-show="unreadCount > 0" class="ml-2 inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-red-100 text-red-800" x-text="unreadCount"></span>
                        </a>
                    </nav>
                </div>

                <!-- Footer User Profile -->
                <div class="bg-indigo-900 border-t border-indigo-800 flex-shrink-0" :class="sidebarOpen ? 'p-6' : 'p-2'">
                    <div class="flex items-center mb-4 hover:bg-indigo-800 rounded p-2 transition" :class="sidebarOpen ? '' : 'justify-center mb-0'">
                        <div class="h-8 w-8 rounded-full bg-indigo-500 flex items-center justify-center text-white font-bold" :class="sidebarOpen ? 'mr-3' : ''">
                            {{ substr(Auth::user()->name, 0, 1) }}
                        </div>
                        <div x-show="sidebarOpen">
                            <p class="text-sm font-medium text-white">{{ Auth::user()->name }}</p>
                            <p class="text-xs text-indigo-300">{{ Auth::user()->roles->pluck('name')->implode(', ') ?: 'User' }}</p>
                        </div>
                    </div>
                    <form method="POST" action="{{ route('logout') }}" x-show="sidebarOpen">
                        @csrf
                        <button type="submit" class="flex items-center text-indigo-300 hover:text-white transition text-sm">
                            <span class="mr-2">🚪</span> Logout
                        </button>
                    </form>
                    <form method="POST" action="{{ route('logout') }}" x-show="!sidebarOpen" class="flex justify-center">
                        @csrf
                        <button type="submit" class="text-indigo-300 hover:text-white transition" title="Logout">
                            <span class="text-xl">🚪</span>
                        </button>
                    </form>
                </div>
            </div>

            <!-- Main Content -->
            <div class="flex-1 flex flex-col overflow-hidden">
                <!-- Top Header (Optional, mostly for mobile menu toggle if added later) -->
                @if (isset($header))
                    <header class="bg-white shadow-sm z-10">
                        <div class="max-w-7xl mx-auto py-4 px-4 sm:px-6 lg:px-8 flex items-center justify-between">
                            <div>
                                {{ $header }}
                            </div>
                            <div class="flex items-center space-x-4">
                                <!-- Chat Icon -->
                                <a href="{{ route('admin.chat.index') }}" class="relative text-gray-600 hover:text-gray-800 transition" x-data="{ unreadCount: 0 }">
                                    <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z"></path>
                                    </svg>
                                    <span x-show="unreadCount > 0" class="absolute -top-1 -right-1 inline-flex items-center justify-center px-2 py-1 text-xs font-bold leading-none text-white bg-red-500 rounded-full" x-text="unreadCount"></span>
                                </a>
                                
                                <!-- Notifications Icon -->
                                <a href="{{ route('admin.notifications.index') }}" class="relative text-gray-600 hover:text-gray-800 transition" x-data="{ unreadCount: 0 }">
                                    <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 17h5l-1.405-1.405A2.032 2.032 0 0118 14.158V11a6.002 6.002 0 00-4-5.659V5a2 2 0 10-4 0v.341C7.67 6.165 6 8.388 6 11v3.159c0 .538-.214 1.055-.595 1.436L4 17h5m6 0v1a3 3 0 11-6 0v-1m6 0H9"></path>
                                    </svg>
                                    <span x-show="unreadCount > 0" class="absolute -top-1 -right-1 inline-flex items-center justify-center px-2 py-1 text-xs font-bold leading-none text-white bg-red-500 rounded-full" x-text="unreadCount"></span>
                                </a>
                            </div>
                        </div>
                    </header>
                @endif

                <!-- Page Content -->
                <main class="flex-1 overflow-x-hidden overflow-y-auto bg-gray-100">
                    {{ $slot }}
                </main>
            </div>
        </div>
        @stack('scripts')
    </body>
</html>
