class UserChatSystem extends ChatSystem {
    constructor(config) {
        super(config);
        
        // User-specific properties
        this.adminInfo = config.adminInfo || {};
        this.typingTimeout = null;
        this.notificationAudio = null;
        
        // 🔥 ADD: Status debounce untuk handle reconnection
        this.statusDebounceTimer = null;
        this.lastKnownStatus = false; // false = offline, true = online
        
        // Initialize UI
        this.initUI();
    }
    
    initUI() {
        this.createChatBubble();
        this.loadMessages();
        this.setupUserEventListeners();
    }
    
    createChatBubble() {
        // Create floating chat button
        const chatFab = document.createElement('button');
        chatFab.className = 'chat-fab';
        chatFab.innerHTML = `
            <i class="fas fa-comment-dots"></i>
            <span class="unread-badge" style="display: none;"></span>
        `;
        
        // Create chat window
        const chatWindow = document.createElement('div');
        chatWindow.className = 'chat-window';
        chatWindow.innerHTML = `
            <div class="chat-header">
                <div class="chat-user-info">
                    <div class="chat-user-avatar">
                        ${this.adminInfo.avatar ? 
                            `<img src="${this.adminInfo.avatar}" alt="${this.adminInfo.name}">` :
                            (this.adminInfo.name || 'Admin').charAt(0).toUpperCase()
                        }
                        <span class="online-dot offline"></span>
                    </div>
                    <div class="chat-user-details">
                        <h4>${this.adminInfo.name || 'Admin'}</h4>
                        <small class="user-status offline">Checking...</small>
                    </div>
                </div>
                <div class="chat-actions">
                    <button class="btn-minimize" title="Minimize">
                        <i class="fas fa-minus"></i>
                    </button>
                    <button class="btn-close" title="Close">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
            </div>
            
            <div class="messages-container">
                <div class="loading-messages">
                    <div class="spinner"></div>
                    <p>Loading messages...</p>
                </div>
            </div>
            
            <div class="typing-indicator" style="display: none;">
                <div class="typing-dots">
                    <span></span>
                    <span></span>
                    <span></span>
                </div>
                <span class="typing-text">${this.adminInfo.name || 'Admin'} is typing...</span>
            </div>
            
            <div class="message-input-container">
                <div class="input-wrapper">
                    <textarea 
                        class="message-input"
                        placeholder="Type a message..."
                        rows="1"></textarea>
                    <button class="btn-send" title="Send message">
                        <i class="fas fa-paper-plane"></i>
                    </button>
                </div>
            </div>
        `;
        
        // Append to body
        document.body.appendChild(chatFab);
        document.body.appendChild(chatWindow);
        
        // Store references
        this.elements = {
            fab: chatFab,
            window: chatWindow,
            messagesContainer: chatWindow.querySelector('.messages-container'),
            typingIndicator: chatWindow.querySelector('.typing-indicator'),
            messageInput: chatWindow.querySelector('.message-input'),
            sendButton: chatWindow.querySelector('.btn-send'),
            unreadBadge: chatFab.querySelector('.unread-badge'),
            onlineDot: chatWindow.querySelector('.online-dot'),
            userStatus: chatWindow.querySelector('.user-status'),
            minimizeBtn: chatWindow.querySelector('.btn-minimize'),
            closeBtn: chatWindow.querySelector('.btn-close')
        };
        
        // Set admin info
        this.activeConversation = {
            type: 'admin',
            id: this.adminInfo.id,
            name: this.adminInfo.name
        };
    }
    
    setupUserEventListeners() {
        console.log('🎯 [USER] Setting up event listeners');
        
        // Prevent multiple event listeners
        const newFab = this.elements.fab.cloneNode(true);
        this.elements.fab.parentNode.replaceChild(newFab, this.elements.fab);
        this.elements.fab = newFab;
        this.elements.unreadBadge = newFab.querySelector('.unread-badge');
        
        // FAB click
        this.elements.fab.addEventListener('click', (e) => {
            e.stopPropagation();
            this.toggleChatWindow();
        }, { once: false });
        
        // Clone send button
        const newSendBtn = this.elements.sendButton.cloneNode(true);
        this.elements.sendButton.parentNode.replaceChild(newSendBtn, this.elements.sendButton);
        this.elements.sendButton = newSendBtn;
        
        // Send message on Enter
        this.elements.messageInput.addEventListener('keydown', (e) => {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                this.sendMessageToAdmin();
            }
        });
        
        // Send button
        this.elements.sendButton.addEventListener('click', () => {
            this.sendMessageToAdmin();
        });
        
        // Auto-resize textarea
        this.elements.messageInput.addEventListener('input', () => {
            this.autoResizeTextarea(this.elements.messageInput);
            this.handleTyping();
        });
        
        // Minimize/close buttons
        this.elements.minimizeBtn.addEventListener('click', () => {
            this.elements.window.classList.toggle('minimized');
        });
        
        this.elements.closeBtn.addEventListener('click', () => {
            this.closeChatWindow();
        });
        
        // Close when clicking outside
        document.addEventListener('click', (e) => {
            if (!this.elements.window.contains(e.target) && 
                !this.elements.fab.contains(e.target) &&
                this.elements.window.classList.contains('active')) {
                this.closeChatWindow();
            }
        });
        
        // Listen for chat events
        this.on('auth_success', () => {
            console.log('✅ [USER] Auth success - reloading messages');
            this.loadMessages();
            
            // Check admin status after connection established
            setTimeout(() => {
                this.checkAdminOnlineStatus();
            }, 500);
        });
        
        this.on('new_message', (message) => {
            console.log('📨 [USER EVENT] New message received');
            
            const isOwnMessage = (
                message.from.type === this.config.userType && 
                parseInt(message.from.id) === parseInt(this.config.userId)
            );
            
            if (isOwnMessage) {
                return;
            }
            
            this.addMessageToUI(message, false);
            
            const isWindowActive = this.elements.window.classList.contains('active');
            
            // Play sound for incoming messages
            this.playNotificationSound();
            
            if (!isWindowActive) {
                this.incrementUnreadCount();
                this.showNotification(message);
            } else {
                this.markMessagesAsRead();
            }
        });
        
        this.on('typing', (message) => {
            if (message.isTyping) {
                this.showTypingIndicator();
            } else {
                this.hideTypingIndicator();
            }
        });
        
        // 🔥 FIXED: Debounced status updates
        this.on('user_online', (message) => {
            console.log('🟢 [USER EVENT] User online event received');
            if (message.user.type === 'admin' && 
                parseInt(message.user.id) === parseInt(this.adminInfo.id)) {
                this.updateAdminStatusDebounced(true);
            }
        });
        
        this.on('user_offline', (message) => {
            console.log('🔴 [USER EVENT] User offline event received');
            if (message.user.type === 'admin' && 
                parseInt(message.user.id) === parseInt(this.adminInfo.id)) {
                // Delay offline status untuk memberi waktu reconnect
                this.updateAdminStatusDebounced(false);
            }
        });
        
        console.log('✅ [USER] Event listeners setup complete');
    }
    
    // 🔥 NEW: Debounced status update untuk handle reconnection
    updateAdminStatusDebounced(isOnline) {
        console.log('🔄 [STATUS] Debounced update:', isOnline ? 'Online' : 'Offline');
        
        // Clear existing timer
        if (this.statusDebounceTimer) {
            clearTimeout(this.statusDebounceTimer);
        }
        
        if (isOnline) {
            // Update to online immediately
            this.lastKnownStatus = true;
            this.updateAdminStatus(true);
        } else {
            // Delay offline status by 3 seconds to allow reconnection
            console.log('⏳ [STATUS] Delaying offline status for 3s...');
            this.statusDebounceTimer = setTimeout(() => {
                // Only update to offline if we haven't received online event
                if (!this.lastKnownStatus) {
                    console.log('❌ [STATUS] Confirmed offline after delay');
                    this.updateAdminStatus(false);
                } else {
                    console.log('✅ [STATUS] Reconnected, keeping online status');
                }
            }, 3000);
            
            // Mark as potentially offline
            this.lastKnownStatus = false;
        }
    }
    
    checkAdminOnlineStatus() {
        if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
            console.log('⚠️ [STATUS] Cannot check - WebSocket not ready');
            return;
        }
        
        console.log('🔍 [STATUS] Checking admin online status...');
        this.ws.send(JSON.stringify({
            type: 'get_online_status',
            target: {
                type: 'admin',
                id: this.adminInfo.id
            }
        }));
    }
    
    async loadMessages() {
        console.log('🔥 Loading messages from API...');
        try {
            const url = `${this.config.apiUrl}/get_messages`;
            
            const response = await fetch(url, {
                method: 'GET',
                credentials: 'same-origin'
            });
            
            if (!response.ok) {
                throw new Error(`HTTP ${response.status}: ${response.statusText}`);
            }
            
            const data = await response.json();
            
            if (data.status) {
                this.renderMessages(data.messages);
            } else {
                this.elements.messagesContainer.innerHTML = `
                    <div class="empty-messages">
                        <i class="fas fa-exclamation-triangle"></i>
                        <p>Error loading messages</p>
                    </div>
                `;
            }
        } catch (error) {
            console.error('❌ Error loading messages:', error);
            this.elements.messagesContainer.innerHTML = `
                <div class="empty-messages">
                    <i class="fas fa-exclamation-triangle"></i>
                    <p>Failed to load messages</p>
                </div>
            `;
        }
    }
    
    renderMessages(messages) {
        const container = this.elements.messagesContainer;
        container.innerHTML = '';
        
        if (messages.length === 0) {
            container.innerHTML = `
                <div class="empty-messages">
                    <i class="fas fa-comments"></i>
                    <p>No messages yet</p>
                    <p>Say hello to your admin!</p>
                </div>
            `;
            return;
        }
        
        messages.sort((a, b) => new Date(a.created_at) - new Date(b.created_at));
        
        messages.forEach(message => {
            const messageElement = this.createMessageElement(message);
            container.appendChild(messageElement);
        });
        
        setTimeout(() => {
            container.scrollTop = container.scrollHeight;
        }, 100);
    }
    
    createMessageElement(message) {
        const isOwnMessage = message.sender === 'penghuni';
        const time = this.formatTime(message.created_at);
        
        const element = document.createElement('div');
        element.className = `message ${isOwnMessage ? 'message-sent' : 'message-received'}`;
        element.dataset.messageId = message.id_chat;
        
        element.innerHTML = `
            <div class="message-content">
                <div class="message-text">${this.escapeHtml(message.message)}</div>
                <div class="message-meta">
                    <span class="message-time">${time}</span>
                    ${isOwnMessage ? 
                        `<span class="message-status">
                            ${message.is_read_admin ? '✓✓' : '✓'}
                        </span>` : 
                        ''
                    }
                </div>
            </div>
        `;
        
        return element;
    }
    
    sendMessageToAdmin() {
        const message = this.elements.messageInput.value.trim();
        if (!message) return;
        
        console.log('📤 Sending message:', message);
        
        if (!this.isAuthenticated) {
            console.error('❌ Not authenticated');
            alert('Connection not established. Please wait...');
            return;
        }
        
        // Clear input BEFORE sending
        this.elements.messageInput.value = '';
        this.autoResizeTextarea(this.elements.messageInput);
        
        // Stop typing immediately when sending
        this.stopTyping();
        
        // Send via WebSocket
        const messageId = this.sendMessage(
            {
                type: 'admin',
                id: this.adminInfo.id
            },
            message
        );
        
        console.log('✅ Message sent with ID:', messageId);
        
        return messageId;
    }
    
    handleTyping() {
        const message = this.elements.messageInput.value.trim();
        
        if (!message) {
            this.stopTyping();
            return;
        }
        
        const now = Date.now();
        
        if (now - this.lastTypingSent > 1000) {
            this.sendTypingIndicator(
                { type: 'admin', id: this.adminInfo.id },
                true
            );
            this.lastTypingSent = now;
        }
        
        if (this.typingTimeout) {
            clearTimeout(this.typingTimeout);
        }
        
        this.typingTimeout = setTimeout(() => {
            this.stopTyping();
        }, 2000);
    }
    
    stopTyping() {
        if (this.typingTimeout) {
            clearTimeout(this.typingTimeout);
            this.typingTimeout = null;
        }
        
        this.sendTypingIndicator(
            { type: 'admin', id: this.adminInfo.id },
            false
        );
    }
    
    toggleChatWindow() {
        this.elements.window.classList.toggle('active');
        
        if (this.elements.window.classList.contains('active')) {
            this.markMessagesAsRead();
            this.checkAdminOnlineStatus();
            
            setTimeout(() => {
                if (this.elements.messageInput) {
                    this.elements.messageInput.focus();
                }
            }, 100);
        } else {
            this.stopTyping();
        }
    }
    
    closeChatWindow() {
        this.elements.window.classList.remove('active');
        this.stopTyping();
    }
    
    addMessageToUI(message, isOwnMessage) {
        const existingMsg = this.elements.messagesContainer.querySelector(
            `[data-message-id="${message.messageId}"]`
        );
        
        if (existingMsg) {
            return;
        }
        
        const messageElement = this.createMessageElementFromWS(message, isOwnMessage);
        this.elements.messagesContainer.appendChild(messageElement);
        
        if (this.elements.window.classList.contains('active')) {
            setTimeout(() => {
                this.elements.messagesContainer.scrollTop = this.elements.messagesContainer.scrollHeight;
            }, 50);
        }
    }
    
    createMessageElementFromWS(message, isOwnMessage) {
        const time = this.formatTime(message.timestamp);
        
        const element = document.createElement('div');
        element.className = `message ${isOwnMessage ? 'message-sent' : 'message-received'}`;
        element.dataset.messageId = message.messageId;
        
        element.innerHTML = `
            <div class="message-content">
                <div class="message-text">${this.escapeHtml(message.content)}</div>
                <div class="message-meta">
                    <span class="message-time">${time}</span>
                    ${isOwnMessage ? 
                        `<span class="message-status">
                            ${message.isDelivered ? '✓✓' : '✓'}
                        </span>` : 
                        ''
                    }
                </div>
            </div>
        `;
        
        return element;
    }
    
    updateMessageStatus(messageId, status) {
        const messageElement = this.elements.messagesContainer.querySelector(
            `[data-message-id="${messageId}"]`
        );
        
        if (messageElement) {
            const statusElement = messageElement.querySelector('.message-status');
            if (statusElement) {
                statusElement.textContent = status === 'read' ? '✓✓' : '✓✓';
            }
        }
    }
    
    showTypingIndicator() {
        this.elements.typingIndicator.style.display = 'flex';
        
        setTimeout(() => {
            if (this.elements.typingIndicator.style.display === 'flex') {
                this.hideTypingIndicator();
            }
        }, 5000);
    }
    
    hideTypingIndicator() {
        this.elements.typingIndicator.style.display = 'none';
    }
    
    updateUserStatus(user, isOnline) {
        if (user.type === 'admin' && 
            parseInt(user.id) === parseInt(this.adminInfo.id)) {
            this.updateAdminStatus(isOnline);
        }
    }
    
    updateAdminStatus(isOnline) {
        console.log('🔄 [STATUS] Updating UI:', isOnline ? 'Online' : 'Offline');
        this.elements.onlineDot.className = `online-dot ${isOnline ? 'online' : 'offline'}`;
        this.elements.userStatus.textContent = isOnline ? 'Online' : 'Offline';
        this.elements.userStatus.className = `user-status ${isOnline ? 'online' : 'offline'}`;
    }
    
    incrementUnreadCount() {
        let currentCount = parseInt(this.elements.unreadBadge.textContent) || 0;
        currentCount++;
        
        this.elements.unreadBadge.textContent = currentCount > 9 ? '9+' : currentCount;
        this.elements.unreadBadge.style.display = 'flex';
        
        this.elements.fab.style.animation = 'pulse 1s';
        setTimeout(() => {
            this.elements.fab.style.animation = '';
        }, 1000);
    }
    
    markMessagesAsRead() {
        this.elements.unreadBadge.style.display = 'none';
        
        const messageIds = Array.from(
            this.elements.messagesContainer.querySelectorAll('.message-received[data-message-id]')
        ).map(el => el.dataset.messageId);
        
        if (messageIds.length > 0) {
            this.markAsRead(messageIds);
        }
    }
    
    showNotification(message) {
        if (!("Notification" in window)) return;
        
        if (Notification.permission === "granted") {
            this.createNotification(message);
        } else if (Notification.permission !== "denied") {
            Notification.requestPermission().then(permission => {
                if (permission === "granted") {
                    this.createNotification(message);
                }
            });
        }
    }
    
    createNotification(message) {
        const notification = new Notification(this.adminInfo.name || 'Admin', {
            body: message.content.length > 50 ? 
                  message.content.substring(0, 50) + '...' : 
                  message.content,
            icon: '/asset/img/notification-icon.png',
            badge: '/asset/img/chat-badge.png',
            tag: 'chat-notification',
            requireInteraction: false
        });
        
        notification.onclick = () => {
            window.focus();
            this.toggleChatWindow();
            notification.close();
        };
        
        setTimeout(() => notification.close(), 5000);
    }
    
    playNotificationSound() {
        try {
            const audioPath = '/sistemkos/asset/sounds/notification.mp3';
            
            if (!this.notificationAudio) {
                this.notificationAudio = new Audio(audioPath);
                this.notificationAudio.volume = 0.5;
            }
            
            this.notificationAudio.currentTime = 0;
            
            const playPromise = this.notificationAudio.play();
            
            if (playPromise !== undefined) {
                playPromise.catch(() => {
                    // Silently handle autoplay restrictions
                });
            }
        } catch (error) {
            // Silently handle errors
        }
    }
    
    autoResizeTextarea(textarea) {
        textarea.style.height = 'auto';
        textarea.style.height = Math.min(textarea.scrollHeight, 100) + 'px';
    }
}