<header class="h-16 bg-white border-b border-slate-200 flex items-center justify-between px-6 flex-shrink-0 z-10">
    <!-- Active branch context selector indicators -->
    <div class="flex items-center gap-3">
        <span class="text-lg">🏢</span>
        <div>
            <h2 class="text-xs font-extrabold text-slate-800">
                {{ Auth::user()->company->name ?? 'Teletalk Corp Ltd' }}
            </h2>
            <p class="text-[10px] text-slate-500 font-bold font-mono">
                {{ Auth::user()->branch->name ?? 'HQ (Dhaka)' }} ({{ Auth::user()->branch->code ?? 'HQ-DKA' }})
            </p>
        </div>
    </div>

    <!-- Right indicators: Real-time values, notification bell, system timezone status -->
    <div class="flex items-center gap-6">
        <!-- Live System Timestamp Indicator -->
        <div class="hidden lg:flex items-center gap-2">
            <span class="relative flex h-2 w-2">
                <span class="animate-ping absolute inline-flex h-full w-full rounded-full bg-emerald-400 opacity-75"></span>
                <span class="relative inline-flex rounded-full h-2 w-2 bg-emerald-500"></span>
            </span>
            <span class="text-[10px] text-slate-500 font-bold font-mono" id="topbar-live-time">
                {{ date('Y-m-d H:i') }} UTC
            </span>
        </div>

        <!-- Dynamic Notification Bell & Dropdown panel -->
        @php
            $user = Auth::user();
            $companyId = $user->company_id ?? null;
            $isSuperAdmin = $user ? $user->isSuperAdmin() : false;
            $notifications = [];

            if ($user && $companyId) {
                // 1. Pending Transactions (Vouchers waiting for approval)
                $pendingTxQuery = \App\Models\CashTransaction::where('company_id', $companyId)
                    ->where('status', 'Pending');
                if (!$isSuperAdmin) {
                    $pendingTxQuery->where('branch_id', $user->branch_id);
                }
                $pendingTx = $pendingTxQuery->latest()->take(5)->get();

                // 2. Latest transactions of last 48 hours that are Approved or Rejected to notify users
                $recentTx = \App\Models\CashTransaction::where('company_id', $companyId)
                    ->whereIn('status', ['Approved', 'Rejected'])
                    ->where('updated_at', '>=', now()->subDays(2))
                    ->latest()
                    ->take(5)
                    ->get();

                // 3. Recent activity logs inside company users (excluding self to reduce noise)
                $recentLogs = \App\Models\ActivityLog::whereIn('user_id', function($query) use ($companyId) {
                    $query->select('id')->from('users')->where('company_id', $companyId);
                })
                ->where('user_id', '!=', $user->id)
                ->latest()
                ->take(5)
                ->get();

                foreach ($pendingTx as $tx) {
                    $notifications[] = [
                        'id' => 'tx-pending-' . $tx->id,
                        'title' => '⏳ ভাউচার অনুমোদন পেন্ডিং',
                        'body' => $tx->created_by_name . ' কর্তৃক "' . $tx->particulars . '" বাবদ ভাউচার পোস্টিং।',
                        'amount' => $tx->amount,
                        'time' => $tx->created_at->diffForHumans(),
                        'link' => route('cashbook.index'),
                        'type' => 'pending',
                        'time_raw' => $tx->created_at->timestamp
                    ];
                }

                foreach ($recentTx as $tx) {
                    $statusBn = $tx->status === 'Approved' ? 'অনুমোদিত' : 'প্রত্যাখ্যাত';
                    $emoji = $tx->status === 'Approved' ? '✅' : '❌';
                    $notifications[] = [
                        'id' => 'tx-status-' . $tx->id . '-' . $tx->updated_at->timestamp,
                        'title' => $emoji . ' ভাউচার সিদ্ধান্তঃ ' . $statusBn,
                        'body' => 'ভাউচার নং ' . $tx->voucher_no . ' (' . $tx->particulars . ') ' . $statusBn . ' হয়েছে।',
                        'amount' => $tx->amount,
                        'time' => $tx->updated_at->diffForHumans(),
                        'link' => route('cashbook.index'),
                        'type' => $tx->status === 'Approved' ? 'approved' : 'rejected',
                        'time_raw' => $tx->updated_at->timestamp
                    ];
                }

                foreach ($recentLogs as $log) {
                    $notifications[] = [
                        'id' => 'log-' . $log->id,
                        'title' => '🛡️ অডিট বা পরিচালনা ট্রেইল',
                        'body' => $log->user_name . ' (' . $log->role . '): ' . $log->description,
                        'amount' => null,
                        'time' => $log->created_at->diffForHumans(),
                        'link' => '#',
                        'type' => 'log',
                        'time_raw' => $log->created_at->timestamp
                    ];
                }

                // Sort notifications by time DESC
                usort($notifications, function($a, $b) {
                    return $b['time_raw'] - $a['time_raw'];
                });

                // Slice to show max 8
                $notifications = array_slice($notifications, 0, 8);
            }
        @endphp

        <div class="relative inline-block text-left" id="notification-dropdown-wrapper">
            <button onclick="toggleNotificationDropdown()" class="relative focus:outline-none hover:bg-slate-50 p-2 rounded-xl transition cursor-pointer flex items-center justify-center">
                <span class="text-base text-slate-600">🔔</span>
                <span id="notif-badge" class="hidden absolute top-1 right-1 h-4 w-4 bg-rose-500 text-white font-mono font-black text-[9px] rounded-full flex items-center justify-center animate-pulse">
                    <span id="notif-badge-count">0</span>
                </span>
            </button>

            <!-- Notification Dropdown Menu -->
            <div id="notification-dropdown" class="hidden absolute right-0 mt-2 w-80 md:w-96 bg-white border border-slate-200 rounded-2xl shadow-xl z-50 overflow-hidden py-1">
                <div class="px-4 py-3 border-b border-slate-100 flex items-center justify-between bg-slate-50">
                    <span class="text-xs font-black text-slate-800 tracking-wider">🔔 বিজ্ঞপ্তি কেন্দ্র (Notifications)</span>
                    @if(count($notifications) > 0)
                        <button onclick="markAllAsRead()" class="text-[10px] text-indigo-600 hover:text-indigo-800 font-extrabold hover:underline">
                            সবগুলো পঠিত মার্ক করুন
                        </button>
                    @endif
                </div>

                <div class="max-h-[350px] overflow-y-auto divide-y divide-slate-100" id="notification-list-container">
                    @forelse($notifications as $notif)
                        <div id="notif-item-{{ $notif['id'] }}" 
                             onclick="handleNotifClick('{{ $notif['id'] }}', '{{ $notif['link'] }}')" 
                             class="p-3.5 hover:bg-slate-50/70 transition cursor-pointer flex items-start gap-2.5 relative bg-white">
                            
                            <div class="flex-1 min-w-0">
                                <div class="flex items-center justify-between mb-1">
                                    <span class="text-xs font-extrabold text-slate-800 tracking-tight">{{ $notif['title'] }}</span>
                                    <span class="text-[9px] text-slate-400 font-bold whitespace-nowrap">{{ $notif['time'] }}</span>
                                </div>
                                <p class="text-[11px] text-slate-500 leading-normal font-semibold">{{ $notif['body'] }}</p>
                                
                                @if($notif['amount'] !== null)
                                    <div class="mt-1.5 flex items-center gap-1.5">
                                        <span class="text-[10px] font-bold text-slate-400 uppercase tracking-wider">পরিমাণঃ</span>
                                        <span class="font-mono font-black text-[11px] px-2 py-0.5 rounded {{ $notif['type'] === 'pending' ? 'bg-amber-50 text-amber-700 border border-amber-200/50' : 'bg-emerald-50 text-emerald-700 border border-emerald-200/50' }}">
                                            ৳{{ number_format($notif['amount'], 2) }}
                                        </span>
                                    </div>
                                @endif
                            </div>

                            <!-- Unread Marker dot -->
                            <div id="notif-dot-{{ $notif['id'] }}" class="h-2 w-2 rounded-full bg-blue-500 shrink-0 mt-1.5 ml-1 hidden"></div>
                        </div>
                    @empty
                        <div class="py-8 text-center text-slate-400 text-xs font-semibold">
                            ☘️ নতুন বিজ্ঞপ্তির কোনো মেসেজ নেই
                        </div>
                    @endforelse
                </div>

                <div class="px-4 py-2 border-t border-slate-100 bg-slate-50 text-center">
                    <a href="{{ route('cashbook.index') }}" class="text-[10px] text-slate-500 hover:text-slate-800 font-extrabold flex items-center justify-center gap-1">
                        🔍 ক্যাশবুক লেনদেন মেমোরি ও অডিট ভিউ
                    </a>
                </div>
            </div>
        </div>

        <!-- Mini profile card -->
        <div class="flex items-center gap-2">
            <img class="w-8 h-8 rounded-lg object-cover bg-slate-100" 
                 src="{{ Auth::user()->photo_url ?: 'https://images.unsplash.com/photo-1535713875002-d1d0cf377fde?auto=format&fit=crop&w=150&q=80' }}" 
                 alt="Avatar">
            <span class="text-[10px] font-extrabold text-slate-700 bg-slate-100 py-1 px-2 rounded-md">
                {{ Auth::user()->role }}
            </span>
        </div>
    </div>
</header>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        refreshNotifications();

        // Close dropdown when clicking outside
        window.addEventListener('click', function(e) {
            const wrapper = document.getElementById('notification-dropdown-wrapper');
            const dropdown = document.getElementById('notification-dropdown');
            if (wrapper && dropdown && !wrapper.contains(e.target)) {
                dropdown.classList.add('hidden');
            }
        });
    });

    function toggleNotificationDropdown() {
        const dropdown = document.getElementById('notification-dropdown');
        if (dropdown) {
            dropdown.classList.toggle('hidden');
        }
    }

    function refreshNotifications() {
        let readIds = [];
        try {
            readIds = JSON.parse(localStorage.getItem('read_notifications') || '[]');
        } catch(e) {
            readIds = [];
        }

        let unreadCount = 0;
        const ids = {!! json_encode(array_column($notifications, 'id')) !!};

        ids.forEach(id => {
            const itemEl = document.getElementById('notif-item-' + id);
            const dotEl = document.getElementById('notif-dot-' + id);
            if (readIds.includes(id)) {
                if (itemEl) {
                    itemEl.classList.remove('bg-blue-50/50');
                    itemEl.classList.add('bg-white');
                    itemEl.classList.add('opacity-75');
                }
                if (dotEl) {
                    dotEl.classList.add('hidden');
                }
            } else {
                unreadCount++;
                if (itemEl) {
                    itemEl.classList.add('bg-blue-50/50');
                    itemEl.classList.remove('bg-white');
                    itemEl.classList.remove('opacity-75');
                }
                if (dotEl) {
                    dotEl.classList.remove('hidden');
                }
            }
        });

        const badgeEl = document.getElementById('notif-badge');
        const badgeCountEl = document.getElementById('notif-badge-count');
        if (badgeEl && badgeCountEl) {
            if (unreadCount > 0) {
                badgeCountEl.innerText = unreadCount;
                badgeEl.classList.remove('hidden');
            } else {
                badgeEl.classList.add('hidden');
            }
        }
    }

    function markAllAsRead() {
        const ids = {!! json_encode(array_column($notifications, 'id')) !!};
        let readIds = [];
        try {
            readIds = JSON.parse(localStorage.getItem('read_notifications') || '[]');
        } catch(e) {
            readIds = [];
        }

        ids.forEach(id => {
            if (!readIds.includes(id)) {
                readIds.push(id);
            }
        });

        localStorage.setItem('read_notifications', JSON.stringify(readIds));
        refreshNotifications();
    }

    function handleNotifClick(id, link) {
        let readIds = [];
        try {
            readIds = JSON.parse(localStorage.getItem('read_notifications') || '[]');
        } catch(e) {
            readIds = [];
        }
        if (!readIds.includes(id)) {
            readIds.push(id);
            localStorage.setItem('read_notifications', JSON.stringify(readIds));
        }
        if (link && link !== '#') {
            window.location.href = link;
        } else {
            refreshNotifications();
        }
    }
</script>
