<!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>{{ \App\Models\Setting::get('app_name', config('app.name', 'Laravel'), null) }} — {{ $title ?? 'Dashboard' }}</title>
        <link rel="icon" type="image/png" href="{{ \App\Models\Setting::get('favicon_url', asset('favicon.png'), null) }}">

        <link rel="preconnect" href="https://fonts.bunny.net">
        <link href="https://fonts.bunny.net/css?family=figtree:400,500,600,700&display=swap" rel="stylesheet" />
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
        <script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
        <style>
            .flatpickr-calendar {
                border-radius: 12px !important;
                border: 1px solid #f3f4f6 !important;
                box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05) !important;
                font-family: 'Figtree', sans-serif !important;
            }
            .flatpickr-day.selected, .flatpickr-day.startRange, .flatpickr-day.endRange,
            .flatpickr-day.selected.inRange, .flatpickr-day.startRange.inRange, .flatpickr-day.endRange.inRange,
            .flatpickr-day.selected:focus, .flatpickr-day.startRange:focus, .flatpickr-day.endRange:focus,
            .flatpickr-day.selected:hover, .flatpickr-day.startRange:hover, .flatpickr-day.endRange:hover,
            .flatpickr-day.selected.prevMonthDay, .flatpickr-day.startRange.prevMonthDay, .flatpickr-day.endRange.prevMonthDay,
            .flatpickr-day.selected.nextMonthDay, .flatpickr-day.startRange.nextMonthDay, .flatpickr-day.endRange.nextMonthDay {
                background: #4f46e5 !important;
                border-color: #4f46e5 !important;
            }
            .flatpickr-day.inRange {
                background: #e0e7ff !important;
                box-shadow: -5px 0 0 #e0e7ff, 5px 0 0 #e0e7ff !important;
            }
            .flatpickr-months .flatpickr-month {
                color: #1f2937 !important;
                fill: #1f2937 !important;
            }
            .flatpickr-current-month .numInputWrapper span.arrowUp:after {
                border-bottom-color: #4f46e5 !important;
            }
            .flatpickr-current-month .numInputWrapper span.arrowDown:after {
                border-top-color: #4f46e5 !important;
            }
            .flatpickr-current-month input.cur-year {
                font-weight: 600 !important;
            }
            [x-cloak] {
                display: none !important;
            }
        </style>

        @vite(['resources/css/app.css', 'resources/js/app.js'])
        <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
        <script>
            window.AppConfig = {
                currencyPrecision: {{ (int) \App\Models\Setting::get('currency_precision', '2', \App\Models\Business::currentId()) }},
                quantityPrecision: {{ (int) \App\Models\Setting::get('quantity_precision', '2', \App\Models\Business::currentId()) }},
                showSymbolRs: {{ \App\Models\Setting::get('show_symbol_rs', '1', \App\Models\Business::currentId()) ? 'true' : 'false' }},
                currencySymbol: '{{ \App\Models\Setting::get('show_symbol_rs', '1', \App\Models\Business::currentId()) ? 'Rs. ' : '' }}'
            };

            window.formatCurrency = function(val) {
                const num = Number(val || 0);
                const p = window.AppConfig?.currencyPrecision ?? 2;
                const sym = window.AppConfig?.currencySymbol ?? 'Rs. ';
                return sym + num.toLocaleString(undefined, { minimumFractionDigits: p, maximumFractionDigits: p });
            };

            window.formatCurrencyRaw = function(val) {
                const num = Number(val || 0);
                const p = window.AppConfig?.currencyPrecision ?? 2;
                return num.toLocaleString(undefined, { minimumFractionDigits: p, maximumFractionDigits: p });
            };

            window.formatQuantity = function(val) {
                const num = Number(val || 0);
                const p = window.AppConfig?.quantityPrecision ?? 2;
                return num.toLocaleString(undefined, { minimumFractionDigits: p, maximumFractionDigits: p });
            };

            window.playNotification = function(type) {
                const audio = new Audio('/assets/sounds/' + (type === 'success' ? 'success.mp3' : 'error.mp3'));
                audio.play().catch(e => console.log('Audio playback prevented by browser policies.'));
            };

            window.showToast = function(type, message) {
                window.playNotification(type);
                const Toast = Swal.mixin({
                    toast: true,
                    position: 'top-end',
                    showConfirmButton: false,
                    timer: 3000,
                    timerProgressBar: true,
                    didOpen: (toast) => {
                        toast.addEventListener('mouseenter', Swal.stopTimer)
                        toast.addEventListener('mouseleave', Swal.resumeTimer)
                    }
                });
                Toast.fire({
                    icon: type,
                    title: message
                });
            };
        </script>
    </head>
    <body class="font-sans antialiased bg-gray-50">
        @if(session()->has('impersonated_by'))
            <div class="bg-indigo-600 text-white text-xs font-semibold py-2.5 px-4 text-center sticky top-0 z-50 flex items-center justify-center gap-2 shadow-md">
                <span>You are currently impersonating <strong>{{ Auth::user()->name }}</strong>.</span>
                <a href="{{ route('super-admin.impersonate.leave') }}" class="underline hover:text-indigo-100 font-bold transition">
                    Leave Impersonation (Back to Admin)
                </a>
            </div>
        @endif

        <div class="lg:flex">

            @include('layouts.navigation')

            <div class="flex-1 min-w-0">

                <!-- Topbar (desktop only, mobile uses sidebar's own topbar) -->
                <header class="hidden lg:flex items-center justify-between h-16 px-6 bg-white border-b border-gray-100 sticky top-0 z-10">
                    <div class="flex-1 mr-6">
                        @isset($header)
                            {{ $header }}
                        @else
                            <h1 class="text-lg font-semibold text-gray-800">Dashboard</h1>
                        @endisset
                    </div>

                    <div class="flex items-center gap-3" x-data="notificationSystem()" x-init="fetchNotifications()">
                        <div class="relative">
                            <button @click="open = !open" class="p-2 rounded-lg text-gray-400 hover:bg-gray-50 hover:text-gray-600 transition relative">
                                <svg class="w-5 h-5" 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" class="absolute top-1.5 right-1.5 px-1 py-0.5 min-w-4 text-[9px] font-bold text-white bg-red-500 rounded-full flex items-center justify-center animate-pulse" x-text="unreadCount"></span>
                            </button>

                            <!-- Dropdown Menu -->
                            <div x-show="open" @click.outside="open = false" x-cloak
                                 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"
                                 class="absolute right-0 mt-2 w-80 bg-white border border-gray-100 rounded-2xl shadow-xl py-3 z-50 space-y-2 origin-top-right">
                                <div class="px-4 pb-2 border-b border-gray-50 flex items-center justify-between">
                                    <span class="text-xs font-bold text-gray-800">Notifications</span>
                                    <button x-show="unreadCount > 0" @click="markAllAsRead()" class="text-[10px] text-indigo-600 hover:text-indigo-800 font-semibold">Mark all as read</button>
                                </div>
                                <div class="max-h-60 overflow-y-auto divide-y divide-gray-50">
                                    <template x-for="n in notifications" :key="n.id">
                                        <div class="px-4 py-2.5 hover:bg-gray-50 transition flex justify-between items-start gap-2">
                                            <div class="min-w-0 flex-1">
                                                <p class="text-xs text-gray-700 font-medium" x-text="n.data.message"></p>
                                                <span class="text-[9px] text-gray-400" x-text="n.created_at"></span>
                                            </div>
                                            <button @click="markRead(n.id)" class="text-gray-300 hover:text-indigo-600">
                                                <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.5" d="M5 13l4 4L19 7" />
                                                </svg>
                                            </button>
                                        </div>
                                    </template>
                                    <template x-if="notifications.length === 0">
                                        <div class="px-4 py-6 text-center text-xs text-gray-400">
                                            No new notifications
                                        </div>
                                    </template>
                                </div>
                            </div>
                        </div>
                    </div>
                </header>

                <!-- Page Content -->
                <main class="p-4 sm:p-6 lg:p-8">
                    {{ $slot }}
                </main>
                <x-toast />
            </div>
        </div>
        <script>
            function notificationSystem() {
                return {
                    open: false,
                    notifications: [],
                    unreadCount: 0,
                    async fetchNotifications() {
                        try {
                            const res = await fetch('/notifications', {
                                headers: { 'Accept': 'application/json' }
                            }).then(r => r.json());
                            if (res.success) {
                                this.notifications = res.notifications;
                                this.unreadCount = res.unread_count;
                            }
                        } catch (e) {}
                    },
                    async markRead(id) {
                        try {
                            const res = await fetch(`/notifications/${id}/read`, {
                                method: 'POST',
                                headers: {
                                    'Accept': 'application/json',
                                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
                                }
                            }).then(r => r.json());
                            if (res.success) {
                                this.fetchNotifications();
                            }
                        } catch (e) {}
                    },
                    async markAllAsRead() {
                        try {
                            const res = await fetch('/notifications/read-all', {
                                method: 'POST',
                                headers: {
                                    'Accept': 'application/json',
                                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
                                }
                            }).then(r => r.json());
                            if (res.success) {
                                this.fetchNotifications();
                            }
                        } catch (e) {}
                    }
                };
            }
        </script>
    </body>
</html>