<!-- app/templates/admin/partials/header.html -->
<!-- Top header bar with search, theme toggle, notifications, profile -->
<header class="z-10 py-4 bg-white shadow-md dark:bg-gray-800">
    <div class="container flex items-center justify-between h-full px-6 mx-auto text-purple-600 dark:text-purple-300">
        <!-- Mobile hamburger -->
        <button class="p-1 mr-5 -ml-1 rounded-md md:hidden focus:outline-none focus:shadow-outline-purple"
                @click="toggleSideMenu" aria-label="Menu">
            <span x-html="$icon('menu', 'w-6 h-6')"></span>
        </button>

        <!-- Search input -->
        <div class="flex justify-center flex-1 lg:mr-32">
            <div class="relative w-full max-w-xl mr-6 focus-within:text-purple-500">
                <div class="absolute inset-y-0 flex items-center pl-2">
                    <span x-html="$icon('search', 'w-4 h-4')"></span>
                </div>
                <input class="w-full pl-8 pr-2 text-sm text-gray-700 placeholder-gray-600 bg-gray-100 border-0 rounded-md dark:placeholder-gray-500 dark:focus:shadow-outline-gray dark:focus:placeholder-gray-600 dark:bg-gray-700 dark:text-gray-200 focus:placeholder-gray-500 focus:bg-white focus:border-purple-300 focus:outline-none focus:shadow-outline-purple form-input"
                       type="text" placeholder="Search for projects" aria-label="Search"/>
            </div>
        </div>

        <ul class="flex items-center flex-shrink-0 space-x-6">
            <!-- Platform Context Indicator -->
            <li class="flex" x-data="platformContext()">
                <!-- Super Admin + Platform selected -->
                <template x-if="isSuperAdmin && platform">
                    <div class="flex items-center space-x-2">
                        <span class="px-3 py-1 text-xs font-medium text-green-700 bg-green-100 dark:text-green-300 dark:bg-green-900/30 rounded-full">
                            Super Admin
                        </span>
                        <span class="px-3 py-1 text-xs font-medium text-purple-700 bg-purple-100 dark:text-purple-300 dark:bg-purple-900/30 rounded-full">
                            <span x-text="platform.name"></span>
                        </span>
                        <a href="/admin/select-platform"
                           class="text-xs text-gray-500 hover:text-purple-600 dark:text-gray-400 dark:hover:text-purple-400"
                           title="Switch platform">
                            <span x-html="$icon('switch-horizontal', 'w-4 h-4')"></span>
                        </a>
                    </div>
                </template>
                <!-- Super Admin + Global mode (no platform) -->
                <template x-if="isSuperAdmin && !platform">
                    <div class="flex items-center space-x-2">
                        <span class="px-3 py-1 text-xs font-medium text-green-700 bg-green-100 dark:text-green-300 dark:bg-green-900/30 rounded-full">
                            Super Admin (Global)
                        </span>
                        <a href="/admin/select-platform"
                           class="text-xs text-gray-500 hover:text-purple-600 dark:text-gray-400 dark:hover:text-purple-400"
                           title="Switch platform">
                            <span x-html="$icon('switch-horizontal', 'w-4 h-4')"></span>
                        </a>
                    </div>
                </template>
                <!-- Platform Admin -->
                <template x-if="!isSuperAdmin && platform">
                    <div class="flex items-center space-x-2">
                        <span class="px-3 py-1 text-xs font-medium text-purple-700 bg-purple-100 dark:text-purple-300 dark:bg-purple-900/30 rounded-full">
                            <span x-text="platform.name"></span>
                        </span>
                        <a href="/admin/select-platform"
                           class="text-xs text-gray-500 hover:text-purple-600 dark:text-gray-400 dark:hover:text-purple-400"
                           title="Switch platform">
                            <span x-html="$icon('switch-horizontal', 'w-4 h-4')"></span>
                        </a>
                    </div>
                </template>
            </li>

            <!-- Theme toggler -->
            <li class="flex">
                <button class="rounded-md focus:outline-none focus:shadow-outline-purple"
                        @click="toggleTheme" aria-label="Toggle color mode">
                    <span x-show="!dark" x-html="$icon('moon', 'w-5 h-5')"></span>
                    <span x-show="dark" x-html="$icon('sun', 'w-5 h-5')"></span>
                </button>
            </li>

            <!-- Language selector -->
            <li class="relative" x-data="languageSelector('{{ request.state.language|default('en') }}')">
                <button
                    @click="isLangOpen = !isLangOpen"
                    @click.outside="isLangOpen = false"
                    class="inline-flex items-center gap-1 p-1 rounded-md focus:outline-none focus:shadow-outline-purple"
                    aria-label="Change language"
                >
                    <span x-html="$icon('globe-alt', 'w-5 h-5')"></span>
                    <span class="text-xs font-semibold text-gray-600 dark:text-gray-300 uppercase" x-text="currentLang"></span>
                </button>
                <div
                    x-show="isLangOpen"
                    x-cloak
                    x-transition:enter="transition ease-out duration-100"
                    x-transition:enter-start="transform opacity-0 scale-95"
                    x-transition:enter-end="transform opacity-100 scale-100"
                    x-transition:leave="transition ease-in duration-75"
                    x-transition:leave-start="transform opacity-100 scale-100"
                    x-transition:leave-end="transform opacity-0 scale-95"
                    class="absolute right-0 w-44 mt-2 bg-white dark:bg-gray-700 rounded-lg shadow-lg border border-gray-100 dark:border-gray-600 py-1 z-50"
                >
                    <template x-for="lang in languages" :key="lang">
                        <button
                            @click="setLanguage(lang)"
                            type="button"
                            class="flex items-center gap-3 w-full px-4 py-2 text-sm font-medium transition-colors"
                            :class="currentLang === lang
                                ? 'bg-purple-50 dark:bg-purple-900/20 text-purple-700 dark:text-purple-300'
                                : 'text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-600'"
                        >
                            <span class="fi" :class="'fi-' + languageFlags[lang]"></span>
                            <span x-text="languageNames[lang]"></span>
                            <span x-show="currentLang === lang" x-html="$icon('check', 'w-4 h-4 ml-auto')" class="text-purple-600 dark:text-purple-400"></span>
                        </button>
                    </template>
                </div>
            </li>

            <!-- Messages link with badge -->
            <li class="relative" x-data="headerMessages()">
                <a href="/admin/messages"
                   class="relative align-middle rounded-md focus:outline-none focus:shadow-outline-purple"
                   aria-label="Messages">
                    <span x-html="$icon('chat-bubble-left-right', 'w-5 h-5')"></span>
                    <!-- Unread badge -->
                    <span x-show="unreadCount > 0"
                          aria-hidden="true"
                          class="absolute top-0 right-0 inline-flex items-center justify-center w-4 h-4 text-xs font-bold text-white transform translate-x-1 -translate-y-1 bg-green-600 border-2 border-white rounded-full dark:border-gray-800"
                          x-text="unreadCount > 9 ? '9+' : unreadCount"></span>
                </a>
            </li>

            <!-- Notifications menu -->
            <li class="relative" x-data="headerNotifications()">
                <button class="relative align-middle rounded-md focus:outline-none focus:shadow-outline-purple"
                        @click="toggleDropdown()"
                        @keydown.escape="notifOpen = false"
                        aria-label="Notifications" aria-haspopup="true">
                    <span x-html="$icon('bell', 'w-5 h-5')"></span>
                    <!-- Notification badge -->
                    <span x-show="unreadCount > 0"
                          aria-hidden="true"
                          class="absolute top-0 right-0 inline-flex items-center justify-center w-4 h-4 text-xs font-bold text-white transform translate-x-1 -translate-y-1 bg-red-600 border-2 border-white rounded-full dark:border-gray-800"
                          x-text="unreadCount > 9 ? '9+' : unreadCount"></span>
                    <span x-show="unreadCount === 0"
                          aria-hidden="true"
                          class="absolute top-0 right-0 inline-block w-2 h-2 transform translate-x-1 -translate-y-1 bg-gray-400 rounded-full dark:border-gray-800"></span>
                </button>

                <div x-show="notifOpen"
                    x-cloak
                    x-transition:leave="transition ease-in duration-150"
                    x-transition:leave-start="opacity-100"
                    x-transition:leave-end="opacity-0"
                    @click.away="notifOpen = false"
                    @keydown.escape="notifOpen = false"
                    class="absolute right-0 w-80 mt-2 text-gray-600 bg-white border border-gray-100 rounded-md shadow-lg dark:text-gray-300 dark:border-gray-700 dark:bg-gray-700 z-50">

                    <!-- Header -->
                    <div class="flex items-center justify-between px-4 py-2 border-b dark:border-gray-600">
                        <h3 class="text-sm font-semibold text-gray-800 dark:text-gray-200">Notifications</h3>
                        <template x-if="unreadCount > 0">
                            <button @click="markAllRead()"
                                    class="text-xs text-purple-600 hover:text-purple-800 dark:text-purple-400">
                                Mark all read
                            </button>
                        </template>
                    </div>

                    <!-- Notifications list -->
                    <ul class="max-h-64 overflow-y-auto">
                        <!-- Loading state -->
                        <template x-if="loading">
                            <li class="px-4 py-3 text-center text-sm text-gray-500">
                                <span x-html="$icon('spinner', 'w-4 h-4 inline mr-2')"></span>
                                Loading...
                            </li>
                        </template>

                        <!-- Empty state -->
                        <template x-if="!loading && notifications.length === 0">
                            <li class="px-4 py-6 text-center">
                                <span x-html="$icon('bell', 'w-8 h-8 mx-auto mb-2 text-gray-300')"></span>
                                <p class="text-sm text-gray-500">No notifications</p>
                            </li>
                        </template>

                        <!-- Notification items -->
                        <template x-for="notif in notifications" :key="notif.id">
                            <li class="border-b dark:border-gray-600 last:border-0">
                                <a :href="notif.action_url || '/admin/notifications'"
                                   @click="markAsRead(notif.id)"
                                   class="flex items-start px-4 py-3 hover:bg-gray-50 dark:hover:bg-gray-600 transition-colors">
                                    <!-- Priority indicator -->
                                    <span class="flex-shrink-0 w-2 h-2 mt-2 mr-3 rounded-full"
                                          :class="{
                                              'bg-red-500': notif.priority === 'critical',
                                              'bg-orange-500': notif.priority === 'high',
                                              'bg-blue-500': notif.priority === 'normal',
                                              'bg-gray-400': notif.priority === 'low'
                                          }"></span>
                                    <div class="flex-1 min-w-0">
                                        <p class="text-sm font-medium text-gray-800 dark:text-gray-200 truncate" x-text="notif.title"></p>
                                        <p class="text-xs text-gray-500 dark:text-gray-400 line-clamp-2" x-text="notif.message"></p>
                                        <p class="text-xs text-gray-400 mt-1" x-text="formatTimeAgo(notif.created_at)"></p>
                                    </div>
                                </a>
                            </li>
                        </template>
                    </ul>

                    <!-- Footer -->
                    <div class="px-4 py-2 border-t dark:border-gray-600">
                        <a href="/admin/notifications"
                           class="block text-center text-sm text-purple-600 hover:text-purple-800 dark:text-purple-400">
                            View all notifications
                        </a>
                    </div>
                </div>
            </li>

            <!-- Profile menu -->
            <li class="relative" x-data="{ profileOpen: false }">
                <button class="align-middle rounded-full focus:shadow-outline-purple focus:outline-none"
                        @click="profileOpen = !profileOpen"
                        @keydown.escape="profileOpen = false"
                        aria-label="Account"
                        aria-haspopup="true">
                    <img class="object-cover w-8 h-8 rounded-full"
                         src="https://images.unsplash.com/photo-1502378735452-bc7d86632805?ixlib=rb-0.3.5&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=200&fit=max&s=aa3a807e1bbdfd4364d1f449eaa96d82"
                         alt="" aria-hidden="true"/>
                </button>

                <ul x-show="profileOpen"
                    x-cloak
                    x-transition:leave="transition ease-in duration-150"
                    x-transition:leave-start="opacity-100"
                    x-transition:leave-end="opacity-0"
                    @click.away="profileOpen = false"
                    @keydown.escape="profileOpen = false"
                    class="absolute right-0 w-56 p-2 mt-2 space-y-2 text-gray-600 bg-white border border-gray-100 rounded-md shadow-md dark:border-gray-700 dark:text-gray-300 dark:bg-gray-700 z-50"
                    style="display: none;"
                    aria-label="submenu">
                    <li class="flex">
                        <a class="inline-flex items-center w-full px-2 py-1 text-sm font-semibold transition-colors duration-150 rounded-md hover:bg-gray-100 hover:text-gray-800 dark:hover:bg-gray-800 dark:hover:text-gray-200" href="#">
                            <span x-html="$icon('user', 'w-4 h-4 mr-3')"></span>
                            <span>Profile</span>
                        </a>
                    </li>
                    <li class="flex">
                        <a class="inline-flex items-center w-full px-2 py-1 text-sm font-semibold transition-colors duration-150 rounded-md hover:bg-gray-100 hover:text-gray-800 dark:hover:bg-gray-800 dark:hover:text-gray-200" href="/admin/settings">
                            <span x-html="$icon('cog', 'w-4 h-4 mr-3')"></span>
                            <span>Settings</span>
                        </a>
                    </li>
                    <li class="flex">
                        <button
                            @click="handleLogout()"
                            class="inline-flex items-center w-full px-2 py-1 text-sm font-semibold transition-colors duration-150 rounded-md hover:bg-gray-100 hover:text-gray-800 dark:hover:bg-gray-800 dark:hover:text-gray-200 text-left">
                            <span x-html="$icon('logout', 'w-4 h-4 mr-3')"></span>
                            <span>Log out</span>
                        </button>
                    </li>
                </ul>
            </li>
        </ul>
    </div>
</header>

<!-- Header notifications and logout handler script -->
<script>
// Platform context component for header
function platformContext() {
    return {
        platform: null,
        isSuperAdmin: false,

        init() {
            // Try to get platform from localStorage
            const storedPlatform = localStorage.getItem('admin_platform');
            if (storedPlatform) {
                try {
                    this.platform = JSON.parse(storedPlatform);
                } catch (e) {
                    console.warn('Failed to parse stored platform:', e);
                }
            }

            // Check if user is super admin
            const storedUser = localStorage.getItem('admin_user');
            if (storedUser) {
                try {
                    const user = JSON.parse(storedUser);
                    this.isSuperAdmin = user.is_super_admin === true || user.role === 'super_admin';
                } catch (e) {
                    console.warn('Failed to parse stored user:', e);
                }
            }
        }
    };
}

// Header messages component
function headerMessages() {
    return {
        unreadCount: 0,

        async init() {
            try {
                const response = await apiClient.get('/admin/messages/unread-count');
                this.unreadCount = response.count || 0;
            } catch (error) {
                // Silently fail - messages count is not critical
            }
        }
    };
}

// Header notifications component
function headerNotifications() {
    return {
        notifOpen: false,
        loading: false,
        notifications: [],
        unreadCount: 0,
        pollInterval: null,

        init() {
            this.loadNotifications();
            // Poll for new notifications every 60 seconds
            this.pollInterval = setInterval(() => this.loadNotifications(), 60000);
        },

        destroy() {
            if (this.pollInterval) {
                clearInterval(this.pollInterval);
            }
        },

        async toggleDropdown() {
            this.notifOpen = !this.notifOpen;
            if (this.notifOpen) {
                await this.loadNotifications();
            }
        },

        async loadNotifications() {
            try {
                const response = await apiClient.get('/admin/notifications/recent?limit=5');
                this.notifications = response.notifications || [];
                this.unreadCount = response.unread_count || 0;
            } catch (error) {
                console.error('Failed to load notifications:', error);
            }
        },

        async markAsRead(notificationId) {
            try {
                await apiClient.put(`/admin/notifications/${notificationId}/read`);
                // Update local state
                const notif = this.notifications.find(n => n.id === notificationId);
                if (notif) {
                    this.notifications = this.notifications.filter(n => n.id !== notificationId);
                    this.unreadCount = Math.max(0, this.unreadCount - 1);
                }
            } catch (error) {
                console.error('Failed to mark notification as read:', error);
            }
        },

        async markAllRead() {
            try {
                await apiClient.put('/admin/notifications/mark-all-read');
                this.notifications = [];
                this.unreadCount = 0;
            } catch (error) {
                console.error('Failed to mark all as read:', error);
            }
        },

        formatTimeAgo(dateString) {
            if (!dateString) return '';
            const date = new Date(dateString);
            const now = new Date();
            const diff = Math.floor((now - date) / 1000);

            if (diff < 60) return 'Just now';
            if (diff < 3600) return `${Math.floor(diff / 60)}m ago`;
            if (diff < 86400) return `${Math.floor(diff / 3600)}h ago`;
            if (diff < 604800) return `${Math.floor(diff / 86400)}d ago`;
            return date.toLocaleDateString();
        }
    };
}

// Add handleLogout function to Alpine data
document.addEventListener('alpine:init', () => {
    // Extend the data() function to include logout
    const originalData = window.data;
    window.data = function() {
        const baseData = originalData();
        return {
            ...baseData,
            handleLogout() {
                console.log('Logging out...');

                // Call logout API
                fetch('/api/v1/admin/auth/logout', {
                    method: 'POST',
                    headers: {
                        'Authorization': `Bearer ${localStorage.getItem('admin_token')}`
                    }
                })
                .then(() => {
                    console.log('Logout API called successfully');
                })
                .catch((error) => {
                    console.error('Logout API error (continuing anyway):', error);
                })
                .finally(() => {
                    // Clear admin tokens only (not store or customer tokens)
                    // Keep admin_last_visited_page so user returns to same page after login
                    localStorage.removeItem('admin_token');
                    localStorage.removeItem('admin_user');
                    localStorage.removeItem('admin_platform');
                    // Note: Do NOT use localStorage.clear() - it would clear store/customer tokens too
                    window.location.href = '/admin/login';
                });
            }
        };
    };
});
</script>
