<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}" class="h-full antialiased">
<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', 'Dashboard') - {{ config('app.name', 'Command Center') }}</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=Inter:wght@300;400;500;600&display=swap" rel="stylesheet">

    <!-- Tailwind CDN for extended theming -->
    <script src="https://cdn.tailwindcss.com"></script>
    <script>
        tailwind.config = {
            darkMode: 'class',
            theme: {
                extend: {
                    fontFamily: { sans: ['Inter', 'sans-serif'] },
                    colors: {
                        background: '#0B0E14',
                        surface: '#151921',
                        border: '#2A2F3A',
                    }
                }
            }
        }
    </script>

    <!-- Leaflet (maps) -->
    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css">
    <script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>

    <!-- Lucide icons -->
    <script src="https://unpkg.com/lucide@latest/dist/umd/lucide.js"></script>

    @vite(['resources/css/app.css', 'resources/js/app.js'])

    <style>
        body { background-color: #0B0E14; color: #E5E7EB; }
        .glass-panel { background: rgba(21, 25, 33, 0.8); backdrop-filter: blur(12px); border: 1px solid rgba(255,255,255,0.08); }
        .status-dot { box-shadow: 0 0 0 2px #151921; }
    </style>

    @stack('styles')
</head>
@php $activeRoute = request()->route() ? request()->route()->getName() : ''; $user = auth()->user(); @endphp
<body class="min-h-screen flex flex-col font-sans bg-background text-sm text-gray-200">
    <!-- Header -->
    <header class="h-14 border-b border-border bg-surface/70 backdrop-blur flex items-center justify-between px-4 sticky top-0 z-40">
        <div class="flex items-center gap-4">
            <div class="flex items-center gap-2">
                <div class="h-6 w-6 bg-gradient-to-br from-indigo-500 to-purple-600 rounded-md flex items-center justify-center shadow-lg shadow-indigo-500/20">
                    <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 text-white" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/></svg>
                </div>
                <h1 class="text-base font-semibold tracking-tight text-white">{{ config('app.name', 'Command Center') }}</h1>
            </div>
            <div class="hidden md:flex items-center gap-2 text-xs text-gray-400">
                <span class="flex items-center gap-1">
                    <span class="relative flex h-2 w-2">
                        <span class="animate-ping absolute inline-flex h-full w-full rounded-full bg-green-400 opacity-75"></span>
                        <span class="relative inline-flex rounded-full h-2 w-2 bg-green-500"></span>
                    </span>
                    Sistem Online
                </span>
                <span class="text-gray-600">•</span>
                <span class="font-mono text-gray-500">Lat: -6.2</span>
                <span class="font-mono text-gray-500">Long: 106.8</span>
            </div>
        </div>
        <div class="flex items-center gap-3">
            <div class="hidden md:flex items-center gap-2 bg-white/5 border border-white/5 rounded-full px-3 py-1 text-xs text-red-400 font-medium">
                SIAGA 1
            </div>
            <div class="flex items-center gap-2">
                <span class="text-xs text-gray-400">{{ $user?->name }}</span>
                <span class="px-2 py-1 text-[10px] rounded-full bg-white/5 border border-white/10">
                    {{ ucfirst($user->role ?? 'guest') }}
                </span>
            </div>
        </div>
    </header>

    <div class="flex flex-1 overflow-hidden">
        <!-- Sidebar -->
        <aside class="hidden md:flex w-20 md:w-64 flex-col justify-between border-r border-border bg-surface">
            <nav class="p-3 space-y-1 overflow-y-auto flex-1">
                @php
                    $navGroups = [
                        [
                            'label' => 'Dashboard',
                            'items' => [
                                ['route' => 'dashboard', 'label' => 'GIS Dashboard', 'icon' => 'map', 'badge' => null],
                            ]
                        ],
                        [
                            'label' => 'Operasi',
                            'items' => [
                                ['route' => 'complaints.index', 'label' => 'Aduan Masuk', 'icon' => 'phone', 'badge' => null],
                                ['route' => 'call-records.index', 'label' => 'Call Records', 'icon' => 'phone-call', 'badge' => 'NEW'],
                                ['route' => 'dispatches.index', 'label' => 'Dispatch', 'icon' => 'radio', 'badge' => null],
                                ['route' => 'field-reports.index', 'label' => 'Laporan Lapangan', 'icon' => 'file-text', 'badge' => null],
                            ]
                        ],
                        [
                            'label' => 'Sumber Daya',
                            'items' => [
                                ['route' => 'cctvs.index', 'label' => 'CCTV Network', 'icon' => 'video', 'badge' => null],
                                ['route' => 'panic-buttons.index', 'label' => 'Panic Button', 'icon' => 'alert-triangle', 'badge' => null],
                                ['route' => 'officers.index', 'label' => 'Unit Lapangan', 'icon' => 'users', 'badge' => null],
                            ]
                        ],
                        [
                            'label' => 'Komunikasi',
                            'items' => [
                                ['route' => 'coordinations.index', 'label' => 'Koordinasi', 'icon' => 'network', 'badge' => null],
                                ['route' => 'notifications.index', 'label' => 'Notifikasi', 'icon' => 'bell', 'badge' => null],
                                ['route' => 'broadcasts.index', 'label' => 'Broadcast Alert', 'icon' => 'megaphone', 'badge' => null],
                            ]
                        ],
                        [
                            'label' => 'Konfigurasi',
                            'items' => [
                                ['route' => 'automation-rules.index', 'label' => 'Automation Rules', 'icon' => 'settings', 'badge' => 'NEW'],
                                ['route' => 'notification-templates.index', 'label' => 'Templates', 'icon' => 'file-edit', 'badge' => 'NEW'],
                                ['route' => 'area-codes.index', 'label' => 'Area Codes', 'icon' => 'map-pin', 'badge' => 'NEW'],
                            ]
                        ],
                        [
                            'label' => 'Laporan',
                            'items' => [
                                ['route' => 'performance.index', 'label' => 'Performance', 'icon' => 'trending-up', 'badge' => null],
                                ['route' => 'analytics.index', 'label' => 'Analytics', 'icon' => 'activity', 'badge' => null],
                            ]
                        ],
                        [
                            'label' => 'Edukasi',
                            'items' => [
                                ['route' => 'knowledge-center.index', 'label' => 'Knowledge Center', 'icon' => 'book-open', 'badge' => null],
                            ]
                        ],
                    ];
                    
                    // Helper function to check if route is active (including nested routes)
                    $isRouteActive = function($routeName) use ($activeRoute) {
                        if ($activeRoute === $routeName) return true;
                        // Check for nested routes (e.g., automation-rules.create, automation-rules.edit)
                        $baseRoute = explode('.', $routeName)[0];
                        $activeBase = explode('.', $activeRoute)[0] ?? '';
                        return $activeBase === $baseRoute && (strpos($activeRoute, $baseRoute) === 0);
                    };
                @endphp
                
                @foreach($navGroups as $group)
                    <div class="mb-4">
                        <div class="px-3 py-2 mb-1">
                            <span class="hidden md:block text-[10px] font-semibold text-gray-500 uppercase tracking-wider">{{ $group['label'] }}</span>
                        </div>
                        @foreach($group['items'] as $item)
                            @php 
                                try {
                                    $routeUrl = route($item['route']);
                                    $isActive = $isRouteActive($item['route']);
                                    $hasRoute = true;
                                } catch (\Exception $e) {
                                    $routeUrl = '#';
                                    $isActive = false;
                                    $hasRoute = false;
                                }
                            @endphp
                            <a href="{{ $routeUrl }}"
                               @if(!$hasRoute) onclick="return false;" @endif
                               class="flex items-center justify-between gap-3 px-3 py-2 rounded-md border border-transparent text-sm transition group
                                      {{ $isActive ? 'bg-white/10 border-white/10 text-white' : 'text-gray-400 hover:bg-white/5 hover:text-white' }}
                                      {{ !$hasRoute ? 'opacity-50 cursor-not-allowed' : '' }}">
                                <div class="flex items-center gap-3 flex-1 min-w-0">
                                    <i data-lucide="{{ $item['icon'] }}" class="w-4 h-4 flex-shrink-0"></i>
                                    <span class="hidden md:block font-medium truncate">{{ $item['label'] }}</span>
                                </div>
                                @if($item['badge'] ?? null)
                                <span class="hidden md:block px-1.5 py-0.5 text-[9px] font-semibold bg-blue-500/20 text-blue-400 rounded border border-blue-500/30">
                                    {{ $item['badge'] }}
                                </span>
                                @endif
                            </a>
                        @endforeach
                    </div>
                @endforeach
            </nav>
            <form method="POST" action="{{ route('logout') }}" class="p-3">
                @csrf
                <button class="w-full px-3 py-2 text-left text-xs text-gray-400 hover:bg-white/5 rounded-md flex items-center gap-2">
                    <i data-lucide="log-out" class="w-4 h-4"></i> Logout
                </button>
            </form>
        </aside>

        <!-- Main Content -->
        <main class="flex-1 overflow-y-auto bg-background">
            <div class="max-w-[1920px] mx-auto p-6 space-y-6">
                @yield('content')
            </div>
        </main>

        <!-- Right Sidebar -->
        <aside class="hidden xl:flex w-72 border-l border-border bg-surface flex-col">
            <div class="p-4 border-b border-border">
                <h3 class="text-xs font-semibold text-gray-500 uppercase tracking-wider mb-2">Stakeholder Nasional</h3>
                <p class="text-xs text-gray-400">Integrasi instansi (Damkar, RS, BNPB, dll)</p>
            </div>
            <div class="flex-1 overflow-y-auto p-4 space-y-4">
                <!-- External Agencies Status -->
                <div class="space-y-3">
                    <div class="flex items-center justify-between p-2 bg-white/5 rounded-lg border border-white/5">
                        <div class="flex items-center gap-2">
                            <span class="w-2 h-2 rounded-full bg-green-500"></span>
                            <span class="text-xs text-gray-300">Mabes Polri</span>
                        </div>
                        <span class="text-[10px] text-green-400">Online</span>
                    </div>
                    <div class="flex items-center justify-between p-2 bg-white/5 rounded-lg border border-white/5">
                        <div class="flex items-center gap-2">
                            <span class="w-2 h-2 rounded-full bg-yellow-500"></span>
                            <span class="text-xs text-gray-300">BNPB</span>
                        </div>
                        <span class="text-[10px] text-yellow-400">Siaga</span>
                    </div>
                    <div class="flex items-center justify-between p-2 bg-white/5 rounded-lg border border-white/5">
                        <div class="flex items-center gap-2">
                            <span class="w-2 h-2 rounded-full bg-blue-500"></span>
                            <span class="text-xs text-gray-300">Damkar Jakarta</span>
                        </div>
                        <span class="text-[10px] text-blue-400">Standby</span>
                    </div>
                    <div class="flex items-center justify-between p-2 bg-white/5 rounded-lg border border-white/5">
                        <div class="flex items-center gap-2">
                            <span class="w-2 h-2 rounded-full bg-purple-500"></span>
                            <span class="text-xs text-gray-300">Kemenkes RI</span>
                        </div>
                        <span class="text-[10px] text-purple-400">On-call</span>
                    </div>
                </div>

                <!-- Quick Stats -->
                @php
                    try {
                        $activeCalls = \Illuminate\Support\Facades\Schema::hasTable('call_records') 
                            ? \App\Models\CallRecord::whereIn('status', ['ringing', 'answered'])->count() 
                            : 0;
                        $pendingDispatches = \Illuminate\Support\Facades\Schema::hasTable('dispatches')
                            ? \App\Models\Dispatch::where('status', 'pending')->count()
                            : 0;
                        $activeRules = \Illuminate\Support\Facades\Schema::hasTable('automation_rules')
                            ? \App\Models\AutomationRule::where('is_active', true)->count()
                            : 0;
                    } catch (\Exception $e) {
                        $activeCalls = 0;
                        $pendingDispatches = 0;
                        $activeRules = 0;
                    }
                @endphp
                <div class="pt-4 border-t border-white/5">
                    <h4 class="text-xs font-semibold text-gray-500 uppercase tracking-wider mb-3">Quick Stats</h4>
                    <div class="space-y-2 text-xs">
                        <div class="flex justify-between items-center">
                            <span class="text-gray-400">Active Calls</span>
                            <span class="text-blue-400 font-semibold">{{ $activeCalls }}</span>
                        </div>
                        <div class="flex justify-between items-center">
                            <span class="text-gray-400">Pending Dispatches</span>
                            <span class="text-yellow-400 font-semibold">{{ $pendingDispatches }}</span>
                        </div>
                        <div class="flex justify-between items-center">
                            <span class="text-gray-400">Active Rules</span>
                            <span class="text-green-400 font-semibold">{{ $activeRules }}</span>
                        </div>
                    </div>
                </div>
            </div>
        </aside>
    </div>

    @stack('scripts')
    <script>
        // Initialize Lucide icons
        if (window.lucide) {
            lucide.createIcons();
        } else {
            // Wait for lucide to load
            window.addEventListener('load', function() {
                if (window.lucide) {
                    lucide.createIcons();
                }
            });
        }

        // Real-time updates via WebSocket/Pusher (if configured)
        @if(config('broadcasting.default') === 'pusher' && config('broadcasting.connections.pusher.key'))
        // Note: Uncomment and configure if using Laravel Echo & Pusher
        /*
        window.Echo = new Echo({
            broadcaster: 'pusher',
            key: '{{ config('broadcasting.connections.pusher.key') }}',
            cluster: '{{ config('broadcasting.connections.pusher.options.cluster') }}',
            encrypted: true
        });

        // Listen for incoming calls
        Echo.channel('incoming-calls')
            .listen('.call.incoming', (e) => {
                console.log('Incoming call:', e);
                // Show notification or update UI
                if (Notification.permission === 'granted') {
                    new Notification('Incoming Call', {
                        body: `Call from ${e.caller_id}`,
                        icon: '/icon.png'
                    });
                }
            });
        */
        @endif
    </script>
</body>
</html>
