<!-- 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 #{{ str_pad($incident['id'], 5, '0', STR_PAD_LEFT) }}</h1>
            <p class="text-sm text-slate-500">Reported at {{ date('h:i A - M d, Y', strtotime($incident['created_at'])) }}</p>
        </div>
        
        <!-- Status Badge -->
        <div id="status-badge-container">
            @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>
            @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>
            @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>
            @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>
            @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">
                        {{ $incident['latitude'] }}, {{ $incident['longitude'] }}
                    </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> {{ $incident['description'] }}</p>
                @if($incident['image_url'])
                    <div class="mt-4">
                        <p class="font-semibold text-sm text-slate-500 mb-2">Attached Image:</p>
                        <a href="{{ MEDIA_URL }}/{{ $incident['image_url'] }}" target="_blank">
                            <img src="{{ MEDIA_URL }}/{{ $incident['image_url'] }}" class="max-w-xs rounded-lg border shadow-sm hover:opacity-90 transition-opacity" alt="Emergency Photo">
                        </a>
                    </div>
                @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 = {{ $incident['id'] }};
    const incLat = {{ $incident['latitude'] }};
    const incLng = {{ $incident['longitude'] }};

    // --- MAP INITIALIZATION (OpenStreetMap via Leaflet) ---
    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();

    // Invalidate map size to prevent gray-box rendering issues on load
    setTimeout(() => {
        map.invalidateSize();
    }, 500);

    // --- MOBILE CHAT EXPAND LOGIC ---
    $('#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) {
            // Expand to fullscreen
            $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 {
            // Collapse to normal
            $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();
    });

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

    function fetchMessages() {
        $.ajax({
            url: `{{APP_URL}}/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: `{{APP_URL}}/api/emergency/${incidentId}/messages`,
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify({ message_text: text }),
            success: function(response) {
                if(response.status === 'success') {
                    fetchMessages(); 
                }
            }
        });
    });

    // Utilities
    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);
    }

    // Poll every 3 seconds
    setInterval(fetchMessages, 3000);
    fetchMessages();
});
</script>
@endAddScript