<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= htmlspecialchars($title ?? 'Emergency Response Coordination System', ENT_QUOTES, 'UTF-8') ?></title>
    <meta name="description" content="<?= htmlspecialchars($meta_description ?? 'Rapid emergency reporting and dispatch system.', ENT_QUOTES, 'UTF-8') ?>">
    
    <!-- Google Fonts: Inter for clean, highly legible UI -->
    <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;700&display=swap" rel="stylesheet">
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/4.0.0/jquery.min.js"></script>

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

    <!-- Tailwind CSS CDN -->
    <script src="https://cdn.tailwindcss.com"></script>
    <script>

        tailwind.config = {
            theme: {
                extend: {
                    fontFamily: {
                        sans: ['Inter', 'sans-serif'],
                    },
                    colors: {
                        navy: {
                            800: '#1e3a8a',
                            900: '#1e3a8a', // Deep professional navy
                            950: '#172554',
                        },
                        brandBlue: {
                            500: '#3b82f6', // Bright, actionable blue
                            600: '#2563eb',
                        },
                        alert: '#ef4444', // Red for emergencies
                    }
                }
            }
        }
    </script>

    <!-- SweetAlert2 CSS & JS for elegant notifications -->
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

    <!-- Coreflux Head Injection -->
    <?= htmlspecialchars(Core\View::renderHead(), ENT_QUOTES, 'UTF-8') ?>

    <style>
        
        body {
            font-family: 'Inter', sans-serif;
            background-color: #f8fafc; 
            display: flex;
            flex-direction: column;
            min-height: 100vh;
        }
        main {
            flex: 1;
        }
        
        ::-webkit-scrollbar {
            width: 8px;
        }
        ::-webkit-scrollbar-track {
            background: #f1f1f1; 
        }
        ::-webkit-scrollbar-thumb {
            background: #cbd5e1; 
            border-radius: 4px;
        }
        ::-webkit-scrollbar-thumb:hover {
            background: #94a3b8; 
        }
    </style>
</head>
<body class="text-slate-800 antialiased">

    <!-- Navbar -->
    <nav class="bg-navy-950 text-white shadow-lg sticky top-0 z-50">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div class="flex justify-between h-16">
                <!-- Logo & Brand -->
                <div class="flex items-center">
                    <a href="<?= htmlspecialchars(APP_URL, ENT_QUOTES, 'UTF-8') ?>/" class="flex-shrink-0 flex items-center gap-2 group">
                        <div class="w-10 h-10 bg-alert text-white rounded-lg flex items-center justify-center font-bold text-xl shadow-md group-hover:scale-105 transition-transform">
                            <i class="fas fa-shield-alt"></i>
                        </div>
                        <span class="font-bold text-xl tracking-tight hidden sm:block">ERCS</span>
                    </a>
                </div>

                <!-- Desktop Menu -->
                <div class="hidden md:flex items-center space-x-4">
                    <a href="<?= htmlspecialchars(APP_URL, ENT_QUOTES, 'UTF-8') ?>/" class="px-3 py-2 rounded-md text-sm font-medium hover:bg-navy-800 transition-colors">Home</a>
                    <a href="<?= htmlspecialchars(APP_URL, ENT_QUOTES, 'UTF-8') ?>/about" class="px-3 py-2 rounded-md text-sm font-medium hover:bg-navy-800 transition-colors">About</a>
                    <a href="<?= htmlspecialchars(APP_URL, ENT_QUOTES, 'UTF-8') ?>/contact" class="px-3 py-2 rounded-md text-sm font-medium hover:bg-navy-800 transition-colors">Contact</a>
                    
                    <!-- Primary Call to Action -->
                    <a href="<?= htmlspecialchars(APP_URL, ENT_QUOTES, 'UTF-8') ?>/emergency/report" class="ml-4 px-4 py-2 bg-alert hover:bg-red-600 text-white font-semibold rounded-md shadow-md transition-colors flex items-center gap-2 pulse-animation">
                        <i class="fas fa-exclamation-triangle"></i> Report Emergency
                    </a>

                    <!-- Auth Links / Dynamic State -->
                    <?php if (Core\Auth::check()): ?>
                        <a href="<?= htmlspecialchars(APP_URL, ENT_QUOTES, 'UTF-8') ?>/dashboard" class="ml-2 px-3 py-2 text-sm font-medium text-brandBlue-500 hover:text-white transition-colors">
                            <i class="fas fa-user-circle mr-1"></i> Dashboard
                        </a>
                    <?php else: ?>
                        <a href="<?= htmlspecialchars(APP_URL, ENT_QUOTES, 'UTF-8') ?>/login" class="ml-2 px-3 py-2 text-sm font-medium text-slate-300 hover:text-white transition-colors">
                            Login
                        </a>
                    <?php endif; ?>
                </div>

                <!-- Mobile menu button -->
                <div class="md:hidden flex items-center">
                    <button id="mobile-menu-btn" class="text-slate-300 hover:text-white focus:outline-none">
                        <i class="fas fa-bars text-2xl"></i>
                    </button>
                </div>
            </div>
        </div>

        <!-- Mobile Menu (Hidden by default) -->
        <div id="mobile-menu" class="hidden md:hidden bg-navy-900 border-t border-navy-800 pb-4 shadow-inner">
            <div class="px-2 pt-2 space-y-1">
                <a href="<?= htmlspecialchars(APP_URL, ENT_QUOTES, 'UTF-8') ?>/" class="block px-3 py-2 rounded-md text-base font-medium hover:bg-navy-800">Home</a>
                <a href="<?= htmlspecialchars(APP_URL, ENT_QUOTES, 'UTF-8') ?>/about" class="block px-3 py-2 rounded-md text-base font-medium hover:bg-navy-800">About</a>
                <a href="<?= htmlspecialchars(APP_URL, ENT_QUOTES, 'UTF-8') ?>/contact" class="block px-3 py-2 rounded-md text-base font-medium hover:bg-navy-800">Contact</a>
                
                <a href="<?= htmlspecialchars(APP_URL, ENT_QUOTES, 'UTF-8') ?>/emergency/report" class="block mt-2 px-3 py-3 bg-alert text-white rounded-md text-base font-bold text-center shadow">
                    <i class="fas fa-exclamation-triangle mr-2"></i> Report Emergency
                </a>
                
                <div class="border-t border-navy-800 mt-2 pt-2">
                    <?php if (Core\Auth::check()): ?>
                        <a href="<?= htmlspecialchars(APP_URL, ENT_QUOTES, 'UTF-8') ?>/dashboard" class="block px-3 py-2 rounded-md text-base font-medium text-brandBlue-500 hover:bg-navy-800">Dashboard</a>
                        <a href="<?= htmlspecialchars(APP_URL, ENT_QUOTES, 'UTF-8') ?>/logout" class="block px-3 py-2 rounded-md text-base font-medium text-slate-300 hover:bg-navy-800">Logout</a>
                    <?php else: ?>
                        <a href="<?= htmlspecialchars(APP_URL, ENT_QUOTES, 'UTF-8') ?>/login" class="block px-3 py-2 rounded-md text-base font-medium text-slate-300 hover:bg-navy-800">Login</a>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </nav>

    <!-- Main Content Area where individual views are injected -->
    <main>
        <!-- Path: app/Views/emergency/track.view.php -->
<!-- Include Leaflet CSS -->
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" />

<div class="bg-white border-b border-slate-200">
    <div class="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8 py-4 flex flex-col md:flex-row justify-between items-center gap-4">
        <div>
            <h1 class="text-2xl font-bold text-navy-900">Incident #<?= htmlspecialchars(str_pad($incident['id'], 5, '0', STR_PAD_LEFT), ENT_QUOTES, 'UTF-8') ?></h1>
            <p class="text-sm text-slate-500">Reported at <?= htmlspecialchars(date('h:i A - M d, Y', strtotime($incident['created_at'])), ENT_QUOTES, 'UTF-8') ?></p>
        </div>
        
        <!-- Status Badge -->
        <div id="status-badge-container">
            <?php if ($incident['status'] == 'pending'): ?>
                <span class="px-4 py-2 rounded-full bg-yellow-100 text-yellow-800 font-bold border border-yellow-200 flex items-center gap-2">
                    <i class="fas fa-circle-notch fa-spin"></i> Verifying...
                </span>
            <?php elseif ($incident['status'] == 'dispatched'): ?>
                <span class="px-4 py-2 rounded-full bg-blue-100 text-blue-800 font-bold border border-blue-200 flex items-center gap-2 pulse-animation">
                    <i class="fas fa-truck-pickup"></i> Dispatched
                </span>
            <?php elseif ($incident['status'] == 'en_route'): ?>
                <span class="px-4 py-2 rounded-full bg-brandBlue-100 text-brandBlue-800 font-bold border border-brandBlue-200 flex items-center gap-2 pulse-animation">
                    <i class="fas fa-ambulance"></i> En Route
                </span>
            <?php elseif ($incident['status'] == 'resolved'): ?>
                <span class="px-4 py-2 rounded-full bg-green-100 text-green-800 font-bold border border-green-200 flex items-center gap-2">
                    <i class="fas fa-check-circle"></i> Resolved
                </span>
            <?php endif; ?>
        </div>
    </div>
</div>

<div class="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
    <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
        
        <!-- Map and Details Column -->
        <div class="lg:col-span-2 space-y-6">
            
            <div class="bg-white rounded-xl shadow-sm border border-slate-200 overflow-hidden">
                <div class="p-4 bg-slate-50 border-b border-slate-200 font-semibold text-navy-900 flex justify-between items-center gap-2">
                    <span><i class="fas fa-map-marked-alt text-brandBlue-500"></i> Live Location</span>
                    <span class="font-mono text-xs font-bold text-slate-600 bg-slate-200 px-2 py-1 rounded">
                        <?= htmlspecialchars($incident['latitude'], ENT_QUOTES, 'UTF-8') ?>, <?= htmlspecialchars($incident['longitude'], ENT_QUOTES, 'UTF-8') ?>
                    </span>
                </div>
                <!-- Embedded OpenStreetMap Container -->
                <div id="map" class="w-full h-64 bg-slate-200 relative z-0 border-b border-slate-200 shadow-inner"></div>
            </div>

            <div class="bg-white rounded-xl shadow-sm border border-slate-200 p-6">
                <h3 class="font-bold text-navy-900 mb-4 border-b pb-2">Emergency Details</h3>
                <p class="text-slate-700 bg-slate-50 p-3 rounded border border-slate-100"><strong>Description:</strong> <br> <?= htmlspecialchars($incident['description'], ENT_QUOTES, 'UTF-8') ?></p>
                <?php if ($incident['image_url']): ?>
                    <div class="mt-4">
                        <p class="font-semibold text-sm text-slate-500 mb-2">Attached Image:</p>
                        <a href="<?= htmlspecialchars(MEDIA_URL, ENT_QUOTES, 'UTF-8') ?>/<?= htmlspecialchars($incident['image_url'], ENT_QUOTES, 'UTF-8') ?>" target="_blank">
                            <img src="<?= htmlspecialchars(MEDIA_URL, ENT_QUOTES, 'UTF-8') ?>/<?= htmlspecialchars($incident['image_url'], ENT_QUOTES, 'UTF-8') ?>" class="max-w-xs rounded-lg border shadow-sm hover:opacity-90 transition-opacity" alt="Emergency Photo">
                        </a>
                    </div>
                <?php endif; ?>
            </div>
            
        </div>

        <!-- Chat / Communication Column -->
        <div class="lg:col-span-1">
            <div id="chat-card" class="bg-white rounded-xl shadow-sm border border-slate-200 h-[500px] flex flex-col transition-all duration-200">
                <div class="p-4 bg-navy-900 text-white rounded-t-xl font-semibold flex items-center justify-between">
                    <div>
                        <i class="fas fa-comments mr-2 text-brandBlue-300"></i> Live Chat
                        <span class="ml-2 text-[10px] bg-green-500 text-white px-2 py-0.5 rounded-full uppercase tracking-wide"><i class="fas fa-circle text-[6px] mr-1"></i> Online</span>
                    </div>
                    
                    <!-- Mobile Expand/Collapse Button -->
                    <button type="button" id="btn-toggle-chat" class="lg:hidden text-xs font-semibold px-2 py-1 rounded bg-white/20 hover:bg-white/30 text-white transition-colors flex items-center gap-1.5">
                        <i class="fas fa-expand-alt" id="chat-expand-icon"></i>
                        <span id="chat-expand-text">Expand</span>
                    </button>
                </div>
                
                <!-- Chat Messages Area -->
                <div id="chat-messages" class="flex-1 p-4 overflow-y-auto bg-slate-50 space-y-4">
                    <div class="text-center text-xs text-slate-400 my-2">System Message</div>
                    <div class="bg-blue-100 text-blue-800 p-3 rounded-lg rounded-tl-none text-sm max-w-[85%] border border-blue-200">
                        Your emergency report has been received. Please wait for a dispatcher to assign a responder.
                    </div>
                </div>
                
                <!-- Chat Input Form -->
                <div class="p-3 border-t border-slate-200 bg-white rounded-b-xl" id="chat-input-container">
                    <form id="chatForm" class="flex gap-2">
                        <input type="text" id="chatInput" name="message_text" placeholder="Type a message..." class="flex-1 px-3 py-2 border border-slate-300 rounded-md focus:outline-none focus:border-brandBlue-500 text-sm" autocomplete="off" required>
                        <button type="submit" class="bg-brandBlue-500 hover:bg-brandBlue-600 text-white px-4 py-2 rounded-md transition-colors">
                            <i class="fas fa-paper-plane"></i>
                        </button>
                    </form>
                </div>
            </div>
        </div>

    </div>
</div>

@addScript
<!-- Include Leaflet JS -->
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>

<script>
$(document).ready(function() {
    const incidentId = <?= htmlspecialchars($incident['id'], ENT_QUOTES, 'UTF-8') ?>;
    const incLat = <?= htmlspecialchars($incident['latitude'], ENT_QUOTES, 'UTF-8') ?>;
    const incLng = <?= htmlspecialchars($incident['longitude'], ENT_QUOTES, 'UTF-8') ?>;

    const map = L.map('map').setView([incLat, incLng], 15);

    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>'
    }).addTo(map);

    L.marker([incLat, incLng]).addTo(map)
        .bindPopup('<b class="text-alert">Emergency Location</b><br>You are here.')
        .openPopup();

    setTimeout(() => {
        map.invalidateSize();
    }, 500);

    $('#btn-toggle-chat').on('click', function() {
        const $chatCard = $('#chat-card');
        const $icon = $('#chat-expand-icon');
        const $text = $('#chat-expand-text');
        const $header = $chatCard.children().first();
        const $footer = $('#chat-input-container');
        const isExpanded = $chatCard.hasClass('fixed');

        if (!isExpanded) {

            $chatCard
                .removeClass('rounded-xl border shadow-sm h-[500px]')
                .addClass('fixed inset-0 z-50 h-full w-full rounded-none border-none flex flex-col');
            $header.removeClass('rounded-t-xl');
            $footer.removeClass('rounded-b-xl');
            $icon.removeClass('fa-expand-alt').addClass('fa-compress-alt');
            $text.text('Close');
            $('body').addClass('overflow-hidden');
        } else {

            $chatCard
                .removeClass('fixed inset-0 z-50 h-full w-full rounded-none border-none flex flex-col')
                .addClass('rounded-xl border shadow-sm h-[500px]');
            $header.addClass('rounded-t-xl');
            $footer.addClass('rounded-b-xl');
            $icon.removeClass('fa-compress-alt').addClass('fa-expand-alt');
            $text.text('Expand');
            $('body').removeClass('overflow-hidden');
        }
        
        scrollToBottom();
    });

    const chatContainer = $('#chat-messages');
    let lastMessageCount = 0;

    function fetchMessages() {
        $.ajax({
            url: `<?= htmlspecialchars(APP_URL, ENT_QUOTES, 'UTF-8') ?>/api/emergency/${incidentId}/messages`,
            type: 'GET',
            global: false, 
            success: function(response) {
                if(response.status === 'success') {
                    let messages = response.data;
                    
                    if(messages.length > lastMessageCount) {
                        renderMessages(messages);
                        lastMessageCount = messages.length;
                        scrollToBottom();
                    }
                }
            }
        });
    }

    function renderMessages(messages) {
        let html = `
            <div class="text-center text-xs text-slate-400 my-2">System Message</div>
            <div class="bg-blue-100 text-blue-800 p-3 rounded-lg rounded-tl-none text-sm max-w-[85%] border border-blue-200 mb-4 shadow-sm">
                Your emergency report has been received. Help is on the way.
            </div>
        `;

        messages.forEach(msg => {
            let isVictim = msg.sender_role === 'victim';
            
            if(isVictim) {
                html += `
                    <div class="flex justify-end mb-4">
                        <div class="bg-navy-900 text-white p-3 rounded-lg rounded-tr-none text-sm max-w-[85%] shadow-sm">
                            ${escapeHtml(msg.message_text)}
                            <div class="text-[10px] text-slate-300 text-right mt-1">${formatTime(msg.created_at)}</div>
                        </div>
                    </div>
                `;
            } else {
                html += `
                    <div class="flex justify-start mb-4">
                        <div class="bg-white border border-slate-200 text-slate-800 p-3 rounded-lg rounded-tl-none text-sm max-w-[85%] shadow-sm">
                            <strong class="block text-xs text-brandBlue-600 mb-1">${escapeHtml(msg.sender_name)} (${capitalizeRole(msg.sender_role)})</strong>
                            ${escapeHtml(msg.message_text)}
                            <div class="text-[10px] text-slate-400 mt-1">${formatTime(msg.created_at)}</div>
                        </div>
                    </div>
                `;
            }
        });

        chatContainer.html(html);
    }

    function scrollToBottom() {
        chatContainer.scrollTop(chatContainer[0].scrollHeight);
    }

    $('#chatForm').on('submit', function(e) {
        e.preventDefault();
        let input = $('#chatInput');
        let text = input.val().trim();
        
        if(text === '') return;
        
        input.val('');
        
        $.ajax({
            url: `<?= htmlspecialchars(APP_URL, ENT_QUOTES, 'UTF-8') ?>/api/emergency/${incidentId}/messages`,
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify({ message_text: text }),
            success: function(response) {
                if(response.status === 'success') {
                    fetchMessages(); 
                }
            }
        });
    });

    function escapeHtml(unsafe) {
        if (!unsafe) return '';
        return unsafe.toString().replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#039;");
    }
    
    function formatTime(dateString) {
        let d = new Date(dateString);
        return d.toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'});
    }

    function capitalizeRole(role) {
        if (!role) return '';
        return role.charAt(0).toUpperCase() + role.slice(1);
    }

    setInterval(fetchMessages, 3000);
    fetchMessages();
});
</script>
@endAddScript
    </main>

    <!-- Footer -->
    <footer class="bg-slate-900 text-slate-300 py-10 mt-auto border-t border-slate-800">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div class="grid grid-cols-1 md:grid-cols-3 gap-8">
                <div>
                    <h3 class="text-white text-lg font-bold mb-4 flex items-center gap-2">
                        <i class="fas fa-shield-alt text-alert"></i> ERCS
                    </h3>
                    <p class="text-sm text-slate-400">
                        Rapid emergency reporting and intelligent responder coordination. Saving lives through instant communication and real-time location tracking.
                    </p>
                </div>
                <div>
                    <h3 class="text-white text-lg font-bold mb-4">Quick Links</h3>
                    <ul class="space-y-2 text-sm">
                        <li><a href="<?= htmlspecialchars(APP_URL, ENT_QUOTES, 'UTF-8') ?>/emergency/report" class="hover:text-white transition-colors text-alert font-semibold">Report Emergency</a></li>
                        <li><a href="<?= htmlspecialchars(APP_URL, ENT_QUOTES, 'UTF-8') ?>/about" class="hover:text-white transition-colors">How it Works</a></li>
                        <li><a href="<?= htmlspecialchars(APP_URL, ENT_QUOTES, 'UTF-8') ?>/login" class="hover:text-white transition-colors">Responder Login</a></li>
                    </ul>
                </div>
                <div>
                    <h3 class="text-white text-lg font-bold mb-4">Emergency Contacts</h3>
                    <ul class="space-y-2 text-sm text-slate-400">
                        <li><i class="fas fa-phone-alt mr-2 text-brandBlue-500"></i> Toll-Free: 112</li>
                        <li><i class="fas fa-ambulance mr-2 text-brandBlue-500"></i> Medical: 911</li>
                        <li><i class="fas fa-fire mr-2 text-brandBlue-500"></i> Fire Service: 101</li>
                    </ul>
                </div>
            </div>
            <div class="border-t border-slate-800 mt-8 pt-8 text-sm text-center text-slate-500">
                &copy; <?= htmlspecialchars(date('Y'), ENT_QUOTES, 'UTF-8') ?> Emergency Response Coordination System. All rights reserved.
            </div>
        </div>
    </footer>

    <!-- jQuery for seamless AJAX requests (Chat, Location updates) -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>

    <!-- Global Layout Scripts -->
    <script>
        $(document).ready(function() {

            $('#mobile-menu-btn').on('click', function() {
                $('#mobile-menu').slideToggle('fast');
            });

            $.ajaxSetup({
                error: function(jqXHR, textStatus, errorThrown) {
                    let errorMessage = "An unexpected error occurred.";
                    if (jqXHR.responseJSON && jqXHR.responseJSON.message) {
                        errorMessage = jqXHR.responseJSON.message;
                    }


                    if (this.global !== false) {
                        Swal.fire({
                            icon: 'error',
                            title: 'System Error',
                            text: errorMessage,
                            confirmButtonColor: '#1e3a8a'
                        });
                    }
                }
            });
        });

        function showNotification(type, title, message) {
            Swal.fire({
                icon: type, // 'success', 'error', 'warning', 'info'
                title: title,
                text: message,
                toast: true,
                position: 'top-end',
                showConfirmButton: false,
                timer: 4000,
                timerProgressBar: true,
                didOpen: (toast) => {
                    toast.addEventListener('mouseenter', Swal.stopTimer)
                    toast.addEventListener('mouseleave', Swal.resumeTimer)
                }
            });
        }
    </script>

    <!-- Coreflux Injected View Scripts (e.g. Google Maps, Chat scripts added via @addScript) -->
    <?= htmlspecialchars(Core\View::renderScripts(), ENT_QUOTES, 'UTF-8') ?>
</body>
</html>