<!-- Chat Modal Content (No Layout) -->
<div id="chat-conversation-data" data-conversation-id="{{ conversation.id }}" style="display: none;"></div>
<style>
{% if item.isRequest %}
/* Yellow hover theme for "asking for" items */
.btn-primary:hover {
    background-color: #ffc107 !important;
    border-color: #ffc107 !important;
    color: #000 !important;
}
.btn-outline-danger:hover {
    background-color: #ffc107 !important;
    border-color: #ffc107 !important;
    color: #000 !important;
}
.btn-outline-success:hover {
    background-color: #ffc107 !important;
    border-color: #ffc107 !important;
    color: #000 !important;
}
.btn-success:hover {
    background-color: #ffc107 !important;
    border-color: #ffc107 !important;
    color: #000 !important;
}
.btn-primary:hover,
.btn-primary:focus,
.btn-primary:active {
    background-color: #ffc107 !important;
    border-color: #ffc107 !important;
    color: #000 !important;
}
.btn-secondary:hover {
    background-color: #ffc107 !important;
    border-color: #ffc107 !important;
    color: #000 !important;
}
.input-group:hover .form-control,
.input-group:focus-within .form-control,
.input-group .form-control:focus,
.input-group .form-control:active {
    border-color: #ffc107 !important;
    box-shadow: 0 0 0 0.2rem rgba(255, 193, 7, 0.25) !important;
}
.input-group:hover .btn-primary,
.input-group .btn-primary:hover,
.input-group .btn-primary:focus,
.input-group .btn-primary:active {
    background-color: #ffc107 !important;
    border-color: #ffc107 !important;
    color: #000 !important;
}
{% endif %}
</style>
<div class="container-fluid" {% if item.isRequest %}style="background-color: #fff3cd; border-radius: 0.375rem; padding: 1rem;"{% endif %}>
    <!-- Modal Header with Item Focus -->
    <div class="row mb-3">
        <div class="col-12">
            <div class="d-flex align-items-center justify-content-between bg-light rounded p-3 border">
                <div class="d-flex align-items-center">
                    <h5 class="mb-0 me-3">Chat about {{ item.name }}</h5>
                    {% if not item.isRequest %}
                        <a href="/borrow/{{ item.id }}" class="btn btn-success btn-sm">
                            <img src="/lendables/logo_borrow_600.png" alt="Borrow" style="width: 20px; height: auto;" class="me-1">
                            Borrow Item
                        </a>
                    {% endif %}
                </div>
                <div class="d-flex align-items-center gap-3">
                    <!-- Owner Avatar -->
                    <div class="text-center">
                        <img src="/ll_images/{{ owner.avatar ?: 'default.svg' }}" 
                             alt="{{ owner.showName ?: owner.firstName }}" 
                             class="rounded-circle border border-success" 
                             style="width: 50px; height: 50px; object-fit: cover;">
                        <div class="small mt-1">{{ owner.showName ?: owner.firstName }}</div>
                        <div class="small text-muted">{% if item.isRequest %}Asking{% else %}Owner{% endif %}</div>
                    </div>
                    <!-- Borrower Avatar -->
                    <div class="text-center">
                        <img src="/ll_images/{{ borrower.avatar ?: 'default.svg' }}" 
                             alt="{{ borrower.showName ?: borrower.firstName }}" 
                             class="rounded-circle border border-primary" 
                             style="width: 50px; height: 50px; object-fit: cover;">
                        <div class="small mt-1">{{ borrower.showName ?: borrower.firstName }}</div>
                        <div class="small text-muted">Interested</div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Message Input Area -->
    <div class="row mb-3">
        <div class="col-12">
            <div class="card">
                <div class="card-body">
                    <!-- Text Message Form -->
                    <div class="mb-2">
                        <label for="messageInput" class="form-label fw-bold">Type Message</label>
                        <form id="textMessageForm" class="mb-2">
                            <div class="input-group">
                                <input type="text" id="messageInput" class="form-control" placeholder="Type your message..." maxlength="500">
                                <button type="submit" class="btn btn-primary">
                                    <i class="fas fa-paper-plane"></i> Send
                                </button>
                            </div>
                        </form>
                        <div class="text-start text-muted small">or</div>
                    </div>
                    
                    <!-- Audio Recording Controls -->
                    <div class="audio-controls mb-3">
                        <div class="btn-group mb-2" role="group">
                            <button id="recordBtn" class="btn btn-outline-danger btn-sm" onclick="startRecording()">
                                <i class="fas fa-microphone"></i> Record Voicemail
                            </button>
                            <button id="stopBtn" class="btn btn-outline-success btn-sm" onclick="stopRecording()" style="display: none;">
                                <i class="fas fa-stop"></i> Stop Recording
                            </button>
                        </div>
                        
                        <div id="recordingStatus" class="text-muted small mb-2" style="display: none;">
                            <i class="fas fa-circle text-danger blink"></i> Recording... <span id="recordingTime">0:00</span>
                        </div>
                        
                        <div id="audioPreview" class="audio-preview" style="display: none;">
                            <div class="d-flex align-items-center gap-2 p-2 bg-light rounded">
                                <audio id="audioPlayback" controls class="flex-grow-1"></audio>
                                <div class="btn-group-vertical">
                                    <button id="sendAudioBtn" class="btn btn-success btn-sm" onclick="sendAudioMessage()">
                                        <i class="fas fa-paper-plane"></i> Send Audio
                                    </button>
                                    <button id="cancelAudioBtn" class="btn btn-secondary btn-sm" onclick="cancelAudioMessage()">
                                        <i class="fas fa-times"></i> Cancel
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Messages Area -->
    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-header">
                    <h6 class="mb-0">Conversation</h6>
                </div>
                <div class="card-body" style="height: 200px; overflow-y: auto;" id="messagesContainer">
                    <!-- Messages will be loaded here -->
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Chat JavaScript -->
<script>
// Audio Canon compliant variables
let conversationId = null;
let mediaRecorder = null;
let recordingStartTime = null;
let recordingTimer = null;
let currentAudioBlob = null;
let isSendingMessage = false;

// Initialize chat variables for this specific conversation
conversationId = {{ conversation.id }};
const currentUserId = {{ currentUserId }};

// Initialize chat immediately when script loads
console.log('Chat modal initializing...');
console.log('Conversation ID:', conversationId);
console.log('Current User ID:', currentUserId);

// Create a global initialization function that can be called from outside
window.initializeChatModal = function() {
    console.log('Initializing chat modal...');
    loadMessages();
};

// Call initialization immediately if this script runs
if (typeof loadMessages === 'function') {
    loadMessages();
}

// Auto-refresh messages only when modal is visible
let chatPollingInterval = null;

function startChatPolling() {
    if (!chatPollingInterval) {
        chatPollingInterval = setInterval(loadMessages, 8000);
    }
}

function stopChatPolling() {
    if (chatPollingInterval) {
        clearInterval(chatPollingInterval);
        chatPollingInterval = null;
    }
}

// Audio Canon recording functions (matching Item Detail Chat)
function startRecording() {
    console.log('Starting recording...');
    
    navigator.mediaDevices.getUserMedia({ audio: true })
        .then(stream => {
            mediaRecorder = new MediaRecorder(stream, { mimeType: 'audio/webm' });
            let audioChunks = [];
            
            mediaRecorder.ondataavailable = event => {
                if (event.data.size > 0) {
                    audioChunks.push(event.data);
                }
            };
            
            mediaRecorder.onstop = () => {
                currentAudioBlob = new Blob(audioChunks, { type: 'audio/webm' });
                showAudioPreview(currentAudioBlob);
                stream.getTracks().forEach(track => track.stop());
            };
            
            mediaRecorder.start();
            recordingStartTime = Date.now();
            
            // Update UI
            document.getElementById('recordBtn').style.display = 'none';
            document.getElementById('stopBtn').style.display = 'inline-block';
            document.getElementById('recordingStatus').style.display = 'block';
            
            // Start timer
            recordingTimer = setInterval(updateRecordingTimer, 1000);
            
            // Auto-stop recording after 30 seconds to prevent butt-dialing
            setTimeout(() => {
                if (mediaRecorder && mediaRecorder.state === 'recording') {
                    mediaRecorder.stop();
                    alert('Recording automatically stopped after 30 seconds to prevent accidental long recordings.');
                }
            }, 30000);
        })
        .catch(err => {
            console.error('Error accessing microphone:', err);
            alert('Could not access microphone. Please check permissions.');
        });
}

function stopRecording() {
    console.log('Stopping recording...');
    
    if (mediaRecorder && mediaRecorder.state !== 'inactive') {
        mediaRecorder.stop();
    }
    
    // Clear timer
    if (recordingTimer) {
        clearInterval(recordingTimer);
        recordingTimer = null;
    }
    
    // Reset UI
    document.getElementById('recordBtn').style.display = 'inline-block';
    document.getElementById('stopBtn').style.display = 'none';
    document.getElementById('recordingStatus').style.display = 'none';
}

function updateRecordingTimer() {
    if (!recordingStartTime) return;
    
    const elapsed = Date.now() - recordingStartTime;
    const seconds = Math.floor(elapsed / 1000);
    const minutes = Math.floor(seconds / 60);
    const remainingSeconds = seconds % 60;
    
    document.getElementById('recordingTime').textContent = 
        `${minutes}:${remainingSeconds.toString().padStart(2, '0')}`;
}

function showAudioPreview(audioBlob) {
    const audioPreview = document.getElementById('audioPreview');
    const audioPlayback = document.getElementById('audioPlayback');
    
    // Create audio URL
    const audioUrl = URL.createObjectURL(audioBlob);
    audioPlayback.src = audioUrl;
    
    // Show preview section
    audioPreview.style.display = 'block';
}

function sendAudioMessage() {
    if (!currentAudioBlob || !conversationId) return;
    
    if (isSendingMessage) return; // Prevent duplicate sends
    isSendingMessage = true;
    
    const formData = new FormData();
    formData.append('recording', currentAudioBlob, 'recording.webm');
    
    document.getElementById('sendAudioBtn').disabled = true;
    document.getElementById('sendAudioBtn').textContent = 'Sending...';
    
    fetch(`/api/chat/${conversationId}/audio`, {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            // Clear preview
            cancelAudioMessage();
            // Reload messages to show the new audio message
            loadMessages();
        } else {
            alert('Failed to send audio message: ' + (data.error || 'Unknown error'));
        }
    })
    .catch(error => {
        console.error('Error sending audio:', error);
        alert('Error sending audio message');
    })
    .finally(() => {
        document.getElementById('sendAudioBtn').disabled = false;
        document.getElementById('sendAudioBtn').textContent = 'Send Audio';
        isSendingMessage = false;
    });
}

function cancelAudioMessage() {
    if (currentAudioBlob) {
        URL.revokeObjectURL(document.getElementById('audioPlayback').src);
        currentAudioBlob = null;
    }
    
    document.getElementById('audioPreview').style.display = 'none';
}
    
    if (sendAudioButton) {
        sendAudioButton.addEventListener('click', function(e) {
            e.preventDefault();
            sendAudioMessage();
        });
    }
    
    if (cancelButton) {
        cancelButton.addEventListener('click', function(e) {
            e.preventDefault();
            cancelRecording();
        });
    }
}, 100);

// Text message form submission
document.getElementById('textMessageForm').addEventListener('submit', function(e) {
    e.preventDefault();
    console.log('Form submitted');
    const messageInput = document.getElementById('messageInput');
    const message = messageInput.value.trim();
    console.log('Message content:', message);
    
    if (message) {
        console.log('Sending message:', message);
        sendTextMessage(message);
        messageInput.value = '';
    } else {
        console.log('No message content to send');
    }
});

function loadMessages() {
    console.log('Loading messages for conversation:', {{ conversation.id }});
    fetch(`/api/chat/{{ conversation.id }}/messages`)
        .then(response => {
            console.log('Messages API response status:', response.status);
            return response.json();
        })
        .then(data => {
            console.log('Messages data received:', data);
            displayMessages(data.messages);
        })
        .catch(error => {
            console.error('Error loading messages:', error);
        });
}

function displayMessages(messages) {
    const container = document.getElementById('messagesContainer');
    container.innerHTML = '';
    
    messages.forEach(message => {
        const messageDiv = document.createElement('div');
        messageDiv.className = `message mb-3 ${message.senderId === {{ currentUserId }} ? 'text-end' : 'text-start'}`;
        
        const senderName = message.senderId === {{ owner.id }} ? '{{ owner.showName ?: owner.firstName }}' : '{{ borrower.showName ?: borrower.firstName }}';
        const timestamp = new Date(message.createdAt).toLocaleString();
        
        if (message.messageType === 'audio') {
            messageDiv.innerHTML = `
                <div class="d-inline-block p-2 rounded ${message.senderId === {{ currentUserId }} ? 'bg-primary text-white' : 'bg-light'}">
                    <div class="d-flex justify-content-between align-items-start">
                        <div class="flex-grow-1">
                            <div class="small fw-bold">${senderName}</div>
                            <div>
                                <audio controls class="mb-1" style="max-width: 250px;">
                                    <source src="${message.audioPath}" type="audio/webm">
                                    Your browser does not support audio playback.
                                </audio>
                            </div>
                            ${message.transcription ? `<div class="small text-muted fst-italic">${message.transcription}</div>` : ''}
                            <div class="small opacity-75">${timestamp}</div>
                        </div>
                        ${message.senderId === {{ currentUserId }} ? `
                        <div class="dropdown ms-2">
                            <button class="btn btn-link btn-sm p-0" type="button" data-bs-toggle="dropdown" aria-expanded="false">
                                <i class="fas fa-ellipsis-v ${message.senderId === {{ currentUserId }} ? 'text-white' : 'text-muted'}"></i>
                            </button>
                            <ul class="dropdown-menu dropdown-menu-end">
                                <li><a class="dropdown-item" href="${message.audioPath}" download="audio_message_${message.id}.webm">
                                    <i class="fas fa-download me-2"></i>Download
                                </a></li>
                                <li><a class="dropdown-item text-danger" href="#" onclick="deleteAudioMessage(${message.id})">
                                    <i class="fas fa-trash me-2"></i>Delete
                                </a></li>
                            </ul>
                        </div>
                        ` : ''}
                    </div>
                </div>
            `;
        } else {
            messageDiv.innerHTML = `
                <div class="d-inline-block p-2 rounded ${message.senderId === {{ currentUserId }} ? 'bg-primary text-white' : 'bg-light'}">
                    <div class="small fw-bold">${senderName}</div>
                    <div>${message.textContent}</div>
                    <div class="small opacity-75">${timestamp}</div>
                </div>
            `;
        }
        
        container.appendChild(messageDiv);
    });
    
    // Scroll to bottom
    container.scrollTop = container.scrollHeight;
}

function sendTextMessage(message) {
    if (isSendingMessage) return; // Prevent duplicate submissions
    isSendingMessage = true;
    
    fetch(`/api/chat/{{ conversation.id }}/message?user={{ currentUserId }}`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            content: message
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            console.log('Message sent successfully');
            loadMessages();
        } else {
            console.error('Message send failed:', data);
        }
    })
    .catch(error => {
        console.error('Error sending message:', error);
    })
    .finally(() => {
        isSendingMessage = false;
    });
}

// Audio recording functions
async function toggleRecording() {
    if (mediaRecorder && mediaRecorder.state === 'recording') {
        stopRecording();
    } else {
        await startRecording();
    }
}

async function startRecording() {
    try {
        const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
        mediaRecorder = new MediaRecorder(stream);
        audioChunks = [];
        
        mediaRecorder.ondataavailable = event => {
            audioChunks.push(event.data);
        };
        
        mediaRecorder.onstop = () => {
            currentAudioBlob = new Blob(audioChunks, { type: 'audio/webm' });
            stream.getTracks().forEach(track => track.stop());
            showPlaybackControls();
        };
        
        mediaRecorder.start();
        showRecordingState();
        startTimer();
        
    } catch (error) {
        console.error('Recording failed:', error);
        alert('Could not start recording. Please check microphone permissions.');
    }
}

function stopRecording() {
    if (mediaRecorder && mediaRecorder.state === 'recording') {
        mediaRecorder.stop();
        stopTimer();
        hideRecordingState();
    }
}

function showRecordingState() {
    document.getElementById('recordButton').classList.add('btn-danger');
    document.getElementById('recordButton').classList.remove('btn-outline-danger');
    document.getElementById('recordText').textContent = 'Stop Recording';
    document.getElementById('recordingStatus').style.display = 'block';
}

function hideRecordingState() {
    document.getElementById('recordButton').classList.remove('btn-danger');
    document.getElementById('recordButton').classList.add('btn-outline-danger');
    document.getElementById('recordText').textContent = 'Record Audio';
    document.getElementById('recordingStatus').style.display = 'none';
}

function showPlaybackControls() {
    document.getElementById('playbackControls').style.display = 'flex';
}

function startTimer() {
    recordingStartTime = Date.now();
    recordingTimer = setInterval(() => {
        const elapsed = Math.floor((Date.now() - recordingStartTime) / 1000);
        const minutes = Math.floor(elapsed / 60);
        const seconds = elapsed % 60;
        document.getElementById('recordingTimer').textContent = `${minutes}:${seconds.toString().padStart(2, '0')}`;
    }, 1000);
}

function stopTimer() {
    if (recordingTimer) {
        clearInterval(recordingTimer);
        recordingTimer = null;
    }
}

function playRecording() {
    if (currentAudioBlob) {
        const audio = new Audio(URL.createObjectURL(currentAudioBlob));
        audio.play();
    }
}

async function sendAudioMessage() {
    if (!currentAudioBlob) return;
    
    try {
        const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
        const filename = `audio-message-${timestamp}.webm`;
        
        const formData = new FormData();
        formData.append('audio', currentAudioBlob, filename);
        formData.append('messageType', 'audio');
        
        const response = await fetch(`/api/chat/{{ conversation.id }}/message?user={{ currentUserId }}`, {
            method: 'POST',
            body: formData
        });
        
        if (response.ok) {
            cancelRecording();
            loadMessages();
        } else {
            alert('Failed to send audio message. Please try again.');
        }
    } catch (error) {
        console.error('Error sending audio message:', error);
        alert('Error sending audio message. Please try again.');
    }
}

function cancelRecording() {
    currentAudioBlob = null;
    audioChunks = [];
    document.getElementById('playbackControls').style.display = 'none';
    hideRecordingState();
}

// Define functions globally and ensure they execute immediately  
(function() {
    // Make functions globally available for modal context
    window.toggleRecording = toggleRecording;
    window.playRecording = playRecording;
    window.sendAudioMessage = sendAudioMessage;
    window.cancelRecording = cancelRecording;
    
    console.log('Audio functions assigned to window:', {
        toggleRecording: typeof window.toggleRecording,
        playRecording: typeof window.playRecording,
        sendAudioMessage: typeof window.sendAudioMessage,
        cancelRecording: typeof window.cancelRecording
    });
})();

function deleteAudioMessage(messageId) {
    if (!confirm('Are you sure you want to delete this audio message?')) {
        return;
    }
    
    fetch(`/api/chat/message/${messageId}/delete`, {
        method: 'DELETE',
        headers: {
            'Content-Type': 'application/json',
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            loadMessages(); // Reload messages to reflect deletion
        } else {
            alert('Failed to delete message: ' + (data.error || 'Unknown error'));
        }
    })
    .catch(error => {
        console.error('Error deleting message:', error);
        alert('Error deleting message');
    });
}

</script>