class LocalChat {
    constructor() {
        this.isOpen = false;
        this.currentChannel = 'general';
        this.currentConversation = null;
        this.currentTab = 'channels';
        this.lastMessageId = 0;
        this.staffList = [];
        this.unreadCount = 0;
        this.typingTimeout = null;
        this.messagePolling = null;
        this.statusPolling = null;
        
        this.init();
    }
    
    init() {
        this.createChatWidget();
        this.attachEventListeners();
        this.startPolling();
        this.updateUserStatus('online');
        this.loadUnreadCount();
        
        window.addEventListener('beforeunload', () => {
            this.updateUserStatus('offline');
        });
    }
    
    createChatWidget() {
        const widget = document.createElement('div');
        widget.className = 'chat-widget';
        widget.innerHTML = `
            <button class="chat-toggle" id="chat-toggle">
                <i class="fas fa-comments"></i>
                <span class="chat-badge hidden" id="chat-badge">0</span>
            </button>
            
            <div class="chat-panel" id="chat-panel">
                <div class="chat-header">
                    <div>
                        <div class="chat-title">Staff Chat</div>
                        <div class="chat-status" id="chat-status">Connecté au réseau local</div>
                    </div>
                    <div class="chat-controls">
                        <button class="chat-control-btn" id="minimize-chat">
                            <i class="fas fa-minus"></i>
                        </button>
                    </div>
                </div>
                
                <div class="chat-tabs">
                    <button class="chat-tab active" data-tab="channels">Canaux</button>
                    <button class="chat-tab" data-tab="users">Staff</button>
                    <button class="chat-tab" data-tab="conversations">Messages</button>
                </div>
                
                <div class="chat-content">
                    <div id="channels-tab" class="tab-content">
                        <div class="channels-list" id="channels-list"></div>
                    </div>
                    
                    <div id="users-tab" class="tab-content hidden">
                        <div class="users-list" id="users-list"></div>
                    </div>
                    
                    <div id="conversations-tab" class="tab-content hidden">
                        <div class="users-list" id="conversations-list"></div>
                    </div>
                    
                    <div id="chat-view" class="tab-content hidden">
                        <div class="chat-messages" id="chat-messages"></div>
                        <div class="typing-indicator hidden" id="typing-indicator">
                            <span id="typing-text">Quelqu'un écrit...</span>
                            <div class="typing-dots">
                                <div class="typing-dot"></div>
                                <div class="typing-dot"></div>
                                <div class="typing-dot"></div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="chat-input">
                    <div class="input-group">
                        <input type="text" class="message-input" id="message-input" 
                               placeholder="Tapez votre message..." maxlength="500">
                        <button class="send-btn" id="send-btn" disabled>
                            <i class="fas fa-paper-plane"></i>
                        </button>
                    </div>
                </div>
            </div>
        `;
        
        document.body.appendChild(widget);
    }
    
    attachEventListeners() {
        document.getElementById('chat-toggle').addEventListener('click', () => {
            this.toggleChat();
        });
        
        document.getElementById('minimize-chat').addEventListener('click', () => {
            this.toggleChat();
        });
        
        document.querySelectorAll('.chat-tab').forEach(tab => {
            tab.addEventListener('click', (e) => {
                this.switchTab(e.target.dataset.tab);
            });
        });
        
        const messageInput = document.getElementById('message-input');
        messageInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                this.sendMessage();
            }
        });
        
        messageInput.addEventListener('input', () => {
            this.handleTyping();
            this.toggleSendButton();
        });
        
        document.getElementById('send-btn').addEventListener('click', () => {
            this.sendMessage();
        });
        
        document.addEventListener('click', (e) => {
            if (!e.target.closest('.chat-widget')) {
                // Ne pas fermer automatiquement le chat
            }
        });
    }
    
    toggleChat() {
        const panel = document.getElementById('chat-panel');
        this.isOpen = !this.isOpen;
        
        if (this.isOpen) {
            panel.classList.add('active');
            this.loadInitialData();
            document.getElementById('message-input').focus();
        } else {
            panel.classList.remove('active');
        }
    }
    
    switchTab(tabName) {
        document.querySelectorAll('.chat-tab').forEach(tab => {
            tab.classList.remove('active');
        });
        
        document.querySelector(`[data-tab="${tabName}"]`).classList.add('active');
        
        document.querySelectorAll('.tab-content').forEach(content => {
            content.classList.add('hidden');
        });
        
        this.currentTab = tabName;
        
        if (tabName === 'channels') {
            document.getElementById('channels-tab').classList.remove('hidden');
            this.loadChannels();
        } else if (tabName === 'users') {
            document.getElementById('users-tab').classList.remove('hidden');
            this.loadStaffList();
        } else if (tabName === 'conversations') {
            document.getElementById('conversations-tab').classList.remove('hidden');
            this.loadPrivateConversations();
        }
        
        this.hideMessageView();
    }
    
    showMessageView(title) {
        document.querySelectorAll('.tab-content').forEach(content => {
            content.classList.add('hidden');
        });
        
        document.getElementById('chat-view').classList.remove('hidden');
        
        const statusElement = document.getElementById('chat-status');
        statusElement.textContent = title;
        
        document.getElementById('message-input').disabled = false;
        this.toggleSendButton();
    }
    
    hideMessageView() {
        document.getElementById('chat-view').classList.add('hidden');
        document.getElementById('message-input').disabled = true;
        this.toggleSendButton();
    }
    
    async loadInitialData() {
        await this.loadChannels();
        await this.loadStaffList();
        await this.loadPrivateConversations();
    }
    
    async loadChannels() {
        try {
            const response = await fetch('chat_api.php?action=get_channels');
            const channels = await response.json();
            
            const channelsList = document.getElementById('channels-list');
            channelsList.innerHTML = '';
            
            channels.forEach(channel => {
                const item = document.createElement('div');
                item.className = `channel-item ${channel.id === this.currentChannel ? 'active' : ''}`;
                item.innerHTML = `
                    <div class="channel-icon">
                        <i class="fas fa-hashtag"></i>
                    </div>
                    <div>
                        <div class="font-medium">${channel.name}</div>
                        <div class="text-xs text-gray-500">${channel.description}</div>
                    </div>
                `;
                
                item.addEventListener('click', () => {
                    this.selectChannel(channel.id, channel.name);
                });
                
                channelsList.appendChild(item);
            });
        } catch (error) {
            console.error('Erreur lors du chargement des canaux:', error);
        }
    }
    
    async loadStaffList() {
        try {
            const response = await fetch('chat_api.php?action=get_staff_list');
            const staff = await response.json();
            this.staffList = staff;
            
            const usersList = document.getElementById('users-list');
            usersList.innerHTML = '';
            
            staff.forEach(user => {
                const item = document.createElement('div');
                item.className = 'user-item';
                item.innerHTML = `
                    <div class="user-avatar">
                        <i class="fas fa-user"></i>
                        <div class="user-status status-${user.status || 'offline'}"></div>
                    </div>
                    <div class="flex-1">
                        <div class="font-medium">${user.username}</div>
                        <div class="text-xs text-gray-500">${user.roleinimators || 'Staff'}</div>
                        <div class="text-xs text-gray-400">${user.is_online ? 'En ligne' : user.last_seen_formatted}</div>
                    </div>
                `;
                
                item.addEventListener('click', () => {
                    this.startPrivateConversation(user.id, user.username);
                });
                
                usersList.appendChild(item);
            });
        } catch (error) {
            console.error('Erreur lors du chargement du staff:', error);
        }
    }
    
    async loadPrivateConversations() {
        try {
            const response = await fetch('chat_api.php?action=get_private_conversations');
            const conversations = await response.json();
            
            const conversationsList = document.getElementById('conversations-list');
            conversationsList.innerHTML = '';
            
            if (conversations.length === 0) {
                conversationsList.innerHTML = '<div class="text-center text-gray-500 p-4">Aucune conversation</div>';
                return;
            }
            
            conversations.forEach(conv => {
                const item = document.createElement('div');
                item.className = 'user-item';
                item.innerHTML = `
                    <div class="user-avatar">
                        <i class="fas fa-user"></i>
                        ${conv.unread_count > 0 ? `<div class="chat-badge">${conv.unread_count}</div>` : ''}
                    </div>
                    <div class="flex-1">
                        <div class="font-medium">${conv.other_username}</div>
                        <div class="text-xs text-gray-500">${conv.other_role || 'Staff'}</div>
                        <div class="text-xs text-gray-400">${conv.last_message || 'Aucun message'}</div>
                        <div class="text-xs text-gray-400">${conv.last_message_formatted}</div>
                    </div>
                `;
                
                item.addEventListener('click', () => {
                    this.openPrivateConversation(conv.conversation_id, conv.other_username);
                });
                
                conversationsList.appendChild(item);
            });
        } catch (error) {
            console.error('Erreur lors du chargement des conversations:', error);
        }
    }
    
    selectChannel(channelId, channelName) {
        this.currentChannel = channelId;
        this.currentConversation = null;
        this.lastMessageId = 0;
        
        document.querySelectorAll('.channel-item').forEach(item => {
            item.classList.remove('active');
        });
        
        event.target.closest('.channel-item').classList.add('active');
        
        this.showMessageView(`Canal: ${channelName}`);
        this.loadMessages();
        this.startMessagePolling();
    }
    
    startPrivateConversation(userId, username) {
        this.currentChannel = null;
        this.currentConversation = null;
        this.lastMessageId = 0;
        
        this.showMessageView(`Message privé avec ${username}`);
        
        this.sendPrivateMessage(userId).then(() => {
            this.loadMessages();
            this.startMessagePolling();
        });
    }
    
    openPrivateConversation(conversationId, username) {
        this.currentChannel = null;
        this.currentConversation = conversationId;
        this.lastMessageId = 0;
        
        this.showMessageView(`Message privé avec ${username}`);
        this.loadMessages();
        this.startMessagePolling();
    }
    
    async sendPrivateMessage(recipientId) {
        try {
            const response = await fetch('chat_api.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    action: 'send_message',
                    message: ' ',
                    recipient_id: recipientId
                })
            });
            
            const result = await response.json();
            this.currentConversation = result.conversation_id;
        } catch (error) {
            console.error('Erreur lors de l\'initialisation de la conversation:', error);
        }
    }
    
    async loadMessages() {
        try {
            const params = new URLSearchParams({
                action: 'get_messages',
                last_id: this.lastMessageId
            });
            
            if (this.currentConversation) {
                params.append('conversation_id', this.currentConversation);
            } else {
                params.append('channel', this.currentChannel);
            }
            
            const response = await fetch(`chat_api.php?${params}`);
            const messages = await response.json();
            
            this.displayMessages(messages);
            
            if (messages.length > 0) {
                this.lastMessageId = Math.max(...messages.map(m => m.id));
            }
        } catch (error) {
            console.error('Erreur lors du chargement des messages:', error);
        }
    }
    
    displayMessages(messages) {
        const messagesContainer = document.getElementById('chat-messages');
        const wasAtBottom = this.isScrolledToBottom(messagesContainer);
        
        messages.forEach(message => {
            const messageGroup = document.createElement('div');
            messageGroup.className = `message-group ${message.is_own ? 'message-own' : ''}`;
            
            messageGroup.innerHTML = `
                <div class="message-header">
                    <span class="message-author">${message.username}</span>
                    <span class="message-time">${message.time_formatted}</span>
                </div>
                <div class="message-content">${this.escapeHtml(message.message)}</div>
            `;
            
            messagesContainer.appendChild(messageGroup);
        });
        
        if (wasAtBottom) {
            this.scrollToBottom(messagesContainer);
        }
    }
    
    async sendMessage() {
        const input = document.getElementById('message-input');
        const message = input.value.trim();
        
        if (!message) return;
        
        try {
            const body = {
                action: 'send_message',
                message: message
            };
            
            if (this.currentConversation) {
                body.conversation_id = this.currentConversation;
            } else {
                body.channel = this.currentChannel;
            }
            
            const response = await fetch('chat_api.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(body)
            });
            
            if (response.ok) {
                input.value = '';
                this.toggleSendButton();
                this.loadMessages();
            }
        } catch (error) {
            console.error('Erreur lors de l\'envoi du message:', error);
        }
    }
    
    handleTyping() {
        if (this.typingTimeout) {
            clearTimeout(this.typingTimeout);
        }
        
        this.markTyping();
        
        this.typingTimeout = setTimeout(() => {
            this.typingTimeout = null;
        }, 3000);
    }
    
    async markTyping() {
        try {
            const body = { action: 'mark_typing' };
            
            if (this.currentConversation) {
                body.conversation_id = this.currentConversation;
            } else {
                body.channel = this.currentChannel;
            }
            
            await fetch('chat_api.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(body)
            });
        } catch (error) {
            console.error('Erreur lors du marquage de frappe:', error);
        }
    }
    
    toggleSendButton() {
        const input = document.getElementById('message-input');
        const button = document.getElementById('send-btn');
        
        button.disabled = !input.value.trim() || input.disabled;
    }
    
    async updateUserStatus(status) {
        try {
            await fetch('chat_api.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    action: 'update_status',
                    status: status
                })
            });
        } catch (error) {
            console.error('Erreur lors de la mise à jour du statut:', error);
        }
    }
    
    async loadUnreadCount() {
        try {
            const response = await fetch('chat_api.php?action=get_unread_count');
            const data = await response.json();
            this.updateUnreadBadge(data.count);
        } catch (error) {
            console.error('Erreur lors du chargement des non-lus:', error);
        }
    }
    
    updateUnreadBadge(count) {
        const badge = document.getElementById('chat-badge');
        this.unreadCount = count;
        
        if (count > 0) {
            badge.textContent = count > 99 ? '99+' : count;
            badge.classList.remove('hidden');
        } else {
            badge.classList.add('hidden');
        }
    }
    
    showNotification(title, message) {
        const notification = document.createElement('div');
        notification.className = 'notification';
        notification.innerHTML = `
            <div class="notification-header">
                <div class="notification-title">${title}</div>
                <button class="notification-close">×</button>
            </div>
            <div class="notification-content">${message}</div>
        `;
        
        document.body.appendChild(notification);
        
        setTimeout(() => notification.classList.add('show'), 100);
        
        const closeBtn = notification.querySelector('.notification-close');
        closeBtn.addEventListener('click', () => {
            this.hideNotification(notification);
        });
        
        setTimeout(() => {
            this.hideNotification(notification);
        }, 5000);
    }
    
    hideNotification(notification) {
        notification.classList.remove('show');
        setTimeout(() => {
            if (notification.parentNode) {
                notification.parentNode.removeChild(notification);
            }
        }, 300);
    }
    
    startPolling() {
        this.startMessagePolling();
        this.startStatusPolling();
    }
    
    startMessagePolling() {
        if (this.messagePolling) {
            clearInterval(this.messagePolling);
        }
        
        this.messagePolling = setInterval(() => {
            if (this.isOpen && (this.currentChannel || this.currentConversation)) {
                this.loadMessages();
            }
        }, 2000);
    }
    
    startStatusPolling() {
        if (this.statusPolling) {
            clearInterval(this.statusPolling);
        }
        
        this.statusPolling = setInterval(() => {
            this.loadUnreadCount();
            if (this.currentTab === 'users') {
                this.loadStaffList();
            }
        }, 10000);
    }
    
    isScrolledToBottom(element) {
        return element.scrollHeight - element.clientHeight <= element.scrollTop + 1;
    }
    
    scrollToBottom(element) {
        element.scrollTop = element.scrollHeight;
    }
    
    escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }
}

document.addEventListener('DOMContentLoaded', function() {
    if (window.userRole === 1) {
        window.localChat = new LocalChat();
    }
});