<!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', 'Admin Dashboard') - Lindsay's Leather</title>
    
    <!-- Fonts -->
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Lato:wght@400;600;700&family=Montserrat:wght@400;500;600&display=swap" rel="stylesheet">
    
    <!-- Scripts -->
    @vite(['resources/css/app.css', 'resources/js/app.js'])
    
    <!-- Konva.js CDN -->
    <script src="https://unpkg.com/konva@9/konva.min.js"></script>
    
    <!-- iziToast CSS -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/izitoast@1.4.0/dist/css/iziToast.min.css">
    
    <!-- iziToast JS -->
    <script src="https://cdn.jsdelivr.net/npm/izitoast@1.4.0/dist/js/iziToast.min.js"></script>
    
    <style>
        * {
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Montserrat', sans-serif;
            background-color: #f8fafc;
            margin: 0;
            padding: 0;
            color: #1f2937;
        }
        
        /* Sidebar */
        .sidebar {
            position: fixed;
            top: 0;
            left: 0;
            width: 280px;
            height: 100vh;
            background: linear-gradient(180deg, #2D1B1B 0%, #1A0F0F 100%);
            color: white;
            z-index: 1000;
            overflow-y: auto;
            transition: transform 0.3s ease;
            box-shadow: 2px 0 10px rgba(0, 0, 0, 0.3);
        }
        
        .sidebar-header {
            padding: 2rem 1.5rem;
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
        }
        
        .sidebar-logo {
            font-family: 'Lato', sans-serif;
            font-size: 1.5rem;
            font-weight: 700;
            color: #F4A261;
            text-decoration: none;
            display: flex;
            align-items: center;
            text-shadow: 0 2px 4px rgba(0, 0, 0, 0.5);
            transition: all 0.3s ease;
        }
        
        .sidebar-logo:hover {
            color: #E76F51;
            transform: translateY(-1px);
        }
        
        .sidebar-logo img {
            filter: drop-shadow(0 2px 4px rgba(0, 0, 0, 0.5));
            transition: all 0.3s ease;
        }
        
        .sidebar-logo:hover img {
            transform: scale(1.05);
        }
        
        .sidebar-nav {
            padding: 1rem 0;
        }
        
        .nav-item {
            display: block;
            padding: 0.75rem 1.5rem;
            color: rgba(255, 255, 255, 0.8);
            text-decoration: none;
            transition: all 0.3s ease;
            border-left: 3px solid transparent;
        }
        
        .nav-item:hover,
        .nav-item.active {
            background: rgba(181, 112, 47, 0.1);
            color: #B5702F;
            border-left-color: #B5702F;
        }
        
        .nav-item svg {
            width: 20px;
            height: 20px;
            margin-right: 0.75rem;
            vertical-align: middle;
            display: inline-block;
        }
        
        /* Main Content */
        .main-content {
            margin-left: 280px;
            min-height: 100vh;
        }
        
        /* Header */
        .header {
            background: white;
            border-bottom: 1px solid #e5e7eb;
            padding: 1rem 2rem;
            display: flex;
            justify-content: space-between;
            align-items: center;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
        }
        
        .header-title {
            font-family: 'Lato', sans-serif;
            font-size: 1.875rem;
            font-weight: 700;
            color: #371C16;
            margin: 0;
        }
        
        .header-actions {
            display: flex;
            align-items: center;
            gap: 1rem;
        }
        
        .back-btn {
            background: #6b7280;
            color: white;
            border: none;
            padding: 0.5rem 1rem;
            border-radius: 0.5rem;
            font-size: 0.875rem;
            font-weight: 500;
            cursor: pointer;
            transition: background-color 0.3s ease;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
        }
        
        .back-btn:hover {
            background: #4b5563;
        }
        
        .logout-btn {
            background: #dc2626;
            color: white;
            border: none;
            padding: 0.5rem 1rem;
            border-radius: 0.5rem;
            font-size: 0.875rem;
            font-weight: 500;
            cursor: pointer;
            transition: background-color 0.3s ease;
        }
        
        .logout-btn:hover {
            background: #b91c1c;
        }
        
        /* Content Area */
        .content {
            padding: 2rem;
        }
        
        /* Mobile Responsive */
        @media (max-width: 768px) {
            .sidebar {
                transform: translateX(-100%);
            }
            
            .sidebar.open {
                transform: translateX(0);
            }
            
            .main-content {
                margin-left: 0;
            }
            
            .content {
                padding: 1rem;
            }
        }
        
        /* Custom Toast Styling - Compact Version */
        .iziToast {
            font-family: 'Montserrat', sans-serif !important;
            border-radius: 6px !important;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15) !important;
            max-width: 560px !important;
        }
        
        .iziToast .iziToast-body {
            padding: 12px 16px !important;
            position: relative !important;
        }
        
        .iziToast .iziToast-title {
            font-weight: 600 !important;
            font-size: 14px !important;
            margin-bottom: 2px !important;
        }
        
        .iziToast .iziToast-message {
            font-size: 12px !important;
            margin-top: 2px !important;
            line-height: 1.3 !important;
        }
        
        .iziToast .iziToast-buttons {
            margin-top: 8px !important;
        }
        
        .iziToast .iziToast-buttons button {
            background: #B5702F !important;
            color: white !important;
            border: none !important;
            padding: 4px 10px !important;
            border-radius: 3px !important;
            font-size: 11px !important;
            font-weight: 500 !important;
            margin-right: 6px !important;
            cursor: pointer !important;
            transition: background-color 0.3s ease !important;
        }
        
        .iziToast .iziToast-buttons button:hover {
            background: #9a5d26 !important;
        }
        
        /* Hide default close button */
        .iziToast .iziToast-close {
            display: none !important;
        }
        
        /* Ensure custom close icon is properly positioned */
        .iziToast .iziToast-body {
            position: relative !important;
            overflow: visible !important;
        }
    </style>
    
    @yield('styles')
</head>
<body>
    <!-- Sidebar -->
    @include('layouts.partials.admin-sidebar')

    <!-- Main Content -->
    <div class="main-content">
        <!-- Header -->
        <header class="header">
            <h1 class="header-title">@yield('page-title', 'Dashboard')</h1>
            <div class="header-actions">
                @yield('header-actions')
                <form method="POST" action="{{ route('admin.logout') }}" style="display: inline;">
                    @csrf
                    <button type="submit" class="logout-btn">
                        <svg width="16" height="16" fill="none" stroke="currentColor" viewBox="0 0 24 24" style="display: inline-block;">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1"></path>
                        </svg>
                        Logout
                    </button>
                </form>
            </div>
        </header>

        <!-- Content -->
        <main class="content">
            @yield('content')
        </main>
    </div>

    @yield('scripts')
    
    <script>
        // Real-time order notifications
        class OrderNotificationManager {
            constructor() {
                this.lastCheck = new Date().toISOString();
                this.pollingInterval = 5000; // 5 seconds
                this.isPolling = false;
                this.notifiedOrders = new Set(); // Track which order IDs have been notified
                this.loadNotifiedOrders(); // Load from localStorage
                this.init();
            }

            // Load previously notified orders from localStorage
            loadNotifiedOrders() {
                try {
                    const stored = localStorage.getItem('notifiedOrders');
                    if (stored) {
                        const orderIds = JSON.parse(stored);
                        // Only keep orders from last 24 hours to prevent memory bloat
                        const oneDayAgo = Date.now() - (24 * 60 * 60 * 1000);
                        const filtered = orderIds.filter(item => item.timestamp > oneDayAgo);
                        filtered.forEach(item => this.notifiedOrders.add(item.id));
                        
                        // Save cleaned list back
                        this.saveNotifiedOrders();
                    }
                } catch (error) {
                    console.error('Error loading notified orders:', error);
                    this.notifiedOrders = new Set();
                }
            }

            // Save notified orders to localStorage
            saveNotifiedOrders() {
                try {
                    const orderIds = Array.from(this.notifiedOrders).map(id => ({
                        id: id,
                        timestamp: Date.now()
                    }));
                    localStorage.setItem('notifiedOrders', JSON.stringify(orderIds));
                } catch (error) {
                    console.error('Error saving notified orders:', error);
                }
            }

            // Check if order has already been notified
            hasBeenNotified(orderId) {
                return this.notifiedOrders.has(orderId);
            }

            // Mark order as notified
            markAsNotified(orderId) {
                if (!orderId) return;
                this.notifiedOrders.add(orderId);
                this.saveNotifiedOrders();
                console.log('Order marked as notified:', orderId, 'Total notified:', this.notifiedOrders.size);
            }

            // Clear all notified orders (for testing/reset)
            clearNotifiedOrders() {
                this.notifiedOrders.clear();
                localStorage.removeItem('notifiedOrders');
                console.log('All notified orders cleared');
            }

            init() {
                // Start polling for new orders
                this.startPolling();
                
                // Stop polling when page is hidden (browser tab not active)
                document.addEventListener('visibilitychange', () => {
                    if (document.hidden) {
                        this.stopPolling();
                    } else {
                        this.startPolling();
                    }
                });
            }

            startPolling() {
                if (this.isPolling) return;
                
                this.isPolling = true;
                this.pollForNewOrders();
            }

            stopPolling() {
                this.isPolling = false;
                if (this.pollingTimer) {
                    clearTimeout(this.pollingTimer);
                }
            }

            async pollForNewOrders() {
                if (!this.isPolling) return;

                try {
                    const response = await fetch(`/api/new-orders?last_check=${encodeURIComponent(this.lastCheck)}`, {
                        method: 'GET',
                        headers: {
                            'X-Requested-With': 'XMLHttpRequest',
                            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
                        }
                    });

                    if (response.ok) {
                        const data = await response.json();
                        this.lastCheck = data.last_check;

                        // Show notifications for new orders (only if not already notified)
                        if (data.new_orders && data.new_orders.length > 0) {
                            data.new_orders.forEach(order => {
                                // Check if this order has already been notified
                                if (!this.hasBeenNotified(order.id)) {
                                    console.log('Showing notification for new order:', order.id);
                                    this.showOrderNotification(order);
                                    this.markAsNotified(order.id);
                                } else {
                                    console.log('Order already notified, skipping:', order.id);
                                }
                            });
                        }
                    }
                } catch (error) {
                    console.error('Error polling for new orders:', error);
                }

                // Schedule next poll
                if (this.isPolling) {
                    this.pollingTimer = setTimeout(() => {
                        this.pollForNewOrders();
                    }, this.pollingInterval);
                }
            }

            showOrderNotification(order) {
                // Validate order object
                if (!order || !order.id) {
                    console.error('Invalid order object:', order);
                    return;
                }

                console.log('Displaying notification for order:', order.id, order.student_name);

                iziToast.show({
                    title: 'New Order Received!',
                    message: `${order.student_name || 'Customer'} ordered a ${order.product_name || 'product'}`,
                    position: 'topRight',
                    timeout: 5000,
                    close: false,
                    closeOnClick: false,
                    progressBar: true,
                    backgroundColor: '#371C16',
                    titleColor: '#FFFFFF',
                    messageColor: '#FFFFFF',
                    icon: 'fas fa-shopping-cart',
                    iconColor: '#B5702F',
                    buttons: [
                        ['<button>View Order</button>', function (instance, toast) {
                            window.location.href = `/admin/orders/${order.id}`;
                        }]
                    ],
                    onOpen: function(instance, toast) {
                        // Add haptic feedback if available
                        if (navigator.vibrate) {
                            navigator.vibrate([200, 100, 200]);
                        }
                        
                        // Add custom close icon with inline SVG
                        const closeIcon = document.createElement('div');
                        closeIcon.innerHTML = `
                            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#fff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                                <line x1="18" y1="6" x2="6" y2="18"></line>
                                <line x1="6" y1="6" x2="18" y2="18"></line>
                            </svg>
                        `;
                        closeIcon.style.cssText = `
                            position: absolute;
                            top: 8px;
                            right: 8px;
                            cursor: pointer;
                            width: 24px;
                            height: 24px;
                            display: flex;
                            align-items: center;
                            justify-content: center;
                            border-radius: 50%;
                            transition: background-color 0.2s ease;
                            z-index: 1000;
                            color: white;
                        `;
                        
                        closeIcon.addEventListener('mouseenter', function() {
                            this.style.backgroundColor = 'rgba(255, 255, 255, 0.1)';
                        });
                        
                        closeIcon.addEventListener('mouseleave', function() {
                            this.style.backgroundColor = 'transparent';
                        });
                        
                        closeIcon.addEventListener('click', function() {
                            instance.hide(toast, {}, 'close');
                        });
                        
                        toast.querySelector('.iziToast-body').appendChild(closeIcon);
                    }
                });
            }
        }

        // Initialize order notifications when DOM is ready
        document.addEventListener('DOMContentLoaded', function() {
            // Only initialize on admin pages
            if (window.location.pathname.startsWith('/admin')) {
                window.orderNotificationManager = new OrderNotificationManager();
                
                console.log('Order Notification Manager initialized');
                console.log('To clear notification history, run: orderNotificationManager.clearNotifiedOrders()');
                
                // Add test button for development (remove in production)
                // if (window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1') {
                //     const testButton = document.createElement('button');
                //     testButton.textContent = 'Test Notification';
                //     testButton.style.cssText = 'position: fixed; top: 10px; right: 10px; z-index: 9999; background: #B5702F; color: white; border: none; padding: 8px 12px; border-radius: 4px; cursor: pointer; font-size: 12px;';
                //     testButton.onclick = function() {
                //         window.orderNotificationManager.showOrderNotification({
                //             id: 'test',
                //             student_name: 'Test Student',
                //             product_name: 'Test Product',
                //             created_at: new Date().toISOString(),
                //             status: 'pending'
                //         });
                //     };
                //     document.body.appendChild(testButton);
                // }
            }
        });
    </script>
</body>
</html>
