document.addEventListener('DOMContentLoaded', function() {
    // Handle attachment button click
    const attachmentBtn = document.getElementById('attachment-btn');
    const attachmentInput = document.getElementById('attachment-input');
    const attachmentPreview = document.getElementById('attachment-preview');
    
    if (attachmentBtn && attachmentInput) {
        attachmentBtn.addEventListener('click', function() {
            attachmentInput.click();
        });
        
        attachmentInput.addEventListener('change', function() {
            if (this.files && this.files[0]) {
                const fileName = this.files[0].name;
                attachmentPreview.innerHTML = `
                    <div class="alert alert-info">
                        <i class="fas fa-paperclip"></i> ${fileName}
                        <button type="button" class="close" data-dismiss="alert">&times;</button>
                    </div>
                `;
            }
        });
    }
    
    // Handle message form submission
    const messageForm = document.getElementById('message-form');
    if (messageForm) {
        messageForm.addEventListener('submit', function(e) {
            e.preventDefault();
            
            const formData = new FormData(this);
            const messageContainer = document.getElementById('message-container');
            
            fetch(this.action, {
                method: 'POST',
                body: formData,
                headers: {
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
                    'X-Requested-With': 'XMLHttpRequest'
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // Clear the form
                    this.reset();
                    attachmentPreview.innerHTML = '';
                    
                    // Add the new message to the container
                    const newMessage = document.createElement('div');
                    newMessage.className = 'direct-chat-msg right';
                    newMessage.innerHTML = `
                        <div class="direct-chat-infos clearfix">
                            <span class="direct-chat-name float-left">You</span>
                            <span class="direct-chat-timestamp float-right">Just now</span>
                        </div>
                        <div class="direct-chat-text">
                            ${formData.get('body')}
                        </div>
                    `;
                    messageContainer.appendChild(newMessage);
                    
                    // Scroll to bottom
                    messageContainer.scrollTop = messageContainer.scrollHeight;
                } else {
                    alert('Error sending message: ' + (data.message || 'Unknown error'));
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('Error sending message. Please try again.');
            });
        });
    }
    
    // Auto-scroll to bottom of messages
    const messageContainer = document.getElementById('message-container');
    if (messageContainer) {
        messageContainer.scrollTop = messageContainer.scrollHeight;
    }
});