{% extends "base.html" %}
{% from "components/ui.html" import page_header %}

{% block title %}{{ channel.name }} - {{ _('Team Chat') }} - {{ app_name }}{% endblock %}

{% block content %}
{% set breadcrumbs = [
    {'text': _('Team Chat'), 'url': url_for('team_chat.chat_index')},
    {'text': channel.name}
] %}

{{ page_header(
    icon_class='fas fa-comments',
    title_text='#' ~ channel.name,
    subtitle_text=channel.description if channel.description else _('Team chat channel'),
    breadcrumbs=breadcrumbs
) }}

<div class="grid grid-cols-1 lg:grid-cols-4 gap-6">
    <!-- Chat Messages Area -->
    <div class="lg:col-span-3 bg-card-light dark:bg-card-dark rounded-lg shadow flex flex-col" style="height: 600px;">
        <!-- Messages Container -->
        <div id="messagesContainer" class="flex-1 overflow-y-auto p-4 space-y-4">
            {% for message in messages %}
            <div class="flex items-start gap-3" data-message-id="{{ message.id }}">
                <div class="flex-shrink-0">
                    <div class="w-10 h-10 rounded-full bg-primary/20 flex items-center justify-center">
                        <i class="fas fa-user text-primary"></i>
                    </div>
                </div>
                <div class="flex-1 min-w-0">
                    <div class="flex items-center gap-2 mb-1">
                        <span class="font-semibold text-text-light dark:text-text-dark">{{ message.user.username if message.user else 'Unknown' }}</span>
                        <span class="text-xs text-text-muted-light dark:text-text-muted-dark">{{ message.created_at|local_time if message.created_at else '' }}</span>
                    </div>
                    <div class="text-text-light dark:text-text-dark whitespace-pre-wrap">{{ message.content }}</div>
                    {% if message.attachments %}
                    <div class="mt-2 space-y-1">
                        {% for attachment in message.attachments %}
                        <a href="{{ url_for('team_chat.download_attachment', message_id=message.id, attachment_id=attachment.id) }}" class="text-sm text-primary hover:underline">
                            <i class="fas fa-paperclip mr-1"></i>{{ attachment.filename }}
                        </a>
                        {% endfor %}
                    </div>
                    {% endif %}
                </div>
            </div>
            {% endfor %}
        </div>

        <!-- Message Input -->
        <div class="border-t border-border-light dark:border-border-dark p-4">
            <form id="messageForm" method="POST" action="{{ url_for('team_chat.send_message', channel_id=channel.id) }}" class="flex gap-2">
                <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
                <div class="flex-1 relative">
                    <textarea id="messageInput" name="content" rows="2" class="form-input w-full resize-none" placeholder="{{ _('Type a message...') }}" required></textarea>
                    <div class="absolute bottom-2 right-2 flex gap-1">
                        <button type="button" onclick="showEmojiPicker()" class="text-text-muted-light dark:text-text-muted-dark hover:text-primary">
                            <i class="fas fa-smile"></i>
                        </button>
                        <button type="button" onclick="showAttachmentModal()" class="text-text-muted-light dark:text-text-muted-dark hover:text-primary">
                            <i class="fas fa-paperclip"></i>
                        </button>
                    </div>
                </div>
                <button type="submit" class="bg-primary text-white px-6 py-2 rounded-lg hover:bg-primary-dark transition-colors self-end">
                    <i class="fas fa-paper-plane"></i>
                </button>
            </form>
        </div>
    </div>

    <!-- Channel Info Sidebar -->
    <div class="lg:col-span-1 bg-card-light dark:bg-card-dark p-4 rounded-lg shadow">
        <h3 class="text-lg font-semibold mb-4">{{ _('Channel Info') }}</h3>
        
        {% if channel.description %}
        <div class="mb-4">
            <p class="text-sm text-text-muted-light dark:text-text-muted-dark">{{ channel.description }}</p>
        </div>
        {% endif %}

        <div class="mb-4">
            <h4 class="text-sm font-semibold mb-2">{{ _('Members') }} ({{ members|length }})</h4>
            <div class="space-y-2">
                {% for member in members %}
                {% set user = member.user %}
                {% if user %}
                    {% set user_status = user.get_status() %}
                    {% set status_colors = {'online': 'bg-green-500', 'away': 'bg-yellow-500', 'offline': 'bg-gray-400'} %}
                    {% set status_color = status_colors.get(user_status, 'bg-gray-400') %}
                    <div class="flex items-center gap-2">
                        <div class="relative flex-shrink-0">
                            {% if user.get_avatar_url() %}
                                <img src="{{ user.get_avatar_url() }}" alt="{{ user.display_name }}" class="w-8 h-8 rounded-full object-cover" onerror="this.onerror=null; this.style.display='none'; this.nextElementSibling.style.display='flex';">
                                <div class="w-8 h-8 rounded-full bg-primary/20 text-primary flex items-center justify-center font-semibold text-xs" style="display: none;">
                                    {{ user.display_name[0:1].upper() }}
                                </div>
                            {% else %}
                                <div class="w-8 h-8 rounded-full bg-primary/20 text-primary flex items-center justify-center font-semibold text-xs">
                                    {{ user.display_name[0:1].upper() }}
                                </div>
                            {% endif %}
                            <span class="absolute bottom-0 right-0 w-2.5 h-2.5 {{ status_color }} border-2 border-card-light dark:border-card-dark rounded-full" title="{{ user_status|capitalize }}"></span>
                        </div>
                        <div class="flex-1 min-w-0">
                            <span class="text-sm font-medium">{{ user.display_name }}</span>
                            <span class="text-xs text-text-muted-light dark:text-text-muted-dark ml-2 capitalize">({{ user_status }})</span>
                        </div>
                    </div>
                {% else %}
                    <div class="flex items-center gap-2">
                        <div class="w-8 h-8 rounded-full bg-primary/20 flex items-center justify-center">
                            <i class="fas fa-user text-primary text-xs"></i>
                        </div>
                        <span class="text-sm">Unknown</span>
                    </div>
                {% endif %}
                {% endfor %}
            </div>
        </div>

        {% if current_user.is_admin or channel.created_by == current_user.id %}
        <div class="pt-4 border-t border-border-light dark:border-border-dark">
            <a href="{{ url_for('team_chat.edit_channel', channel_id=channel.id) }}" class="text-sm text-primary hover:underline">
                <i class="fas fa-cog mr-1"></i>{{ _('Channel Settings') }}
            </a>
        </div>
        {% endif %}
    </div>
</div>

<script>
// Auto-scroll to bottom on load
document.addEventListener('DOMContentLoaded', function() {
    const container = document.getElementById('messagesContainer');
    if (container) {
        container.scrollTop = container.scrollHeight;
    }
});

// WebSocket for real-time messages
if (typeof io !== 'undefined') {
    const socket = io();
    
    socket.on('connect', function() {
        socket.emit('join_channel', { channel_id: {{ channel.id }} });
    });
    
    socket.on('new_message', function(data) {
        if (data.channel_id === {{ channel.id }}) {
            // Reload messages or append new message
            location.reload();
        }
    });
}

// Form submission
document.getElementById('messageForm').addEventListener('submit', function(e) {
    e.preventDefault();
    const form = this;
    const formData = new FormData(form);
    
    fetch(form.action, {
        method: 'POST',
        body: formData,
        headers: {
            'X-Requested-With': 'XMLHttpRequest'
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            form.reset();
            // Reload messages
            location.reload();
        } else {
            alert(data.error || 'Failed to send message');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('Failed to send message');
    });
});

// Emoji picker
let selectedEmoji = null;
const commonEmojis = ['😀', '😃', '😄', '😁', '😅', '🤣', '😂', '🙂', '🙃', '😉', '😊', '😇', '🥰', '😍', '🤩', '😘', '😗', '😋', '😛', '😜', '🤪', '😝', '🤑', '🤗', '🤭', '🤫', '🤔', '🤐', '🤨', '😐', '😑', '😶', '😏', '😒', '🙄', '😬', '🤥', '😌', '😔', '😪', '🤤', '😴', '😷', '🤒', '🤕', '🤢', '🤮', '🤧', '🥵', '🥶', '😶‍🌫️', '😱', '😨', '😰', '😥', '😓', '🤗', '🤔', '🤭', '🤫', '🤥', '😶', '😐', '😑', '😬', '🙄', '😯', '😦', '😧', '😮', '😲', '🥱', '😴', '🤤', '😪', '😵', '😵‍💫', '🤐', '🥴', '🤢', '🤮', '🤧', '😷', '🤒', '🤕', '🤑', '🤠', '😈', '👿', '👹', '👺', '🤡', '💩', '👻', '💀', '☠️', '👽', '👾', '🤖', '🎃', '😺', '😸', '😹', '😻', '😼', '😽', '🙀', '😿', '😾'];

function showEmojiPicker() {
    // Remove existing emoji picker if any
    const existingPicker = document.getElementById('emojiPicker');
    if (existingPicker) {
        existingPicker.remove();
        return;
    }

    // Create emoji picker popup
    const picker = document.createElement('div');
    picker.id = 'emojiPicker';
    picker.className = 'absolute bottom-full right-0 mb-2 bg-card-light dark:bg-card-dark border border-border-light dark:border-border-dark rounded-lg shadow-lg p-4 max-w-xs max-h-64 overflow-y-auto z-50';
    picker.innerHTML = `
        <div class="grid grid-cols-8 gap-2">
            ${commonEmojis.map(emoji => `<button type="button" class="text-2xl hover:scale-125 transition-transform p-1" onclick="insertEmoji('${emoji}')" title="${emoji}">${emoji}</button>`).join('')}
        </div>
    `;

    // Position it relative to the emoji button
    const emojiBtn = event.target.closest('button');
    const relativeContainer = emojiBtn.closest('.relative');
    relativeContainer.style.position = 'relative';
    relativeContainer.appendChild(picker);

    // Close picker when clicking outside
    setTimeout(() => {
        document.addEventListener('click', function closePicker(e) {
            if (!picker.contains(e.target) && e.target !== emojiBtn && !emojiBtn.contains(e.target)) {
                picker.remove();
                document.removeEventListener('click', closePicker);
            }
        });
    }, 100);
}

function insertEmoji(emoji) {
    const messageInput = document.getElementById('messageInput');
    const cursorPos = messageInput.selectionStart;
    const textBefore = messageInput.value.substring(0, cursorPos);
    const textAfter = messageInput.value.substring(cursorPos);
    
    messageInput.value = textBefore + emoji + textAfter;
    messageInput.focus();
    messageInput.setSelectionRange(cursorPos + emoji.length, cursorPos + emoji.length);
    
    // Remove emoji picker
    const picker = document.getElementById('emojiPicker');
    if (picker) picker.remove();
}

// Attachment modal
let pendingAttachments = [];

function showAttachmentModal() {
    const modal = document.createElement('div');
    modal.id = 'attachmentModal';
    modal.className = 'fixed inset-0 z-50 flex items-center justify-center bg-black/50';
    modal.innerHTML = `
        <div class="bg-card-light dark:bg-card-dark rounded-lg shadow-xl max-w-md w-full mx-4">
            <div class="p-6">
                <div class="flex justify-between items-center mb-4">
                    <h3 class="text-lg font-semibold">{{ _('Upload Attachment') }}</h3>
                    <button type="button" onclick="closeAttachmentModal()" class="text-text-muted-light dark:text-text-muted-dark hover:text-text-light dark:hover:text-text-dark">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
                <form id="attachmentUploadForm" onsubmit="uploadAttachment(event)" enctype="multipart/form-data">
                    <div class="mb-4">
                        <label class="block text-sm font-medium mb-2">{{ _('Select File') }}</label>
                        <input type="file" id="attachmentFile" name="file" class="form-input w-full" required>
                        <p class="text-xs text-text-muted-light dark:text-text-muted-dark mt-1">{{ _('Maximum file size: 10 MB') }}</p>
                    </div>
                    <div id="attachmentPreview" class="mb-4 hidden">
                        <p class="text-sm text-text-muted-light dark:text-text-muted-dark">{{ _('Selected:') }} <span id="fileName"></span></p>
                    </div>
                    <div class="flex gap-2">
                        <button type="button" onclick="closeAttachmentModal()" class="flex-1 px-4 py-2 bg-gray-200 dark:bg-gray-700 text-gray-800 dark:text-gray-200 rounded-lg hover:bg-gray-300 dark:hover:bg-gray-600 transition-colors">
                            {{ _('Cancel') }}
                        </button>
                        <button type="submit" class="flex-1 px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary/90 transition-colors">
                            {{ _('Upload') }}
                        </button>
                    </div>
                </form>
            </div>
        </div>
    `;
    document.body.appendChild(modal);

    // Preview file name
    document.getElementById('attachmentFile').addEventListener('change', function(e) {
        const file = e.target.files[0];
        if (file) {
            document.getElementById('fileName').textContent = file.name;
            document.getElementById('attachmentPreview').classList.remove('hidden');
        }
    });
}

function closeAttachmentModal() {
    const modal = document.getElementById('attachmentModal');
    if (modal) modal.remove();
}

function uploadAttachment(event) {
    event.preventDefault();
    const form = event.target;
    const formData = new FormData(form);
    const fileInput = document.getElementById('attachmentFile');
    const file = fileInput.files[0];

    if (!file) {
        alert('{{ _("Please select a file") }}');
        return;
    }

    // Check file size (10 MB)
    if (file.size > 10 * 1024 * 1024) {
        alert('{{ _("File size exceeds 10 MB limit") }}');
        return;
    }

    const uploadBtn = form.querySelector('button[type="submit"]');
    const originalText = uploadBtn.innerHTML;
    uploadBtn.disabled = true;
    uploadBtn.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>{{ _("Uploading...") }}';

    fetch('{{ url_for("team_chat.upload_attachment", channel_id=channel.id) }}', {
        method: 'POST',
        body: formData,
        headers: {
            'X-CSRFToken': '{{ csrf_token() }}'
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            pendingAttachments.push(data.attachment);
            closeAttachmentModal();
            
            // Show attachment indicator
            const messageInput = document.getElementById('messageInput');
            const attachmentIndicator = document.createElement('div');
            attachmentIndicator.id = 'attachmentIndicator';
            attachmentIndicator.className = 'mt-2 p-2 bg-blue-100 dark:bg-blue-900 rounded text-sm';
            attachmentIndicator.innerHTML = `
                <i class="fas fa-paperclip mr-2"></i>${data.attachment.filename}
                <button type="button" onclick="removeAttachment()" class="ml-2 text-red-600 hover:text-red-800">
                    <i class="fas fa-times"></i>
                </button>
            `;
            
            const messageForm = document.getElementById('messageForm');
            if (!document.getElementById('attachmentIndicator')) {
                messageForm.parentElement.insertBefore(attachmentIndicator, messageForm);
            }
        } else {
            alert(data.error || '{{ _("Failed to upload attachment") }}');
            uploadBtn.disabled = false;
            uploadBtn.innerHTML = originalText;
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('{{ _("Failed to upload attachment") }}');
        uploadBtn.disabled = false;
        uploadBtn.innerHTML = originalText;
    });
}

function removeAttachment() {
    pendingAttachments = [];
    const indicator = document.getElementById('attachmentIndicator');
    if (indicator) indicator.remove();
}

// Update message form submission to include attachments
const originalSubmit = document.getElementById('messageForm').onsubmit;
document.getElementById('messageForm').addEventListener('submit', function(e) {
    e.preventDefault();
    const form = this;
    const formData = new FormData(form);
    
    // Add attachment data if any
    if (pendingAttachments.length > 0) {
        formData.append('attachment_data', JSON.stringify(pendingAttachments[0]));
        formData.append('message_type', 'file');
    }
    
    fetch(form.action, {
        method: 'POST',
        body: formData,
        headers: {
            'X-Requested-With': 'XMLHttpRequest'
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            form.reset();
            pendingAttachments = [];
            const indicator = document.getElementById('attachmentIndicator');
            if (indicator) indicator.remove();
            location.reload();
        } else {
            alert(data.error || 'Failed to send message');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('Failed to send message');
    });
});
</script>
{% endblock %}

