<!DOCTYPE html>
<html lang="en" data-bs-theme="light" data-pwa="true">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Chat - Local Lendables</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        body {
            background-color: #f8f9fa;
            font-family: 'Arial', sans-serif;
        }
        
        .chat-container {
            max-width: 800px;
            margin: 2rem auto;
            background: white;
            border-radius: 12px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            overflow: hidden;
        }
        
        .chat-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 1.5rem;
            display: flex;
            align-items: center;
            gap: 1rem;
        }
        
        .item-info {
            display: flex;
            align-items: center;
            gap: 1rem;
        }
        
        .item-image {
            width: 60px;
            height: 60px;
            border-radius: 8px;
            object-fit: cover;
        }
        
        .chat-messages {
            height: 400px;
            overflow-y: auto;
            padding: 1rem;
            display: flex;
            flex-direction: column;
            gap: 1rem;
        }
        
        .message {
            max-width: 70%;
            display: flex;
            flex-direction: column;
        }
        
        .message.sent {
            align-self: flex-end;
        }
        
        .message.received {
            align-self: flex-start;
        }
        
        .message-content {
            padding: 0.75rem 1rem;
            border-radius: 18px;
            position: relative;
        }
        
        .message.sent .message-content {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }
        
        .message.received .message-content {
            background: #e9ecef;
            color: #333;
        }
        
        .timestamp {
            font-size: 0.75rem;
            opacity: 0.7;
            margin-top: 0.25rem;
        }
        
        .audio-message audio {
            width: 100%;
            margin: 0.5rem 0;
        }
        
        .transcription {
            font-style: italic;
            opacity: 0.8;
            margin-top: 0.5rem;
            font-size: 0.9rem;
        }
        
        .chat-input {
            padding: 1.5rem;
            border-top: 1px solid #dee2e6;
            background: #f8f9fa;
        }
        
        .input-group {
            gap: 0.5rem;
        }
        
        .audio-controls {
            display: flex;
            gap: 0.5rem;
            margin-top: 1rem;
        }
        
        .btn-record {
            background: #dc3545;
            color: white;
            border: none;
        }
        
        .btn-record.recording {
            background: #28a745;
            animation: pulse 1s infinite;
        }
        
        @keyframes pulse {
            0% { opacity: 1; }
            50% { opacity: 0.7; }
            100% { opacity: 1; }
        }
        
        .audio-preview {
            margin-top: 1rem;
            padding: 1rem;
            background: #e9ecef;
            border-radius: 8px;
            display: none;
        }
        
        .no-messages {
            text-align: center;
            color: #6c757d;
            font-style: italic;
            padding: 2rem;
        }
    </style>
</head>
<body>
    <div class="chat-container">
        <div class="chat-header">
            <button class="btn btn-link text-white p-0" onclick="window.close()">
                <i class="fas fa-arrow-left"></i>
            </button>
            <div class="item-info">
                {% if item.primaryLogo %}
                    <img src="/images/{{ item.primaryLogo }}" alt="{{ item.name }}" class="item-image">
                {% endif %}
                <div>
                    <h5 class="mb-0">{{ item.name }}</h5>
                    <small>Chat with {{ otherUser.showName ?: (otherUser.firstName ~ ' ' ~ otherUser.lastName) }}</small>
                </div>
            </div>
        </div>
        
        <div id="chatMessages" class="chat-messages">
            <div class="no-messages">Loading messages...</div>
        </div>
        
        <div class="chat-input">
            <div class="input-group">
                <input type="text" id="messageInput" class="form-control" placeholder="Type your message..." onkeypress="handleKeyPress(event)">
                <button class="btn btn-primary" onclick="sendTextMessage()">
                    <i class="fas fa-paper-plane"></i>
                </button>
            </div>
            
            <div class="audio-controls">
                <button id="recordBtn" class="btn btn-record" onclick="toggleRecording()">
                    <i class="fas fa-microphone"></i> Record Audio
                </button>
                <button id="playBtn" class="btn btn-secondary" onclick="playRecording()" style="display: none;">
                    <i class="fas fa-play"></i> Play
                </button>
                <button id="sendAudioBtn" class="btn btn-success" onclick="sendAudioMessage()" style="display: none;">
                    <i class="fas fa-paper-plane"></i> Send Audio
                </button>
                <button id="cancelAudioBtn" class="btn btn-secondary" onclick="cancelRecording()" style="display: none;">
                    <i class="fas fa-times"></i> Cancel
                </button>
            </div>
            
            <div id="audioPreview" class="audio-preview">
                <audio id="audioPlayback" controls style="width: 100%;"></audio>
                <p class="mb-0 mt-2"><small>Audio recorded successfully. You can play it back or send it.</small></p>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        let conversationId = {{ conversationId }};
        let currentUserId = {{ currentUser.id }};
        let mediaRecorder;
        let audioChunks = [];
        let recordedBlob;
        
        // Load messages on page load
        document.addEventListener('DOMContentLoaded', function() {
            loadMessages();
            // Refresh messages every 5 seconds
            setInterval(loadMessages, 5000);
        });
        
        function loadMessages() {
            fetch(`/api/chat/${conversationId}/messages`)
                .then(response => response.json())
                .then(data => {
                    displayMessages(data.messages || []);
                })
                .catch(error => {
                    console.error('Error loading messages:', error);
                });
        }
        
        function displayMessages(messages) {
            const chatMessages = document.getElementById('chatMessages');
            chatMessages.innerHTML = '';
            
            if (!messages || messages.length === 0) {
                chatMessages.innerHTML = '<div class="no-messages">No messages yet. Start the conversation!</div>';
                return;
            }
            
            messages.forEach(message => {
                const messageDiv = document.createElement('div');
                messageDiv.className = `message ${message.sender_id === currentUserId ? 'sent' : 'received'}`;
                
                let messageContent = '';
                if (message.audio_path && message.message_type === 'audio') {
                    messageContent = `
                        <div class="audio-message">
                            <div class="d-flex justify-content-between align-items-start">
                                <div class="flex-grow-1">
                                    <audio controls>
                                        <source src="${message.audio_path}" type="audio/webm">
                                        Your browser does not support the audio element.
                                    </audio>
                                    ${message.transcription ? `<p class="transcription">${message.transcription}</p>` : ''}
                                </div>
                                ${message.sender_id === currentUserId ? `
                                <div class="dropdown">
                                    <button class="btn btn-link btn-sm p-0" type="button" data-bs-toggle="dropdown" aria-expanded="false">
                                        <i class="fas fa-ellipsis-v text-muted"></i>
                                    </button>
                                    <ul class="dropdown-menu dropdown-menu-end">
                                        <li><a class="dropdown-item" href="${message.audio_path}" 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 {
                    messageContent = `<p class="mb-0">${message.text_content || 'Empty message'}</p>`;
                }
                
                messageDiv.innerHTML = `
                    <div class="message-content">
                        ${messageContent}
                        <small class="timestamp">${new Date(message.created_at).toLocaleString()}</small>
                    </div>
                `;
                
                chatMessages.appendChild(messageDiv);
            });
            
            // Scroll to bottom
            chatMessages.scrollTop = chatMessages.scrollHeight;
        }
        
        function handleKeyPress(event) {
            if (event.key === 'Enter') {
                sendTextMessage();
            }
        }
        
        function sendTextMessage() {
            const messageInput = document.getElementById('messageInput');
            const message = messageInput.value.trim();
            
            if (!message) return;
            
            fetch(`/api/chat/${conversationId}/message`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    content: message
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    messageInput.value = '';
                    loadMessages();
                }
            })
            .catch(error => {
                console.error('Error sending message:', error);
            });
        }
        
        async function toggleRecording() {
            const recordBtn = document.getElementById('recordBtn');
            
            if (!mediaRecorder || mediaRecorder.state === 'inactive') {
                try {
                    const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
                    mediaRecorder = new MediaRecorder(stream);
                    audioChunks = [];
                    
                    mediaRecorder.ondataavailable = function(event) {
                        audioChunks.push(event.data);
                    };
                    
                    mediaRecorder.onstop = function() {
                        recordedBlob = new Blob(audioChunks, { type: 'audio/webm' });
                        showAudioPreview();
                        
                        // Stop all tracks
                        stream.getTracks().forEach(track => track.stop());
                    };
                    
                    mediaRecorder.start();
                    recordBtn.textContent = 'Stop Recording';
                    recordBtn.classList.add('recording');
                    
                    // Auto-stop recording after 30 seconds to prevent butt-dialing
                    setTimeout(() => {
                        if (mediaRecorder && mediaRecorder.state === 'recording') {
                            mediaRecorder.stop();
                            recordBtn.textContent = 'Record Audio';
                            recordBtn.classList.remove('recording');
                            alert('Recording automatically stopped after 30 seconds to prevent accidental long recordings.');
                        }
                    }, 30000);
                    
                } catch (error) {
                    console.error('Error accessing microphone:', error);
                    alert('Could not access microphone. Please check your permissions.');
                }
            } else {
                mediaRecorder.stop();
                recordBtn.textContent = 'Record Audio';
                recordBtn.classList.remove('recording');
            }
        }
        
        function showAudioPreview() {
            const audioPreview = document.getElementById('audioPreview');
            const audioPlayback = document.getElementById('audioPlayback');
            const playBtn = document.getElementById('playBtn');
            const sendAudioBtn = document.getElementById('sendAudioBtn');
            const cancelAudioBtn = document.getElementById('cancelAudioBtn');
            
            const audioUrl = URL.createObjectURL(recordedBlob);
            audioPlayback.src = audioUrl;
            
            audioPreview.style.display = 'block';
            playBtn.style.display = 'inline-block';
            sendAudioBtn.style.display = 'inline-block';
            cancelAudioBtn.style.display = 'inline-block';
        }
        
        function playRecording() {
            const audioPlayback = document.getElementById('audioPlayback');
            audioPlayback.play();
        }
        
        function cancelRecording() {
            const audioPreview = document.getElementById('audioPreview');
            const playBtn = document.getElementById('playBtn');
            const sendAudioBtn = document.getElementById('sendAudioBtn');
            const cancelAudioBtn = document.getElementById('cancelAudioBtn');
            
            audioPreview.style.display = 'none';
            playBtn.style.display = 'none';
            sendAudioBtn.style.display = 'none';
            cancelAudioBtn.style.display = 'none';
            
            recordedBlob = null;
        }
        
        function sendAudioMessage() {
            if (!recordedBlob) return;
            
            const formData = new FormData();
            formData.append('audio', recordedBlob, 'recording.webm');
            
            fetch(`/api/chat/${conversationId}/audio`, {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    cancelRecording();
                    loadMessages();
                }
            })
            .catch(error => {
                console.error('Error sending audio:', error);
            });
        }
        
        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>
</body>
</html>