/**
 * Live Chat Widget - Fake Chat System
 * Membuat tampilan chat seperti live chat pada umumnya
 */

class LiveChatWidget {
    constructor() {
        this.isOpen = false;
        this.messages = [];
        this.unreadCount = 0;
        this.username = this.generateRandomUsername();
        this.lastMessageTime = Date.now();
        
        this.init();
        this.loadInitialMessages();
        this.startFakeMessageGenerator();
        this.startPolling();
    }
    
    init() {
        // Create chat widget HTML
        const widgetHTML = `
            <div class="chat-widget-container">
                <!-- Chat Button -->
                <button class="chat-widget-button" onclick="liveChat.toggle()">
                    <i class="fas fa-comments"></i>
                    <span class="chat-notification-badge" id="chatNotifBadge" style="display:none;">0</span>
                </button>
                
                <!-- Chat Box -->
                <div class="chat-widget-box" id="chatWidgetBox">
                    <!-- Header -->
                    <div class="chat-widget-header">
                        <div class="chat-header-info">
                            <div class="chat-header-avatar">
                                <i class="fas fa-comments"></i>
                            </div>
                            <div class="chat-header-text">
                                <h5>Live Chat</h5>
                                <p><span class="chat-online-indicator"></span><span id="onlineCount">0</span> Online</p>
                            </div>
                        </div>
                        <button class="chat-close-btn" onclick="liveChat.close()">
                            <i class="fas fa-times"></i>
                        </button>
                    </div>
                    
                    <!-- Messages Area -->
                    <div class="chat-widget-messages" id="chatMessages">
                        <!-- Messages will be inserted here -->
                    </div>
                    
                    <!-- Typing Indicator -->
                    <div class="chat-typing-indicator" id="typingIndicator">
                        <i class="fas fa-circle-notch fa-spin"></i> 
                        <span id="typingUser">Admin</span> sedang mengetik
                        <span class="chat-typing-dots"><span>.</span><span>.</span><span>.</span></span>
                    </div>
                    
                    <!-- Input Area -->
                    <div class="chat-widget-input">
                        <div class="chat-input-wrapper">
                            <input type="text" 
                                   class="chat-input-field" 
                                   id="chatInputField" 
                                   placeholder="Ketik pesan Anda..."
                                   onkeypress="liveChat.handleKeyPress(event)">
                            <button class="chat-send-btn" onclick="liveChat.sendMessage()">
                                <i class="fas fa-paper-plane"></i>
                            </button>
                        </div>
                    </div>
                </div>
                
                <!-- Toast Notification -->
                <div class="chat-toast-notification" id="chatToast">
                    <div class="chat-toast-header">
                        <div class="chat-toast-avatar" id="toastAvatar"></div>
                        <div class="chat-toast-name" id="toastName"></div>
                    </div>
                    <div class="chat-toast-message" id="toastMessage"></div>
                </div>
            </div>
        `;
        
        document.body.insertAdjacentHTML('beforeend', widgetHTML);
    }
    
    toggle() {
        this.isOpen = !this.isOpen;
        const chatBox = document.getElementById('chatWidgetBox');
        
        if (this.isOpen) {
            chatBox.classList.add('active');
            this.resetUnreadCount();
            this.scrollToBottom();
            document.getElementById('chatInputField').focus();
        } else {
            chatBox.classList.remove('active');
        }
    }
    
    close() {
        this.isOpen = false;
        document.getElementById('chatWidgetBox').classList.remove('active');
    }
    
    loadInitialMessages() {
        // Load messages dari server
        if (window.currentChats && window.currentChats.length > 0) {
            window.currentChats.forEach(chat => {
                this.addMessage(chat.u, chat.m, chat.isAdm, true);
            });
        }
        
        // Tambah welcome message
        this.addSystemMessage('Selamat datang di Live Chat! 👋');
        this.updateOnlineCount();
    }
    
    addMessage(username, message, isAdmin = false, skipServer = false) {
        const time = this.formatTime(new Date());
        const avatar = this.getInitials(username);
        const messageClass = isAdmin ? 'admin' : 'user';
        
        const messageHTML = `
            <div class="chat-message">
                <div class="chat-message-header">
                    <div class="chat-message-avatar ${messageClass}">${avatar}</div>
                    <span class="chat-message-name ${messageClass}">${this.escapeHtml(username)}</span>
                    <span class="chat-message-time">${time}</span>
                </div>
                <div class="chat-message-bubble">${this.escapeHtml(message)}</div>
            </div>
        `;
        
        document.getElementById('chatMessages').insertAdjacentHTML('beforeend', messageHTML);
        this.scrollToBottom();
        
        // Tampilkan notifikasi jika chat tertutup
        if (!this.isOpen && !skipServer) {
            this.showToast(username, message, isAdmin);
            this.incrementUnreadCount();
        }
        
        // Simpan ke server jika bukan dari server
        if (!skipServer && !isAdmin) {
            this.sendToServer(username, message);
        }
    }
    
    addSystemMessage(message) {
        const messageHTML = `
            <div class="chat-system-message">
                <i class="fas fa-info-circle"></i> ${this.escapeHtml(message)}
            </div>
        `;
        document.getElementById('chatMessages').insertAdjacentHTML('beforeend', messageHTML);
        this.scrollToBottom();
    }
    
    sendMessage() {
        const input = document.getElementById('chatInputField');
        const message = input.value.trim();
        
        if (message === '') return;
        
        this.addMessage(this.username, message, false);
        input.value = '';
        
        // Simulasi balasan admin (fake chat)
        if (Math.random() > 0.5) {
            setTimeout(() => {
                this.showTypingIndicator('Admin');
                setTimeout(() => {
                    this.hideTypingIndicator();
                    this.addFakeAdminReply();
                }, 2000);
            }, 1000);
        }
    }
    
    handleKeyPress(event) {
        if (event.key === 'Enter') {
            this.sendMessage();
        }
    }
    
    sendToServer(username, message) {
        $.ajax({
            url: 'ajax/send-chat.php',
            method: 'POST',
            data: { username: username, message: message },
            dataType: 'json'
        });
    }
    
    // Fake Message Generator untuk kesan ramai
    startFakeMessageGenerator() {
        const fakeUsernames = [
            'Player88', 'LuckyUser', 'Winner777', 'GamerPro', 'JackpotHunter',
            'SpinMaster', 'BonusKing', 'MegaWin', 'SlotLover', 'BigWinner',
            'SuperPlayer', 'ProGamer99', 'LuckyDay', 'WinStreak', 'GoldRush'
        ];
        
        const fakeMessages = [
            'Mantap hadiahnya! 🎉',
            'Gacor banget nih!',
            'Alhamdulillah menang',
            'Coba lagi ah',
            'Semoga hoki hari ini',
            'Jackpot dong 💰',
            'Keren banget eventnya',
            'Ayo semangat!',
            'Lumayan dapat bonus',
            'Terima kasih min 🙏',
            'Kapan ada event lagi?',
            'Seru banget spinnya',
            'Recommended!',
            'Legal ini?',
            'Cara claimnya gimana?'
        ];
        
        setInterval(() => {
            // Random chance untuk mengirim fake message (30% setiap 10 detik)
            if (Math.random() < 0.3) {
                const randomUser = fakeUsernames[Math.floor(Math.random() * fakeUsernames.length)];
                const randomMsg = fakeMessages[Math.floor(Math.random() * fakeMessages.length)];
                this.addMessage(randomUser, randomMsg, false, true);
            }
        }, 10000); // Setiap 10 detik
    }
    
    addFakeAdminReply() {
        const adminReplies = [
            'Selamat ya! Semoga beruntung terus 🎉',
            'Terima kasih sudah berpartisipasi!',
            'Jangan lupa claim hadiahnya ya',
            'Silakan hubungi CS untuk info lebih lanjut',
            'Semoga hoki terus! 🍀',
            'Mantap! Terus pantau event kami ya',
            'Terima kasih supportnya!',
            'Sukses selalu! 💪'
        ];
        
        const reply = adminReplies[Math.floor(Math.random() * adminReplies.length)];
        this.addMessage('Admin', reply, true, true);
    }
    
    showTypingIndicator(username) {
        document.getElementById('typingUser').textContent = username;
        document.getElementById('typingIndicator').classList.add('active');
        this.scrollToBottom();
    }
    
    hideTypingIndicator() {
        document.getElementById('typingIndicator').classList.remove('active');
    }
    
    showToast(username, message, isAdmin) {
        const toast = document.getElementById('chatToast');
        const avatar = this.getInitials(username);
        
        document.getElementById('toastAvatar').textContent = avatar;
        document.getElementById('toastName').textContent = username;
        document.getElementById('toastMessage').textContent = message.substring(0, 50) + (message.length > 50 ? '...' : '');
        
        toast.classList.add('active');
        
        setTimeout(() => {
            toast.classList.remove('active');
        }, 4000);
    }
    
    incrementUnreadCount() {
        this.unreadCount++;
        const badge = document.getElementById('chatNotifBadge');
        badge.textContent = this.unreadCount;
        badge.style.display = 'flex';
    }
    
    resetUnreadCount() {
        this.unreadCount = 0;
        document.getElementById('chatNotifBadge').style.display = 'none';
    }
    
    updateOnlineCount() {
        // Simulasi jumlah online (random 15-5000)
        const count = Math.floor(Math.random() * 3500) + 1500;
        document.getElementById('onlineCount').textContent = count;
    }
    
    scrollToBottom() {
        const messagesDiv = document.getElementById('chatMessages');
        setTimeout(() => {
            messagesDiv.scrollTop = messagesDiv.scrollHeight;
        }, 100);
    }
    
    startPolling() {
        // Poll new messages setiap 5 detik
        setInterval(() => {
            $.getJSON('ajax/get-chats.php', (data) => {
                if (data.chats && data.chats.length > this.messages.length) {
                    // Ada pesan baru
                    const newMessages = data.chats.slice(this.messages.length);
                    newMessages.forEach(chat => {
                        this.addMessage(chat.u, chat.m, chat.isAdm, true);
                    });
                    this.messages = data.chats;
                }
            });
            
            // Update online count
            this.updateOnlineCount();
        }, 5000);
    }
    
    // Helper Functions
    generateRandomUsername() {
        const prefixes = ['Player', 'User', 'Guest', 'Lucky', 'Winner'];
        const prefix = prefixes[Math.floor(Math.random() * prefixes.length)];
        const number = Math.floor(Math.random() * 9999);
        return `${prefix}${number}`;
    }
    
    getInitials(name) {
        return name.substring(0, 2).toUpperCase();
    }
    
    formatTime(date) {
        const hours = date.getHours().toString().padStart(2, '0');
        const minutes = date.getMinutes().toString().padStart(2, '0');
        return `${hours}:${minutes}`;
    }
    
    escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }
}

// Initialize Live Chat
let liveChat;
document.addEventListener('DOMContentLoaded', () => {
    liveChat = new LiveChatWidget();
});