class Chatbox {
    constructor(config) {
        console.log('[Chatbox] Constructor called with config:', config);
        this.socket = config.socket;
        this.roomId = config.roomId;
        this.myName = config.playerName;
        this.myRole = config.playerRole;
        this.roleEmojis = config.roleEmojis || {};
        this.containerId = config.containerId || 'chat-modal';
        
        this.unreadCount = 0;
        this.isChatOpen = false;
        
        this.initUI();
        this.attachListeners();
        this.attachSocketListeners();
        console.log('[Chatbox] Initialization complete');
    }

    initUI() {
        console.log('[Chatbox] initUI() - checking for existing chat-modal');
        // Inject HTML if not present
        if (!document.getElementById('chat-modal')) {
            console.log('[Chatbox] chat-modal not found, injecting HTML');
            const chatHTML = `
                <!-- Chat Modal -->
                <div id="chat-modal" class="modal hidden">
                    <div class="modal-content chat-modal-content">
                        <div class="chat-modal-header">
                            <h3>💬 Chat</h3>
                            <button id="close-chat-btn" class="close-btn">✕</button>
                        </div>
                        <div id="chat-messages"></div>
                        <div id="chat-input-area">
                            <input type="text" id="chat-input" placeholder="Type a message..." maxlength="100">
                            <button id="chat-send-btn">Send</button>
                        </div>
                    </div>
                </div>

                <!-- Floating Chat Button -->
                <button id="open-chat-btn" class="floating-chat-btn hidden">
                    💬
                    <span id="unread-badge" class="hidden">0</span>
                </button>
            `;
            document.body.insertAdjacentHTML('beforeend', chatHTML);
            console.log('[Chatbox] HTML injected');
        } else {
            console.log('[Chatbox] chat-modal already exists');
        }

        this.chatModal = document.getElementById('chat-modal');
        this.openChatBtn = document.getElementById('open-chat-btn');
        this.closeChatBtn = document.getElementById('close-chat-btn');
        this.chatInput = document.getElementById('chat-input');
        this.chatSendBtn = document.getElementById('chat-send-btn');
        this.chatMessages = document.getElementById('chat-messages');
        this.unreadBadge = document.getElementById('unread-badge');
        
        console.log('[Chatbox] Elements found:', {
            chatModal: !!this.chatModal,
            openChatBtn: !!this.openChatBtn,
            closeChatBtn: !!this.closeChatBtn
        });
    }

    attachListeners() {
        this.openChatBtn.addEventListener('click', () => this.openChat());
        this.closeChatBtn.addEventListener('click', () => this.closeChat());
        
        this.chatModal.addEventListener('click', (e) => {
            if (e.target === this.chatModal) {
                this.closeChat();
            }
        });

        this.chatSendBtn.addEventListener('click', () => this.sendMessage());
        this.chatInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') this.sendMessage();
        });
    }

    attachSocketListeners() {
        this.socket.on('chat_message', (data) => {
            this.appendMessage(data);
            
            if (!this.isChatOpen && data.sender !== this.myName) {
                this.unreadCount++;
                this.updateUnreadBadge();
            }
            
            if (this.isChatOpen && this.roomId) {
                this.socket.emit('mark_messages_seen', { roomId: this.roomId });
            }
        });

        this.socket.on('messages_seen', (data) => {
            data.messageIds.forEach(msgId => {
                const messageEl = document.querySelector(`[data-message-id="${msgId}"]`);
                if (messageEl) {
                    const seenIndicator = messageEl.querySelector('.seen-indicator');
                    if (seenIndicator) {
                        seenIndicator.innerHTML = '✓✓';
                        seenIndicator.classList.add('seen');
                    }
                }
            });
        });

        this.socket.on('chat_cleared', () => {
            if (this.chatMessages) {
                this.chatMessages.innerHTML = '';
            }
        });
    }

    openChat() {
        this.chatModal.classList.remove('hidden');
        this.isChatOpen = true;
        this.unreadCount = 0;
        this.updateUnreadBadge();
        this.chatInput.focus();
        
        if (this.roomId) {
            this.socket.emit('mark_messages_seen', { roomId: this.roomId });
        }
    }

    closeChat() {
        this.chatModal.classList.add('hidden');
        this.isChatOpen = false;
    }

    sendMessage() {
        const message = this.chatInput.value.trim();
        if (message && this.roomId) {
            this.socket.emit('chat_message', {
                roomId: this.roomId,
                message: message
            });
            this.chatInput.value = '';
        }
    }

    appendMessage(data) {
        const messageDiv = document.createElement('div');
        const isOwn = data.sender === this.myName;
        
        messageDiv.classList.add('message');
        messageDiv.classList.add(isOwn ? 'own' : 'opponent');
        messageDiv.setAttribute('data-message-id', data.id);
        
        // Header
        const headerDiv = document.createElement('div');
        headerDiv.classList.add('message-header');
        const role = data.role || data.color; // Fallback to color for backward compatibility
        const roleEmoji = this.roleEmojis[role] || '';
        headerDiv.textContent = isOwn ? 'You' : (roleEmoji ? `${data.sender} (${roleEmoji})` : data.sender);
        
        // Text
        const textDiv = document.createElement('div');
        textDiv.classList.add('message-text');
        textDiv.textContent = data.text;
        
        // Meta
        const metaDiv = document.createElement('div');
        metaDiv.classList.add('message-meta');
        
        const timeDiv = document.createElement('span');
        timeDiv.classList.add('message-time');
        timeDiv.textContent = this.formatTime(data.timestamp);
        
        metaDiv.appendChild(timeDiv);
        
        if (isOwn) {
            const seenDiv = document.createElement('span');
            seenDiv.classList.add('seen-indicator');
            
            // Determine opponent role (generic approach: find key in roleEmojis that isn't myRole)
            // Or rely on data.seenBy
            // Simplified check: if seenBy contains any role other than mine
            const isSeen = data.seenBy && data.seenBy.some(r => r !== this.myRole);
            
            seenDiv.innerHTML = isSeen ? '✓✓' : '✓';
            if (isSeen) seenDiv.classList.add('seen');
            
            metaDiv.appendChild(seenDiv);
        }
        
        messageDiv.appendChild(headerDiv);
        messageDiv.appendChild(textDiv);
        messageDiv.appendChild(metaDiv);
        
        this.chatMessages.appendChild(messageDiv);
        this.chatMessages.scrollTop = this.chatMessages.scrollHeight;
    }

    updateUnreadBadge() {
        if (this.unreadCount > 0) {
            this.unreadBadge.textContent = this.unreadCount > 9 ? '9+' : this.unreadCount;
            this.unreadBadge.classList.remove('hidden');
            this.openChatBtn.classList.add('has-unread');
        } else {
            this.unreadBadge.classList.add('hidden');
            this.openChatBtn.classList.remove('has-unread');
        }
    }

    formatTime(timestamp) {
        const date = new Date(timestamp);
        const hours = date.getHours().toString().padStart(2, '0');
        const minutes = date.getMinutes().toString().padStart(2, '0');
        return `${hours}:${minutes}`;
    }

    // Method to update config dynamically (e.g. when joining a room)
    updateConfig(config) {
        if (config.roomId) this.roomId = config.roomId;
        if (config.playerName) this.myName = config.playerName;
        if (config.playerRole) this.myRole = config.playerRole;
        if (config.roleEmojis) this.roleEmojis = config.roleEmojis;
    }

    show() {
        console.log('[Chatbox] show() called - removing hidden class');
        this.openChatBtn.classList.remove('hidden');
        console.log('[Chatbox] Button classList after show:', this.openChatBtn.classList.toString());
    }

    hide() {
        console.log('[Chatbox] hide() called');
        this.openChatBtn.classList.add('hidden');
        this.closeChat();
    }

    clearMessages() {
        if (this.chatMessages) {
            this.chatMessages.innerHTML = '';
        }
    }
    
    loadHistory(history) {
        this.clearMessages();
        if (history && history.length > 0) {
            history.forEach(msg => this.appendMessage(msg));
        }
    }
}

// Expose to global scope
window.Chatbox = Chatbox;
