<!-- Path: app/Views/responder/incident_detail.view.php -->
<!-- Include Leaflet CSS -->
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" />

<div class="bg-slate-100 min-h-[calc(100vh-64px)] py-6">
    <div class="max-w-6xl mx-auto px-4 sm:px-6 lg:px-8">
        
        <!-- Action Top Bar -->
        <div class="bg-white rounded-xl shadow-sm border border-slate-200 p-4 mb-6 flex flex-col sm:flex-row justify-between items-center gap-4">
            <div>
                <a href="{{APP_URL}}/responder/dashboard" class="text-slate-500 hover:text-navy-900 mr-3">
                    <i class="fas fa-arrow-left"></i> Back
                </a>
                <h1 class="text-xl font-bold text-navy-900 inline-block">Incident #{{ str_pad($incident['id'], 5, '0', STR_PAD_LEFT) }}</h1>
            </div>
            
            <div id="status-controls" class="flex gap-2">
                @if($incident['status'] == 'dispatched')
                    <button id="btn-accept" class="bg-alert hover:bg-red-600 text-white px-6 py-2 rounded-lg font-bold shadow-md transition-colors pulse-animation">
                        <i class="fas fa-check-circle"></i> ACCEPT DISPATCH
                    </button>
                @elseif($incident['status'] == 'accepted')
                    <button id="btn-enroute" data-status="en_route" class="status-btn bg-brandBlue-600 hover:bg-brandBlue-700 text-white px-6 py-2 rounded-lg font-bold shadow-md transition-colors">
                        <i class="fas fa-ambulance"></i> MARK EN ROUTE
                    </button>
                @elseif($incident['status'] == 'en_route')
                    <button id="btn-resolved" data-status="resolved" class="status-btn bg-green-600 hover:bg-green-700 text-white px-6 py-2 rounded-lg font-bold shadow-md transition-colors">
                        <i class="fas fa-flag-checkered"></i> MARK RESOLVED
                    </button>
                @elseif($incident['status'] == 'resolved')
                    <span class="bg-green-100 text-green-800 px-4 py-2 rounded-lg font-bold border border-green-200">
                        <i class="fas fa-check-double"></i> INCIDENT CLOSED
                    </span>
                @endif
            </div>
        </div>

        <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
            
            <!-- Left Column: Details & Map -->
            <div class="lg:col-span-2 space-y-6">
                <!-- Victim Details -->
                <div class="bg-white rounded-xl shadow-sm border border-slate-200 p-6">
                    <h3 class="text-lg font-bold text-navy-900 mb-4 border-b pb-2"><i class="fas fa-user-injured text-alert mr-2"></i> Victim Information</h3>
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4 text-sm">
                        <div>
                            <strong class="block text-slate-500">Name</strong>
                            <span class="text-lg font-semibold text-slate-900">{{ $incident['victim_name'] }}</span>
                        </div>
                        <div>
                            <strong class="block text-slate-500">Contact Number</strong>
                            <a href="tel:{{ $incident['victim_phone'] }}" class="text-lg font-bold text-brandBlue-600 hover:underline">
                                <i class="fas fa-phone-alt"></i> {{ $incident['victim_phone'] }}
                            </a>
                        </div>
                        <div class="md:col-span-2 mt-2">
                            <strong class="block text-slate-500">Emergency Description</strong>
                            <p class="text-slate-800 bg-slate-50 p-3 rounded border border-slate-100 mt-1">{{ $incident['description'] }}</p>
                        </div>
                        @if($incident['image_url'])
                            <div class="md:col-span-2 mt-2">
                                <strong class="block text-slate-500 mb-2">Attached Evidence</strong>
                                <a href="{{ MEDIA_URL }}/{{ $incident['image_url'] }}" target="_blank">
                                    <img src="{{ MEDIA_URL }}/{{ $incident['image_url'] }}" class="max-w-full h-auto rounded-lg border shadow-sm max-h-64 object-cover" alt="Emergency Photo">
                                </a>
                            </div>
                        @endif
                    </div>
                </div>

                <!-- GPS Map Info -->
                <div class="bg-white rounded-xl shadow-sm border border-slate-200 overflow-hidden">
                    <div class="p-4 bg-navy-900 text-white font-semibold flex justify-between items-center">
                        <span><i class="fas fa-map-marked-alt text-brandBlue-400"></i> Target Location</span>
                        <a href="https://www.google.com/maps/dir/?api=1&destination={{ $incident['latitude'] }},{{ $incident['longitude'] }}" target="_blank" class="bg-brandBlue-600 hover:bg-brandBlue-700 px-3 py-1 rounded text-sm transition-colors flex items-center gap-1 shadow-sm">
                            <i class="fas fa-directions"></i> Nav via Google Maps
                        </a>
                    </div>
                    <div class="p-4 bg-slate-50">
                        <div class="flex justify-between items-center mb-3">
                            <div class="text-xs text-slate-500"><i class="fas fa-info-circle"></i> Incident pinned on the map below.</div>
                            <div class="font-mono text-xs font-bold text-slate-700 bg-slate-200 px-2 py-1 rounded">
                                Lat: {{ $incident['latitude'] }} | Lng: {{ $incident['longitude'] }}
                            </div>
                        </div>
                        <!-- Embedded Map Container -->
                        <div id="incident-map" class="w-full rounded-md border border-slate-300 shadow-inner" style="height: 350px; z-index: 1;"></div>
                    </div>
                </div>
            </div>

            <!-- Right Column: Live Chat -->
            <div class="lg:col-span-1">
                <div id="chat-card" class="bg-white rounded-xl shadow-sm border border-slate-200 h-[600px] flex flex-col transition-all duration-200">
                    <div class="p-4 bg-slate-100 border-b border-slate-200 font-semibold text-navy-900 flex justify-between items-center">
                        <span><i class="fas fa-comments text-brandBlue-500 mr-2"></i> Live Comms (Victim)</span>
                        
                        <!-- Mobile Expand/Collapse Button -->
                        <button type="button" id="btn-toggle-chat" class="lg:hidden text-xs font-semibold px-2.5 py-1 rounded bg-white text-navy-900 border border-slate-300 hover:bg-slate-50 transition-colors flex items-center gap-1.5 shadow-sm">
                            <i class="fas fa-expand-alt" id="chat-expand-icon"></i>
                            <span id="chat-expand-text">Expand</span>
                        </button>
                    </div>
                    
                    <div id="chat-messages" class="flex-1 p-4 overflow-y-auto bg-slate-50 space-y-4">
                        <!-- Messages dynamically load here -->
                    </div>
                    
                    <div class="p-3 border-t border-slate-200 bg-white rounded-b-xl">
                        <form id="chatForm" class="flex gap-2">
                            <input type="text" id="chatInput" placeholder="Message victim..." 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-navy-900 hover:bg-navy-800 text-white px-4 py-2 rounded-md transition-colors">
                                Send
                            </button>
                        </form>
                    </div>
                </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) ---
    // Initialize map focused on incident location
    const map = L.map('incident-map').setView([incLat, incLng], 15);

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

    // Add Marker for the incident
    L.marker([incLat, incLng]).addTo(map)
        .bindPopup('<b class="text-alert">Incident Location</b><br>Victim is here.')
        .openPopup();

    // Fix map rendering issue if resized or placed in hidden/dynamic containers
    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 isExpanded = $chatCard.hasClass('fixed');

        if (!isExpanded) {
            $chatCard
                .removeClass('rounded-xl border shadow-sm h-[600px]')
                .addClass('fixed inset-0 z-50 h-full w-full rounded-none border-none');
            $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')
                .addClass('rounded-xl border shadow-sm h-[600px]');
            $icon.removeClass('fa-compress-alt').addClass('fa-expand-alt');
            $text.text('Expand');
            $('body').removeClass('overflow-hidden');
        }
        
        const chatContainer = $('#chat-messages');
        chatContainer.scrollTop(chatContainer[0].scrollHeight);
    });

    // --- STATUS UPDATE LOGIC ---
    $('#btn-accept').on('click', function() {
        let $btn = $(this);
        let origHtml = $btn.html();
        $btn.html('<i class="fas fa-spinner fa-spin"></i> ACCEPTING...').prop('disabled', true);
        
        $.ajax({
            url: `{{APP_URL}}/responder/incident/${incidentId}/accept`,
            type: 'POST',
            success: function(response) {
                if(response.status === 'success') {
                    showNotification('success', 'Accepted', response.message);
                    setTimeout(() => window.location.reload(), 1500);
                }
            },
            error: function() {
                showNotification('error', 'Error', 'Failed to accept dispatch.');
                $btn.html(origHtml).prop('disabled', false);
            }
        });
    });

    $('.status-btn').on('click', function() {
        let status = $(this).data('status');
        let $btn = $(this);
        let origHtml = $btn.html();
        
        Swal.fire({
            title: 'Update Status?',
            text: "Are you sure you want to mark this as " + status.replace('_', ' ').toUpperCase() + "?",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#1e3a8a',
            cancelButtonColor: '#d33',
            confirmButtonText: 'Yes, update it!'
        }).then((result) => {
            if (result.isConfirmed) {
                $btn.html('<i class="fas fa-spinner fa-spin"></i> UPDATING...').prop('disabled', true);
                $.ajax({
                    url: `{{APP_URL}}/responder/incident/${incidentId}/status`,
                    type: 'POST',
                    data: { status: status },
                    success: function(response) {
                        if(response.status === 'success') {
                            showNotification('success', 'Status Updated', response.message);
                            setTimeout(() => window.location.reload(), 1500);
                        }
                    },
                    error: function() {
                        showNotification('error', 'Error', 'Failed to update status.');
                        $btn.html(origHtml).prop('disabled', false);
                    }
                });
            }
        });
    });

    // --- 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' && response.data.length > lastMessageCount) {
                    renderMessages(response.data);
                    lastMessageCount = response.data.length;
                    chatContainer.scrollTop(chatContainer[0].scrollHeight);
                }
            }
        });
    }

    function renderMessages(messages) {
        let html = '';
        messages.forEach(msg => {
            let isResponder = msg.sender_role === 'responder' || msg.sender_role === 'admin';
            
            if(isResponder) {
                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-alert mb-1">${escapeHtml(msg.sender_name)} (Victim)</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 escapeHtml(unsafe) {
        if (unsafe == null) return '';
        return unsafe.toString().replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#039;");
    }
    
    function formatTime(dateString) {
        return new Date(dateString).toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'});
    }

    $('#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 }),
            global: false,
            success: function(response) {
                if(response.status === 'success') fetchMessages();
            }
        });
    });

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