@php
use Illuminate\Support\Facades\Route;

$user     = auth()->user();
$role     = $user ? $user->roles->first() : null;
$roleName = $role ? $role->name : 'User';

$roleColors = [
    'Super Manager'   => 'bg-purple-500',
    'Manager'         => 'bg-blue-600',
    'Members'         => 'bg-green-500',
    'Trainers'        => 'bg-orange-500',
    'Trainees'        => 'bg-yellow-500',
    'Mentor'          => 'bg-teal-500',
    'Mentee'          => 'bg-cyan-500',
    'Partners'        => 'bg-indigo-500',
    'Contributor'     => 'bg-pink-500',
    'Health Marketor' => 'bg-red-500',
];
$roleBadgeClass = $roleColors[$roleName] ?? 'bg-gray-500';

// Admin/manager roles that can see role-based notifications
$canSeeRoleNotifications = $user && $user->hasAnyRole(['Super Manager', 'Manager']);

// Organisation name for header branding
$org     = \App\Models\Organization::first();
$orgName = $org?->name ?? config('app.name', 'SSHIA');
$orgShort = $org?->short_name ?? $orgName;
@endphp

{{-- ============================================================
     SIDE-HEADER COMPONENT
     Dashboard header that sits beside the sidebar (to its right).
     Background matches sidebar (#4338ca indigo).
     Contains: hamburger toggle, org name branding,
     role-based notifications, common notifications, profile.
     ============================================================ --}}
<header
    x-data="sideHeaderData()"
    x-init="init()"
    @keydown.escape.window="notificationsOpen = false; roleNotificationsOpen = false; profileOpen = false;"
    class="side-header h-16 flex items-center shadow-md transition-all duration-300 w-full"
    style="background-color: #4338ca;"
>
    <div class="h-full w-full px-3 sm:px-4 flex items-center gap-2 sm:gap-3">

        {{-- ── LEFT: hamburger toggle ──────────────────────────────── --}}
        <div class="flex items-center gap-2 flex-shrink-0">
            {{-- Hamburger — calls appLayout store directly, works across all components --}}
            <button
                @click="$store.appLayout.toggleSidebar()"
                class="flex items-center justify-center w-9 h-9 rounded-lg transition-colors duration-200"
                style="background-color: rgba(255,255,255,0.1);"
                onmouseover="this.style.backgroundColor='rgba(255,255,255,0.18)'"
                onmouseout="this.style.backgroundColor='rgba(255,255,255,0.1)'"
                aria-label="Toggle Sidebar"
            >
                <i class="fa-solid fa-bars text-white text-sm"></i>
            </button>
        </div>

        {{-- ── CENTER: Organisation name branding (centred, responsive) ──────── --}}
        <div class="flex-1 flex items-center justify-center min-w-0 px-2">
            {{-- White engraved pill — full name on md+, short name on mobile --}}
            <div class="flex items-center gap-2 px-4 py-2 rounded-lg"
                 style="background: rgba(255,255,255,0.97);
                        box-shadow: inset 0 1px 4px rgba(0,0,0,0.18), 0 1px 0 rgba(255,255,255,0.55);
                        max-width: 100%;">
                {{-- Accent bar (hidden on xs) --}}
                <span class="hidden sm:block w-1 h-6 rounded-full flex-shrink-0"
                      style="background: linear-gradient(180deg, #4338ca 0%, #6366f1 100%);"></span>
                {{-- Full name — hidden on small screens --}}
                <p class="hidden sm:block font-extrabold tracking-wide leading-none whitespace-nowrap"
                   style="font-size: clamp(0.75rem, 1.8vw, 1rem);
                          color: #3730a3;
                          text-shadow: 0 1px 0 rgba(255,255,255,0.8), 0 -1px 0 rgba(0,0,0,0.1);
                          letter-spacing: 0.05em;">
                    {{ strtoupper($orgName) }}
                </p>
                {{-- Short name — shown only on small screens --}}
                <p class="sm:hidden font-extrabold tracking-wide leading-none whitespace-nowrap"
                   style="font-size: clamp(0.7rem, 4vw, 0.9rem);
                          color: #3730a3;
                          text-shadow: 0 1px 0 rgba(255,255,255,0.8), 0 -1px 0 rgba(0,0,0,0.1);
                          letter-spacing: 0.05em;">
                    {{ strtoupper($orgShort) }}
                </p>
            </div>
        </div>

        {{-- ── RIGHT: actions ───────────────────────────────────────── --}}
        <div class="flex items-center gap-1 sm:gap-2 ml-auto flex-shrink-0">

            {{-- Dark mode toggle --}}
            <button
                @click="toggleDarkMode()"
                class="flex items-center justify-center w-9 h-9 rounded-lg transition-colors duration-200"
                style="background-color: rgba(255,255,255,0.08);"
                onmouseover="this.style.backgroundColor='rgba(255,255,255,0.15)'"
                onmouseout="this.style.backgroundColor='rgba(255,255,255,0.08)'"
                aria-label="Toggle Dark Mode"
            >
                <i class="fa-solid text-base transition-colors"
                   :class="darkMode ? 'fa-sun text-yellow-300' : 'fa-moon text-indigo-200'"></i>
            </button>

            {{-- ── Role-based notifications (Super Manager & Manager only) ── --}}
            @if($canSeeRoleNotifications)
            <div class="relative">
                <button
                    @click="roleNotificationsOpen = !roleNotificationsOpen; notificationsOpen = false; profileOpen = false;"
                    class="relative flex items-center justify-center w-9 h-9 rounded-lg transition-colors duration-200"
                    style="background-color: rgba(255,255,255,0.08);"
                    onmouseover="this.style.backgroundColor='rgba(255,255,255,0.15)'"
                    onmouseout="this.style.backgroundColor='rgba(255,255,255,0.08)'"
                    aria-label="Admin Notifications"
                    title="Admin Alerts"
                >
                    <i class="fa-solid fa-shield-halved text-base text-amber-300"></i>
                    <span
                        x-show="roleNotificationCount > 0"
                        x-text="roleNotificationCount > 99 ? '99+' : roleNotificationCount"
                        class="absolute -top-0.5 -right-0.5 min-w-[16px] h-[16px] px-0.5 flex items-center justify-center text-[9px] font-bold text-white bg-amber-500 rounded-full leading-none"
                        style="display:none;"
                    ></span>
                </button>

                {{-- Role notifications dropdown --}}
                <div
                    x-show="roleNotificationsOpen"
                    x-transition:enter="transition ease-out duration-150"
                    x-transition:enter-start="opacity-0 scale-95"
                    x-transition:enter-end="opacity-100 scale-100"
                    x-transition:leave="transition ease-in duration-100"
                    x-transition:leave-start="opacity-100 scale-100"
                    x-transition:leave-end="opacity-0 scale-95"
                    @click.outside="roleNotificationsOpen = false"
                    class="absolute right-0 mt-2 w-80 max-w-[calc(100vw-1rem)] z-[9999] bg-white dark:bg-gray-900 rounded-xl shadow-2xl border border-gray-200/60 dark:border-gray-700/60 overflow-hidden"
                    style="display:none;"
                >
                    <div class="px-4 py-3 border-b border-gray-200 dark:border-gray-700 flex items-center justify-between"
                         style="background: linear-gradient(90deg, #3730a3 0%, #4338ca 60%, #4f46e5 100%);">
                        <h3 class="text-sm font-semibold text-white flex items-center gap-2">
                            <i class="fa-solid fa-shield-halved text-amber-300"></i>
                            Admin Alerts
                        </h3>
                        <button
                            x-show="roleNotificationCount > 0"
                            @click="markAllRoleRead()"
                            class="text-xs text-indigo-200 hover:text-white transition-colors"
                        >Mark all read</button>
                    </div>
                    <div x-show="roleNotificationsLoading" class="px-4 py-6 text-center">
                        <i class="fa-solid fa-spinner fa-spin text-indigo-600"></i>
                    </div>
                    <div x-show="!roleNotificationsLoading" class="max-h-80 overflow-y-auto divide-y divide-gray-100 dark:divide-gray-700/50">
                        <template x-if="roleNotifications.length === 0">
                            <div class="px-4 py-8 text-center">
                                <i class="fa-solid fa-shield-check text-3xl text-indigo-300 mb-2"></i>
                                <p class="text-sm text-gray-500">No admin alerts</p>
                            </div>
                        </template>
                        <template x-for="n in roleNotifications" :key="n.id">
                            <a :href="n.action_url ?? '#'"
                               @click.prevent="markRoleRead(n.id); if(n.action_url) window.location.href = n.action_url"
                               class="flex items-start gap-3 px-4 py-3 hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors cursor-pointer"
                               :class="{'bg-amber-50/50 dark:bg-amber-900/10': !n.is_read}">
                                <div class="flex-shrink-0 w-8 h-8 rounded-full bg-amber-100 dark:bg-amber-900/30 flex items-center justify-center mt-0.5">
                                    <i class="fa-solid text-sm" :class="n.icon ?? 'fa-bell text-amber-500'"></i>
                                </div>
                                <div class="flex-1 min-w-0">
                                    <p class="text-sm font-medium text-gray-900 dark:text-white truncate" x-text="n.title"></p>
                                    <p class="text-xs text-gray-500 mt-0.5 line-clamp-2" x-text="n.message"></p>
                                    <p class="text-xs text-gray-400 mt-1" x-text="n.time_ago"></p>
                                </div>
                                <span x-show="!n.is_read" class="flex-shrink-0 w-2 h-2 bg-amber-500 rounded-full mt-2"></span>
                            </a>
                        </template>
                    </div>
                </div>
            </div>
            @endif

            {{-- ── Common notifications (all users) ──────────────────── --}}
            <div class="relative">
                <button
                    @click="notificationsOpen = !notificationsOpen; roleNotificationsOpen = false; profileOpen = false;"
                    class="relative flex items-center justify-center w-9 h-9 rounded-lg transition-colors duration-200"
                    style="background-color: rgba(255,255,255,0.08);"
                    onmouseover="this.style.backgroundColor='rgba(255,255,255,0.15)'"
                    onmouseout="this.style.backgroundColor='rgba(255,255,255,0.08)'"
                    aria-label="Notifications"
                >
                    <i class="fa-solid fa-bell text-base text-indigo-200"></i>
                    <span
                        x-show="notificationCount > 0"
                        x-text="notificationCount > 99 ? '99+' : notificationCount"
                        class="absolute -top-0.5 -right-0.5 min-w-[16px] h-[16px] px-0.5 flex items-center justify-center text-[9px] font-bold text-white bg-red-500 rounded-full leading-none"
                        style="display:none;"
                    ></span>
                </button>

                {{-- Notifications dropdown --}}
                <div
                    x-show="notificationsOpen"
                    x-transition:enter="transition ease-out duration-150"
                    x-transition:enter-start="opacity-0 scale-95"
                    x-transition:enter-end="opacity-100 scale-100"
                    x-transition:leave="transition ease-in duration-100"
                    x-transition:leave-start="opacity-100 scale-100"
                    x-transition:leave-end="opacity-0 scale-95"
                    @click.outside="notificationsOpen = false"
                    class="absolute right-0 mt-2 w-80 max-w-[calc(100vw-1rem)] z-[9999] bg-white dark:bg-gray-900 rounded-xl shadow-2xl border border-gray-200/60 dark:border-gray-700/60 overflow-hidden"
                    style="display:none;"
                >
                    <div class="px-4 py-3 border-b border-gray-200 dark:border-gray-700 flex items-center justify-between">
                        <h3 class="text-sm font-semibold text-gray-900 dark:text-white">Notifications</h3>
                        <button
                            x-show="notificationCount > 0"
                            @click="markAllRead()"
                            class="text-xs text-indigo-600 dark:text-indigo-400 hover:underline"
                        >Mark all read</button>
                    </div>
                    <div x-show="notificationsLoading" class="px-4 py-6 text-center">
                        <i class="fa-solid fa-spinner fa-spin text-indigo-600"></i>
                    </div>
                    <div x-show="!notificationsLoading" class="max-h-96 overflow-y-auto divide-y divide-gray-100 dark:divide-gray-700/50">
                        <template x-if="notifications.length === 0">
                            <div class="px-4 py-8 text-center">
                                <i class="fa-solid fa-bell-slash text-3xl text-gray-300 mb-2"></i>
                                <p class="text-sm text-gray-500">No notifications</p>
                            </div>
                        </template>
                        <template x-for="n in notifications" :key="n.id">
                            <a :href="n.action_url ?? '#'"
                               @click.prevent="markRead(n.id); if(n.action_url) window.location.href = n.action_url"
                               class="flex items-start gap-3 px-4 py-3 hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors cursor-pointer"
                               :class="{'bg-blue-50/50 dark:bg-blue-900/10': !n.is_read}">
                                <div class="flex-shrink-0 w-8 h-8 rounded-full bg-gray-100 dark:bg-gray-800 flex items-center justify-center mt-0.5">
                                    <i class="fa-solid text-sm" :class="n.icon ?? 'fa-bell text-blue-400'"></i>
                                </div>
                                <div class="flex-1 min-w-0">
                                    <p class="text-sm font-medium text-gray-900 dark:text-white truncate" x-text="n.title"></p>
                                    <p class="text-xs text-gray-500 mt-0.5 line-clamp-2" x-text="n.message"></p>
                                    <p class="text-xs text-gray-400 mt-1" x-text="n.time_ago"></p>
                                </div>
                                <span x-show="!n.is_read" class="flex-shrink-0 w-2 h-2 bg-blue-500 rounded-full mt-2"></span>
                            </a>
                        </template>
                    </div>
                </div>
            </div>

            {{-- ── User profile toggle ────────────────────────────────── --}}
            <div class="relative">
                <button
                    @click="profileOpen = !profileOpen; notificationsOpen = false; roleNotificationsOpen = false;"
                    class="flex items-center gap-2 px-2 py-1.5 rounded-lg transition-colors duration-200"
                    style="background-color: rgba(255,255,255,0.08);"
                    onmouseover="this.style.backgroundColor='rgba(255,255,255,0.15)'"
                    onmouseout="this.style.backgroundColor='rgba(255,255,255,0.08)'"
                    aria-label="User Menu"
                >
                    {{-- Avatar --}}
                    <div class="relative w-8 h-8 rounded-full overflow-hidden bg-gradient-to-br from-green-400 to-green-700 flex items-center justify-center flex-shrink-0"
                         style="box-shadow: 0 0 0 2px rgba(255,255,255,0.4), 0 0 0 4px rgba(229,62,62,0.35);">
                        <img
                            src="{{ $user->avatar_url }}"
                            alt="{{ $user->name }}"
                            class="w-full h-full object-cover"
                            onerror="this.style.display='none'; this.nextElementSibling.style.display='flex';"
                        />
                        <span
                            class="absolute inset-0 flex items-center justify-center text-white font-semibold text-xs"
                            style="display:none;"
                        >{{ $user->initials }}</span>
                    </div>
                    {{-- Name + role (hidden on small screens) --}}
                    <div class="hidden sm:block text-left">
                        <p class="text-xs font-semibold text-white leading-tight truncate max-w-[100px]">{{ $user->name }}</p>
                        <p class="text-[10px] text-indigo-200 leading-tight truncate max-w-[100px]">{{ $roleName }}</p>
                    </div>
                    <i class="fa-solid fa-chevron-down text-[10px] text-indigo-300 hidden sm:block transition-transform duration-200"
                       :class="profileOpen ? 'rotate-180' : 'rotate-0'"></i>
                </button>

                {{-- Profile dropdown --}}
                <div
                    x-show="profileOpen"
                    x-transition:enter="transition ease-out duration-150"
                    x-transition:enter-start="opacity-0 scale-95"
                    x-transition:enter-end="opacity-100 scale-100"
                    x-transition:leave="transition ease-in duration-100"
                    x-transition:leave-start="opacity-100 scale-100"
                    x-transition:leave-end="opacity-0 scale-95"
                    @click.outside="profileOpen = false"
                    class="absolute right-0 mt-2 w-64 max-w-[calc(100vw-1rem)] z-[9999] bg-white dark:bg-gray-900 rounded-xl shadow-2xl border border-gray-200/60 dark:border-gray-700/60 overflow-hidden"
                    style="display:none;"
                >
                    {{-- User info --}}
                    <div class="px-4 py-4 border-b border-gray-200 dark:border-gray-700"
                         style="background: linear-gradient(135deg, #3730a3 0%, #4338ca 100%);">
                        <div class="flex items-center gap-3">
                            <div class="relative w-10 h-10 rounded-full overflow-hidden bg-gradient-to-br from-green-400 to-green-700 flex items-center justify-center flex-shrink-0"
                                 style="box-shadow: 0 0 0 2px rgba(255,255,255,0.5);">
                                <img src="{{ $user->avatar_url }}" alt="{{ $user->name }}"
                                     class="w-full h-full object-cover"
                                     onerror="this.style.display='none'; this.nextElementSibling.style.display='flex';" />
                                <span class="absolute inset-0 flex items-center justify-center text-white font-semibold text-sm"
                                      style="display:none;">{{ $user->initials }}</span>
                            </div>
                            <div class="flex-1 min-w-0">
                                <p class="text-sm font-semibold text-white truncate">{{ $user->name }}</p>
                                <p class="text-xs text-indigo-200 truncate">{{ $user->email }}</p>
                                <span class="inline-block mt-1 px-2 py-0.5 text-[10px] font-semibold text-white rounded-full {{ $roleBadgeClass }}">
                                    {{ $roleName }}
                                </span>
                            </div>
                        </div>
                    </div>
                    {{-- Menu items --}}
                    <div class="py-1">
                        @if(Route::has('profile.edit'))
                        <a href="{{ route('profile.edit') }}"
                           class="flex items-center gap-3 px-4 py-2.5 text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors">
                            <i class="fa-solid fa-user w-4 text-gray-400"></i> Edit Profile
                        </a>
                        @endif
                        <a href="{{ $user->getDashboardUrl() }}"
                           class="flex items-center gap-3 px-4 py-2.5 text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors">
                            <i class="fa-solid fa-gauge w-4 text-gray-400"></i> Dashboard
                        </a>
                        @if($user->hasSelfPacedPortalAccess())
                        <a href="{{ route($user->getSelfPacedPortalRoute()) }}"
                           class="flex items-center gap-3 px-4 py-2.5 text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors">
                            <i class="fa-solid fa-graduation-cap w-4 text-indigo-500"></i>
                            {{ $user->hasRole('Trainees') ? 'My Courses' : 'Self-Paced Portal' }}
                        </a>
                        @endif
                    </div>
                    {{-- Logout --}}
                    <div class="border-t border-gray-200 dark:border-gray-700">
                        <form method="POST" action="{{ route('logout') }}">
                            @csrf
                            <button type="submit"
                                class="flex items-center gap-3 w-full px-4 py-3 text-sm text-red-600 dark:text-red-400 hover:bg-red-50 dark:hover:bg-red-900/20 transition-colors">
                                <i class="fa-solid fa-right-from-bracket w-4"></i> Logout
                            </button>
                        </form>
                    </div>
                </div>
            </div>

        </div>{{-- end right actions --}}
    </div>{{-- end inner flex --}}
</header>

<script>
/**
 * sideHeaderData()
 * Alpine.js component for the dashboard side-header.
 * Manages: common notifications, role-based notifications (admin only),
 * profile dropdown, dark mode toggle.
 * Search has been removed — org name branding is shown instead.
 */
function sideHeaderData() {
    return {
        // Common notifications (all users)
        notificationsOpen: false,
        notificationCount: 0,
        notifications: [],
        notificationsLoading: false,

        // Role-based notifications (admin/manager only)
        roleNotificationsOpen: false,
        roleNotificationCount: 0,
        roleNotifications: [],
        roleNotificationsLoading: false,

        // Profile
        profileOpen: false,

        // Dark mode (mirrors store)
        get darkMode() { return Alpine.store('appLayout').darkMode; },

        // Polling
        pollingTimer: null,

        init() {
            this.fetchNotifications();
            @if($canSeeRoleNotifications)
            this.fetchRoleNotifications();
            @endif
            this.pollingTimer = setInterval(() => {
                this.fetchNotifications();
                @if($canSeeRoleNotifications)
                this.fetchRoleNotifications();
                @endif
            }, 30000);
        },

        // ── Common notifications ──────────────────────────────────────
        fetchNotifications() {
            this.notificationsLoading = true;
            const csrf = document.querySelector('meta[name="csrf-token"]')?.content ?? '';
            fetch('{{ Route::has('api.header.notifications') ? route('api.header.notifications') : '/api/header/notifications' }}', {
                headers: { 'Accept': 'application/json', 'X-CSRF-TOKEN': csrf },
                credentials: 'same-origin',
            })
            .then(r => r.ok ? r.json() : Promise.reject(r.status))
            .then(data => {
                this.notificationCount = data.unread_count ?? 0;
                this.notifications = data.notifications ?? [];
            })
            .catch(() => {})
            .finally(() => { this.notificationsLoading = false; });
        },

        markRead(id) {
            const n = this.notifications.find(n => n.id === id);
            if (n && !n.is_read) { n.is_read = true; this.notificationCount = Math.max(0, this.notificationCount - 1); }
            const csrf = document.querySelector('meta[name="csrf-token"]')?.content ?? '';
            fetch(`/api/header/notifications/${id}/read`, {
                method: 'POST',
                headers: { 'Accept': 'application/json', 'X-CSRF-TOKEN': csrf },
                credentials: 'same-origin',
            }).catch(() => { if (n) { n.is_read = false; this.notificationCount++; } });
        },

        markAllRead() {
            this.notifications.forEach(n => { n.is_read = true; });
            this.notificationCount = 0;
            const csrf = document.querySelector('meta[name="csrf-token"]')?.content ?? '';
            fetch('/api/header/notifications/read-all', {
                method: 'POST',
                headers: { 'Accept': 'application/json', 'X-CSRF-TOKEN': csrf },
                credentials: 'same-origin',
            }).catch(() => this.fetchNotifications());
        },

        // ── Role-based notifications ──────────────────────────────────
        fetchRoleNotifications() {
            this.roleNotificationsLoading = true;
            const csrf = document.querySelector('meta[name="csrf-token"]')?.content ?? '';
            fetch('/api/header/notifications?type=admin', {
                headers: { 'Accept': 'application/json', 'X-CSRF-TOKEN': csrf },
                credentials: 'same-origin',
            })
            .then(r => r.ok ? r.json() : Promise.reject(r.status))
            .then(data => {
                this.roleNotificationCount = data.unread_count ?? 0;
                this.roleNotifications = data.notifications ?? [];
            })
            .catch(() => {})
            .finally(() => { this.roleNotificationsLoading = false; });
        },

        markRoleRead(id) {
            const n = this.roleNotifications.find(n => n.id === id);
            if (n && !n.is_read) { n.is_read = true; this.roleNotificationCount = Math.max(0, this.roleNotificationCount - 1); }
            const csrf = document.querySelector('meta[name="csrf-token"]')?.content ?? '';
            fetch(`/api/header/notifications/${id}/read`, {
                method: 'POST',
                headers: { 'Accept': 'application/json', 'X-CSRF-TOKEN': csrf },
                credentials: 'same-origin',
            }).catch(() => { if (n) { n.is_read = false; this.roleNotificationCount++; } });
        },

        markAllRoleRead() {
            this.roleNotifications.forEach(n => { n.is_read = true; });
            this.roleNotificationCount = 0;
            const csrf = document.querySelector('meta[name="csrf-token"]')?.content ?? '';
            fetch('/api/header/notifications/read-all?type=admin', {
                method: 'POST',
                headers: { 'Accept': 'application/json', 'X-CSRF-TOKEN': csrf },
                credentials: 'same-origin',
            }).catch(() => this.fetchRoleNotifications());
        },

        // ── Dark mode ─────────────────────────────────────────────────
        toggleDarkMode() {
            Alpine.store('appLayout').toggleDarkMode();
            this.darkMode = Alpine.store('appLayout').darkMode;
        },
    };
}
</script>