<!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>@yield('title', config('app.name', 'HinexPay'))</title>

        <!-- Favicon -->
        <link rel="icon" href="{{ asset('assets/image/Fav-Icon-black.png') }}" type="image/png">

        <!-- Fonts -->
        <link rel="preconnect" href="https://fonts.bunny.net">
        <link href="https://fonts.bunny.net/css?family=figtree:400,500,600&display=swap" rel="stylesheet" />

        <!-- Font Awesome -->
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">

        <!-- Scripts -->
        @vite(['resources/css/app.css', 'resources/js/app.js'])

        <!-- Theme Initialization for FOUC prevention -->
        <script>
            if (localStorage.getItem('theme') === 'dark' || (!('theme' in localStorage) && window.matchMedia('(prefers-color-scheme: dark)').matches)) {
                document.documentElement.classList.add('dark');
            } else {
                document.documentElement.classList.remove('dark');
            }
        </script>
    </head>
    <body class="font-sans antialiased">
        <div x-data="{
                isSidebarOpen: false,
                init() {
                    if (window.innerWidth > 768) {
                        this.isSidebarOpen = localStorage.getItem('sidebarOpen') === 'true' || localStorage.getItem('sidebarOpen') === null;
                    } else {
                        this.isSidebarOpen = false;
                    }
                    this.$watch('isSidebarOpen', value => localStorage.setItem('sidebarOpen', value));
                },
                toggleSidebar() {
                    this.isSidebarOpen = !this.isSidebarOpen;
                }
             }"
             @resize.window="if (window.innerWidth <= 768) { isSidebarOpen = false } else { isSidebarOpen = localStorage.getItem('sidebarOpen') === 'true' || localStorage.getItem('sidebarOpen') === null }"
             x-init="init()" class="flex h-screen bg-gray-100 dark:bg-gray-900">
            <!-- Sidebar -->
            @include('dashboard.sidebar')

            <!-- Main content -->
            <div class="flex-1 flex flex-col overflow-hidden transition-all duration-300" :class="isSidebarOpen ? 'md:ml-64' : 'md:ml-20'">
                @include('layouts.navigation')

                <!-- Page Heading -->
                @isset($header)
                    <header class="bg-white dark:bg-gray-800 shadow">
                        <div class="max-w-7xl mx-auto py-6 px-4 sm:px-6 lg:px-8">
                            {{ $header }}
                        </div>
                    </header>
                @endisset

                <!-- Page Content -->
                <main class="flex-1 overflow-x-hidden overflow-y-auto bg-gray-100 dark:bg-gray-900">
                    @yield('content')
                </main>
            </div>
        </div>

        @include('dashboard.add-funds')

        @stack('scripts')
        <script>
            document.addEventListener('DOMContentLoaded', function () {
                // Fullscreen toggle
                const fullscreenBtns = [document.getElementById('fullscreen-btn'), document.getElementById('fullscreen-btn-mobile')];
                fullscreenBtns.forEach(btn => {
                    if (btn) {
                        btn.addEventListener('click', () => {
                            if (!document.fullscreenElement) {
                                document.documentElement.requestFullscreen().catch(err => {
                                    alert(`Error attempting to enable full-screen mode: ${err.message} (${err.name})`);
                                });
                            } else if (document.exitFullscreen) {
                                document.exitFullscreen();
                            }
                        });
                    }
                });

                document.addEventListener('fullscreenchange', () => {
                    const iconClass = document.fullscreenElement ? 'fa-compress' : 'fa-expand';
                    fullscreenBtns.forEach(btn => {
                        if (btn) {
                            const icon = btn.querySelector('i');
                            if (icon) {
                                icon.classList.remove('fa-expand', 'fa-compress');
                                icon.classList.add(iconClass);
                            }
                        }
                    });
                });

                // Theme toggle (Dark/Light mode)
                const themeToggleBtns = [document.getElementById('theme-toggle-btn'), document.getElementById('theme-toggle-btn-mobile')];

                const toggleTheme = () => {
                    const isDark = document.documentElement.classList.toggle('dark');
                    if (isDark) {
                        localStorage.setItem('theme', 'dark');
                    } else {
                        localStorage.setItem('theme', 'light');
                    }
                    updateThemeIcons();
                };

                const updateThemeIcons = () => {
                    const isDark = document.documentElement.classList.contains('dark');
                    const iconClass = isDark ? 'fa-sun' : 'fa-moon';
                    themeToggleBtns.forEach(btn => {
                        if (btn) {
                            const icon = btn.querySelector('i');
                            if (icon) {
                                icon.className = `fas ${iconClass}`;
                            }
                        }
                    });
                };

                themeToggleBtns.forEach(btn => {
                    if (btn) {
                        btn.addEventListener('click', toggleTheme);
                    }
                });

                // Notifications Dropdown
                const notificationBadge = document.getElementById('notification-badge');
                const notificationList = document.getElementById('notification-list');

                function fetchNotifications() {
                    // This is a mock implementation. Replace with your actual API endpoint.
                    // For example: fetch('/notifications')
                    const mockNotifications = [
                        { id: 1, message: 'New payment received from John Doe.', time: '5m ago', read: false },
                        { id: 2, message: 'Your weekly report is ready.', time: '1h ago', read: false },
                        { id: 3, message: 'Server maintenance scheduled for tonight.', time: '3h ago', read: true },
                        { id: 4, message: 'New feature: Dark Mode is now available!', time: '1d ago', read: true },
                    ];

                    // Simulate API call
                    setTimeout(() => {
                        updateNotifications(mockNotifications);
                    }, 500);
                }

                function updateNotifications(notifications) {
                    if (!notificationList || !notificationBadge) return;

                    notificationList.innerHTML = '';
                    let unreadCount = 0;

                    if (notifications.length === 0) {
                        notificationList.innerHTML = '<div class="p-4 text-sm text-gray-500 dark:text-gray-400">No new notifications</div>';
                    } else {
                        notifications.forEach(notification => {
                            if (!notification.read) {
                                unreadCount++;
                            }

                            const notificationItem = document.createElement('a');
                            notificationItem.href = '#'; // Link to the notification details
                            notificationItem.className = `block p-4 text-sm transition-colors ${notification.read ? 'text-gray-500 dark:text-gray-400' : 'text-gray-700 dark:text-gray-200 font-semibold'} hover:bg-gray-100 dark:hover:bg-gray-700`;
                            notificationItem.innerHTML = `
                                <div>${notification.message}</div>
                                <div class="text-xs text-gray-400 dark:text-gray-500 mt-1">${notification.time}</div>
                            `;
                            notificationItem.addEventListener('click', (e) => {
                                e.preventDefault();
                                // Here you would mark the notification as read on the backend
                                console.log(`Notification ${notification.id} clicked.`);
                            });
                            notificationList.appendChild(notificationItem);
                        });
                    }

                    if (unreadCount > 0) {
                        notificationBadge.textContent = unreadCount;
                        notificationBadge.classList.remove('hidden');
                    } else {
                        notificationBadge.classList.add('hidden');
                    }
                }

                // Initial fetch
                fetchNotifications();

                // Poll for new notifications every 30 seconds (replace with WebSocket for true real-time)
                setInterval(fetchNotifications, 30000);

                // Initial call to set the correct theme icon on page load
                updateThemeIcons();

            });
        </script>
    </body>
</html>
