<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <title>@yield('title', 'Dashboard') — Harcourts Marketing Portal</title>
    <!-- Tailwind CSS CDN -->
    <script src="https://cdn.tailwindcss.com"></script>
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        harcourts: {
                            navy: '#001A3D',
                            blue: '#00529B',
                            light: '#0072CE',
                            accent: '#003366',
                            bg: '#F4F6F9',
                        }
                    }
                }
            }
        }
    </script>
    <!-- Alpine.js CDN -->
    <script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"></script>
    <style>
        [x-cloak] { display: none !important; }
    </style>
</head>
<body class="bg-harcourts-bg font-sans text-slate-800 min-h-screen flex flex-col"
    x-data="notificationPoller()"
    x-init="initPoller()">

    <!-- Top Navigation Header -->
    <header class="bg-harcourts-navy text-white border-b border-blue-900 sticky top-0 z-40 shadow-md">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div class="flex items-center justify-between h-16">

                <!-- Brand & Logo -->
                <div class="flex items-center space-x-3">
                    <a href="{{ route('dashboard') }}" class="flex items-center space-x-3 group">
                        <div class="w-9 h-9 rounded bg-harcourts-blue flex items-center justify-center font-black text-white text-lg tracking-tighter shadow-sm group-hover:bg-blue-600 transition-colors">
                            H
                        </div>
                        <div>
                            <span class="font-bold text-lg tracking-tight block leading-tight">HARCOURTS</span>
                            <span class="text-[10px] text-blue-200 uppercase tracking-widest block font-medium">Marketing & Proofing Portal</span>
                        </div>
                    </a>
                </div>

                <!-- Navigation Links (Role Based) -->
                <nav class="hidden md:flex items-center space-x-1">
                    <a href="{{ route('dashboard') }}" class="px-3 py-2 rounded-md text-xs font-semibold uppercase tracking-wider transition-colors {{ request()->routeIs('dashboard') ? 'bg-harcourts-blue text-white' : 'text-blue-100 hover:bg-blue-900/50 hover:text-white' }}">
                        Dashboard
                    </a>

                    @if(auth()->user()->isHarcourtsAdmin() || auth()->user()->isSuperAdmin())
                        <a href="{{ route('requests.create') }}" class="px-3 py-2 rounded-md text-xs font-semibold uppercase tracking-wider bg-emerald-600 hover:bg-emerald-700 text-white transition-colors flex items-center space-x-1 shadow-sm">
                            <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"/></svg>
                            <span>New Request</span>
                        </a>
                    @endif

                    <a href="{{ route('requests.index') }}" class="px-3 py-2 rounded-md text-xs font-semibold uppercase tracking-wider transition-colors {{ request()->routeIs('requests.index') ? 'bg-harcourts-blue text-white' : 'text-blue-100 hover:bg-blue-900/50 hover:text-white' }}">
                        Requests
                    </a>

                    @if(auth()->user()->isDesigner() || auth()->user()->isSuperAdmin())
                        <a href="{{ route('reports.index') }}" class="px-3 py-2 rounded-md text-xs font-semibold uppercase tracking-wider transition-colors {{ request()->routeIs('reports.index') ? 'bg-harcourts-blue text-white' : 'text-blue-100 hover:bg-blue-900/50 hover:text-white' }}">
                            Reports
                        </a>
                    @endif

                    @if(auth()->user()->isSuperAdmin())
                        <div class="relative" x-data="{ open: false }">
                            <button @click="open = !open" class="px-3 py-2 rounded-md text-xs font-semibold uppercase tracking-wider text-blue-100 hover:bg-blue-900/50 flex items-center space-x-1">
                                <span>Administration</span>
                                <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"/></svg>
                            </button>
                            <div x-show="open" @click.away="open = false" x-cloak class="absolute right-0 mt-2 w-48 bg-white text-slate-800 rounded-md shadow-xl border border-slate-200 py-1 z-50 text-xs font-medium">
                                <a href="{{ route('admin.users.index') }}" class="block px-4 py-2 hover:bg-slate-100">User Management</a>
                                <a href="{{ route('admin.agents.index') }}" class="block px-4 py-2 hover:bg-slate-100">Agent Directory</a>
                                <a href="{{ route('admin.request-types.index') }}" class="block px-4 py-2 hover:bg-slate-100">Request Types</a>
                            </div>
                        </div>
                    @endif
                </nav>

                <!-- Right Side Actions & User Menu -->
                <div class="flex items-center space-x-4">
                    <!-- Live Notification Bell Badge -->
                    <div class="relative" x-data="{ open: false }">
                        <button @click="open = !open" class="relative p-2 rounded-full text-blue-200 hover:text-white hover:bg-blue-900/50 focus:outline-none transition-colors">
                            <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" />
                            </svg>
                            <span x-show="unreadCount > 0" x-text="unreadCount" class="absolute top-1 right-1 inline-flex items-center justify-center px-1.5 py-0.5 text-[10px] font-bold leading-none text-white bg-red-600 rounded-full animate-bounce">
                                {{ auth()->user()->unreadNotifications()->count() }}
                            </span>
                        </button>

                        <!-- Notification Dropdown Panel -->
                        <div x-show="open" @click.away="open = false" x-cloak class="absolute right-0 mt-2 w-80 sm:w-96 bg-white text-slate-800 rounded-lg shadow-2xl border border-slate-200 py-2 z-50">
                            <div class="px-4 py-2 border-b border-slate-100 flex items-center justify-between">
                                <span class="font-bold text-sm text-slate-800">Notifications</span>
                                <a href="{{ route('notifications.index') }}" class="text-xs text-harcourts-blue font-semibold hover:underline">View All</a>
                            </div>
                            <div class="max-h-72 overflow-y-auto divide-y divide-slate-100">
                                <template x-if="notifications.length === 0">
                                    <div class="px-4 py-6 text-center text-xs text-slate-400">No new notifications</div>
                                </template>
                                <template x-for="item in notifications" :key="item.id">
                                    <a :href="item.url" class="block px-4 py-3 hover:bg-slate-50 transition-colors">
                                        <div class="font-semibold text-xs text-slate-900" x-text="item.title"></div>
                                        <div class="text-xs text-slate-600 mt-0.5 line-clamp-2" x-text="item.message"></div>
                                        <div class="text-[10px] text-slate-400 mt-1" x-text="item.created_at"></div>
                                    </a>
                                </template>
                            </div>
                        </div>
                    </div>

                    <!-- User Profile Dropdown -->
                    <div class="relative" x-data="{ open: false }">
                        <button @click="open = !open" class="flex items-center space-x-2 text-xs text-blue-100 hover:text-white focus:outline-none">
                            <div class="w-8 h-8 rounded-full bg-blue-800 border border-blue-600 flex items-center justify-center font-bold text-white uppercase text-xs shadow-sm">
                                {{ strtoupper(substr(auth()->user()->name, 0, 2)) }}
                            </div>
                            <span class="hidden sm:inline font-semibold">{{ auth()->user()->name }}</span>
                            <span class="px-1.5 py-0.5 text-[10px] rounded uppercase font-bold tracking-wider
                                {{ auth()->user()->isSuperAdmin() ? 'bg-amber-500 text-black' : (auth()->user()->isDesigner() ? 'bg-purple-600 text-white' : 'bg-blue-600 text-white') }}">
                                {{ str_replace('_', ' ', auth()->user()->role) }}
                            </span>
                        </button>
                        <div x-show="open" @click.away="open = false" x-cloak class="absolute right-0 mt-2 w-48 bg-white text-slate-800 rounded-md shadow-xl border border-slate-200 py-1 z-50 text-xs">
                            <div class="px-4 py-2 border-b border-slate-100 font-semibold text-slate-700">
                                {{ auth()->user()->email }}
                            </div>
                            <form method="POST" action="{{ route('logout') }}">
                                @csrf
                                <button type="submit" class="w-full text-left px-4 py-2 hover:bg-slate-100 text-red-600 font-semibold">
                                    Sign Out
                                </button>
                            </form>
                        </div>
                    </div>
                </div>

            </div>
        </div>
    </header>

    <!-- Global Toast Alert Container -->
    <div class="fixed top-20 right-4 z-50 space-y-2 w-80 pointer-events-none">
        <template x-for="toast in toasts" :key="toast.id">
            <div class="pointer-events-auto bg-slate-900 text-white p-4 rounded-lg shadow-2xl border-l-4 border-harcourts-blue flex items-start justify-between transform transition-all duration-300">
                <div>
                    <div class="font-bold text-xs uppercase tracking-wider text-blue-400" x-text="toast.title"></div>
                    <div class="text-xs text-slate-200 mt-1" x-text="toast.message"></div>
                    <template x-if="toast.url">
                        <a :href="toast.url" class="inline-block text-[11px] font-bold text-blue-300 hover:text-white underline mt-2">View Details &rarr;</a>
                    </template>
                </div>
                <button @click="removeToast(toast.id)" class="text-slate-400 hover:text-white text-xs ml-2">&times;</button>
            </div>
        </template>
    </div>

    <!-- Main Content Area -->
    <main class="flex-1 max-w-7xl w-full mx-auto px-4 sm:px-6 lg:px-8 py-6">
        @if (session('success'))
            <div class="mb-6 bg-emerald-50 border-l-4 border-emerald-500 p-4 text-emerald-800 rounded-r shadow-sm flex items-center justify-between">
                <div class="flex items-center space-x-2 text-sm font-medium">
                    <svg class="w-5 h-5 text-emerald-600 flex-shrink-0" fill="currentColor" viewBox="0 0 20 20"><path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clip-rule="evenodd"/></svg>
                    <span>{{ session('success') }}</span>
                </div>
            </div>
        @endif

        @if (session('error'))
            <div class="mb-6 bg-rose-50 border-l-4 border-rose-500 p-4 text-rose-800 rounded-r shadow-sm flex items-center justify-between">
                <div class="flex items-center space-x-2 text-sm font-medium">
                    <svg class="w-5 h-5 text-rose-600 flex-shrink-0" fill="currentColor" viewBox="0 0 20 20"><path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clip-rule="evenodd"/></svg>
                    <span>{{ session('error') }}</span>
                </div>
            </div>
        @endif

        @yield('content')
    </main>

    <!-- Footer -->
    <footer class="bg-white border-t border-slate-200 py-4 mt-auto">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 text-center text-xs text-slate-500 flex flex-col sm:flex-row items-center justify-between gap-2">
            <div>
                &copy; {{ date('Y') }} <strong>Harcourts Real Estate</strong> — Marketing Request & Proofing Portal.
            </div>
            <div class="text-[11px] text-slate-400">
                Timezone: {{ config('app.timezone', 'Pacific/Auckland') }} | Target Server: cPanel Compatible
            </div>
        </div>
    </footer>

    <!-- Alpine.js AJAX Notification Polling Script -->
    <script>
        function notificationPoller() {
            return {
                unreadCount: {{ auth()->user()->unreadNotifications()->count() }},
                notifications: [],
                lastTimestamp: null,
                toasts: [],

                initPoller() {
                    this.poll();
                    // Poll every 8 seconds
                    setInterval(() => this.poll(), 8000);
                },

                async poll() {
                    try {
                        let url = '{{ route("notifications.poll") }}';
                        if (this.lastTimestamp) {
                            url += '?since=' + encodeURIComponent(this.lastTimestamp);
                        }

                        const response = await fetch(url, {
                            headers: {
                                'X-Requested-With': 'XMLHttpRequest',
                                'Accept': 'application/json',
                            }
                        });

                        if (!response.ok) return;

                        const data = await response.json();
                        
                        // Check for new notifications to trigger toast alerts
                        if (data.unread_count > this.unreadCount) {
                            if (data.notifications && data.notifications.length > 0) {
                                const latest = data.notifications[0];
                                this.addToast(latest.title, latest.message, latest.url);
                            }
                        }

                        this.unreadCount = data.unread_count;
                        this.notifications = data.notifications || [];
                        this.lastTimestamp = data.timestamp;

                    } catch (e) {
                        console.log('Polling check silent catch:', e);
                    }
                },

                addToast(title, message, url = null) {
                    const id = Date.now();
                    this.toasts.push({ id, title, message, url });
                    setTimeout(() => this.removeToast(id), 6000);
                },

                removeToast(id) {
                    this.toasts = this.toasts.filter(t => t.id !== id);
                }
            }
        }
    </script>
</body>
</html>
