/**
 * WhatsApp CRM Live Chat Engine
 */
const Chat = {
    currentConversationId: null,
    currentContact: null,
    inboxList: [],
    filterStatus: 'all',
    searchQuery: '',
    pollInterval: null,

    init() {
        this.refreshInbox();
        this.startPolling();

        // Check if conversation ID is in URL query (?conv_id=1)
        const urlParams = new URLSearchParams(window.location.search);
        const urlConvId = urlParams.get('conv_id');
        if (urlConvId) {
            setTimeout(() => this.selectConversation(parseInt(urlConvId)), 500);
        }
    },

    startPolling() {
        if (this.pollInterval) clearInterval(this.pollInterval);
        this.pollInterval = setInterval(() => {
            this.refreshInbox(true);
            if (this.currentConversationId) {
                this.refreshMessagesSilent(this.currentConversationId);
            }
        }, 3000);
    },

    async refreshInbox(isSilent = false) {
        try {
            const url = `/api/chat/inbox?status=${this.filterStatus}&search=${encodeURIComponent(this.searchQuery)}`;
            const res = await fetch(url, { headers: { 'X-Requested-With': 'XMLHttpRequest' } });
            const data = await res.json();

            if (data.success) {
                this.inboxList = data.data;
                this.renderInbox();
            }
        } catch (e) {
            if (!isSilent) console.error('Error fetching inbox:', e);
        }
    },

    renderInbox() {
        const container = document.getElementById('inbox-list');
        if (!container) return;

        if (this.inboxList.length === 0) {
            container.innerHTML = `
                <div class="p-8 text-center text-slate-500 text-xs">
                    <i class="fa-solid fa-inbox text-2xl mb-2 opacity-50"></i>
                    <p>No conversations found</p>
                </div>
            `;
            return;
        }

        let totalUnread = 0;
        let html = '';

        this.inboxList.forEach(conv => {
            totalUnread += (conv.unread_count || 0);
            const isSelected = (this.currentConversationId === conv.id);
            const initials = (conv.contact_name || 'WA').substring(0, 2).toUpperCase();
            const timeStr = this.formatTime(conv.last_message_at);

            html += `
                <div onclick="Chat.selectConversation(${conv.id})" 
                     class="p-3.5 flex items-start space-x-3 cursor-pointer transition ${isSelected ? 'bg-slate-800/90 border-l-4 border-emerald-500' : 'hover:bg-slate-800/40'}">
                    
                    <div class="w-11 h-11 rounded-2xl bg-gradient-to-tr from-emerald-600 to-teal-500 flex items-center justify-center font-bold text-white text-xs flex-shrink-0 shadow-md shadow-emerald-500/10">
                        ${initials}
                    </div>

                    <div class="flex-1 min-w-0">
                        <div class="flex items-center justify-between mb-1">
                            <h4 class="text-xs font-bold text-white truncate ${conv.unread_count > 0 ? 'text-emerald-400' : ''}">
                                ${this.escapeHtml(conv.contact_name)}
                            </h4>
                            <span class="text-[10px] text-slate-500">${timeStr}</span>
                        </div>
                        
                        <p class="text-xs text-slate-400 truncate ${conv.unread_count > 0 ? 'font-semibold text-slate-200' : ''}">
                            ${this.escapeHtml(conv.last_message || 'No messages yet')}
                        </p>

                        <div class="flex items-center justify-between mt-1.5">
                            <div class="flex items-center space-x-1.5 overflow-hidden">
                                ${conv.stage_name ? `<span class="text-[9px] px-1.5 py-0.5 rounded-md font-semibold text-white truncate" style="background-color: ${conv.stage_color || '#3b82f6'}">${this.escapeHtml(conv.stage_name)}</span>` : ''}
                                ${conv.assigned_agent_name ? `<span class="text-[9px] text-slate-400 truncate">👤 ${this.escapeHtml(conv.assigned_agent_name)}</span>` : ''}
                            </div>

                            ${conv.unread_count > 0 ? `
                                <span class="w-4 h-4 rounded-full bg-emerald-500 text-slate-950 font-bold text-[9px] flex items-center justify-center flex-shrink-0">
                                    ${conv.unread_count}
                                </span>
                            ` : ''}
                        </div>
                    </div>
                </div>
            `;
        });

        container.innerHTML = html;

        const badge = document.getElementById('unread-total-badge');
        if (badge) {
            if (totalUnread > 0) {
                badge.innerText = `${totalUnread} New`;
                badge.classList.remove('hidden');
            } else {
                badge.classList.add('hidden');
            }
        }
    },

    async selectConversation(id) {
        this.currentConversationId = id;
        this.renderInbox(); // update active styling

        document.getElementById('empty-chat-state').classList.add('hidden');
        document.getElementById('chat-header').classList.remove('hidden');
        document.getElementById('messages-container').classList.remove('hidden');
        document.getElementById('chat-composer').classList.remove('hidden');

        try {
            const res = await fetch(`/api/chat/conversation/${id}`, { headers: { 'X-Requested-With': 'XMLHttpRequest' } });
            const data = await res.json();

            if (data.success) {
                const { conversation, contact, messages, deals } = data.data;
                this.currentContact = contact;

                // Update Header
                document.getElementById('active-contact-name').innerText = contact.name || 'WhatsApp Contact';
                document.getElementById('active-contact-phone').innerText = contact.phone_number || '';
                document.getElementById('active-contact-avatar').innerText = (contact.name || 'WA').substring(0, 2).toUpperCase();
                
                const stageBadge = document.getElementById('active-contact-stage-badge');
                if (stageBadge && contact.stage_name) {
                    stageBadge.innerText = contact.stage_name;
                    stageBadge.style.backgroundColor = (contact.stage_color || '#3b82f6') + '33';
                    stageBadge.style.color = contact.stage_color || '#3b82f6';
                }

                document.getElementById('active-assigned-agent').value = conversation.assigned_user_id || '';
                document.getElementById('active-conv-status').value = conversation.status || 'open';

                // Update CRM Panel (Right Sidebar)
                this.updateCrmPanel(contact, deals);

                // Render Messages
                this.renderMessages(messages);
            }
        } catch (e) {
            console.error('Error loading conversation:', e);
        }
    },

    async refreshMessagesSilent(id) {
        try {
            const res = await fetch(`/api/chat/conversation/${id}`, { headers: { 'X-Requested-With': 'XMLHttpRequest' } });
            const data = await res.json();
            if (data.success) {
                this.renderMessages(data.data.messages, true);
            }
        } catch (e) {}
    },

    renderMessages(messages, isSilent = false) {
        const container = document.getElementById('messages-container');
        if (!container) return;

        let html = '';
        messages.forEach(msg => {
            const isOut = (msg.direction === 'outbound');
            const time = this.formatTime(msg.created_at);
            const statusTicks = this.renderStatusTicks(msg.status, isOut);

            html += `
                <div class="flex flex-col ${isOut ? 'items-end' : 'items-start'}">
                    <div class="max-w-[75%] rounded-2xl p-3.5 shadow-md ${isOut ? 'bg-emerald-600 text-white rounded-br-none' : 'bg-slate-900 border border-slate-800 text-slate-100 rounded-bl-none'}">
                        
                        ${msg.user_name && isOut ? `<div class="text-[10px] text-emerald-200/80 font-semibold mb-1">Sent by ${this.escapeHtml(msg.user_name)}</div>` : ''}

                        ${msg.media_url ? `
                            <div class="mb-2 rounded-xl overflow-hidden bg-black/20">
                                ${msg.message_type === 'image' ? `
                                    <a href="${msg.media_url}" target="_blank">
                                        <img src="${msg.media_url}" class="max-h-60 rounded-xl object-cover hover:opacity-90 transition">
                                    </a>
                                ` : `
                                    <a href="${msg.media_url}" target="_blank" class="flex items-center space-x-2 p-2.5 text-xs underline font-medium">
                                        <i class="fa-solid fa-file-arrow-down text-lg"></i>
                                        <span>Download Attachment</span>
                                    </a>
                                `}
                            </div>
                        ` : ''}

                        <div class="text-xs leading-relaxed whitespace-pre-wrap select-text">${this.escapeHtml(msg.content)}</div>

                        <div class="flex items-center justify-end space-x-1.5 mt-1.5 text-[10px] ${isOut ? 'text-emerald-200/70' : 'text-slate-500'}">
                            <span>${time}</span>
                            ${statusTicks}
                        </div>
                    </div>
                </div>
            `;
        });

        container.innerHTML = html;

        // Auto scroll to bottom unless user is scrolled up
        if (!isSilent || (container.scrollHeight - container.scrollTop <= container.clientHeight + 100)) {
            container.scrollTop = container.scrollHeight;
        }
    },

    renderStatusTicks(status, isOut) {
        if (!isOut) return '';
        if (status === 'read') {
            return `<i class="fa-solid fa-check-double text-blue-300" title="Read"></i>`;
        } else if (status === 'delivered') {
            return `<i class="fa-solid fa-check-double text-slate-300" title="Delivered"></i>`;
        } else if (status === 'sent') {
            return `<i class="fa-solid fa-check text-slate-300" title="Sent"></i>`;
        } else if (status === 'failed') {
            return `<i class="fa-solid fa-circle-exclamation text-red-300" title="Failed"></i>`;
        }
        return `<i class="fa-regular fa-clock text-slate-400" title="Pending"></i>`;
    },

    updateCrmPanel(contact, deals) {
        document.getElementById('crm-contact-id-badge').innerText = `#${contact.id}`;
        document.getElementById('crm-contact-avatar-large').innerText = (contact.name || 'WA').substring(0, 2).toUpperCase();
        document.getElementById('crm-contact-name').innerText = contact.name || 'WhatsApp User';
        document.getElementById('crm-contact-company').innerText = contact.company || contact.phone_number;
        document.getElementById('crm-contact-stage').value = contact.stage_id || 1;
        document.getElementById('crm-contact-notes').value = contact.notes || '';
        document.getElementById('deal-contact-id').value = contact.id;

        // Render Tags
        const tagsContainer = document.getElementById('crm-tags-list');
        if (tagsContainer) {
            tagsContainer.innerHTML = (contact.tags || []).map(t => `
                <span class="text-[10px] px-2 py-0.5 rounded-full font-semibold flex items-center space-x-1" style="background-color: ${t.color}25; color: ${t.color}; border: 1px solid ${t.color}40;">
                    <span>${this.escapeHtml(t.name)}</span>
                </span>
            `).join('') || '<span class="text-xs text-slate-500">No tags assigned</span>';
        }

        // Render Deals
        const dealsContainer = document.getElementById('crm-deals-list');
        if (dealsContainer) {
            dealsContainer.innerHTML = (deals || []).map(d => `
                <div class="p-2.5 bg-slate-950 border border-slate-800 rounded-xl space-y-1">
                    <div class="flex items-center justify-between text-xs font-semibold text-white">
                        <span>${this.escapeHtml(d.title)}</span>
                        <span class="text-emerald-400">$${parseFloat(d.value).toFixed(2)}</span>
                    </div>
                    <div class="text-[10px] text-slate-400 flex items-center justify-between">
                        <span class="px-1.5 py-0.5 rounded text-[9px]" style="background-color: ${d.stage_color || '#3b82f6'}30; color: ${d.stage_color || '#3b82f6'}">${this.escapeHtml(d.stage_name)}</span>
                        <span>${d.closing_date || 'No closing date'}</span>
                    </div>
                </div>
            `).join('') || '<p class="text-xs text-slate-500">No deals linked</p>';
        }
    },

    async handleSend(e) {
        if (e) e.preventDefault();
        const input = document.getElementById('message-input');
        const text = input.value.trim();
        if (!text || !this.currentConversationId) return;

        input.value = '';
        this.hideQuickReplyHint();

        try {
            const formData = new FormData();
            formData.append('conversation_id', this.currentConversationId);
            formData.append('message', text);
            formData.append('message_type', 'text');

            const res = await fetch('/api/chat/send', {
                method: 'POST',
                body: formData,
                headers: { 'X-Requested-With': 'XMLHttpRequest' }
            });
            const data = await res.json();

            if (data.success) {
                this.refreshMessagesSilent(this.currentConversationId);
                this.refreshInbox(true);
            } else {
                App.toast(data.error || 'Failed to send message', 'error');
            }
        } catch (err) {
            App.toast('Error sending message', 'error');
        }
    },

    handleKeyDown(e) {
        if (e.key === 'Enter' && !e.shiftKey) {
            e.preventDefault();
            this.handleSend();
        }
    },

    handleInputTyping(textarea) {
        const val = textarea.value;
        if (val.startsWith('/')) {
            document.getElementById('quick-reply-hint-box').classList.remove('hidden');
        } else {
            this.hideQuickReplyHint();
        }
    },

    hideQuickReplyHint() {
        const box = document.getElementById('quick-reply-hint-box');
        if (box) box.classList.add('hidden');
    },

    insertQuickReply(text) {
        const input = document.getElementById('message-input');
        let processed = text;
        if (this.currentContact) {
            processed = processed.replace('{{name}}', this.currentContact.name || 'there');
        }
        input.value = processed;
        this.hideQuickReplyHint();
        input.focus();
    },

    async handleFileUpload(e) {
        const file = e.target.files[0];
        if (!file || !this.currentConversationId) return;

        const formData = new FormData();
        formData.append('file', file);

        App.toast('Uploading media...', 'info');

        try {
            const res = await fetch('/api/chat/upload', {
                method: 'POST',
                body: formData,
                headers: { 'X-Requested-With': 'XMLHttpRequest' }
            });
            const data = await res.json();

            if (data.success) {
                const mediaUrl = data.data.url;
                const isImage = file.type.startsWith('image/');
                const msgType = isImage ? 'image' : 'document';

                const sendFormData = new FormData();
                sendFormData.append('conversation_id', this.currentConversationId);
                sendFormData.append('message', '');
                sendFormData.append('message_type', msgType);
                sendFormData.append('media_url', mediaUrl);

                await fetch('/api/chat/send', {
                    method: 'POST',
                    body: sendFormData,
                    headers: { 'X-Requested-With': 'XMLHttpRequest' }
                });

                App.toast('Attachment sent!', 'success');
                this.refreshMessagesSilent(this.currentConversationId);
                this.refreshInbox(true);
            }
        } catch (err) {
            App.toast('Upload failed', 'error');
        }
    },

    async sendTemplateDirect(templateName, language) {
        if (!this.currentConversationId) return;

        try {
            const formData = new FormData();
            formData.append('conversation_id', this.currentConversationId);
            formData.append('template_name', templateName);
            formData.append('language', language || 'en_US');

            const res = await fetch('/api/chat/send-template', {
                method: 'POST',
                body: formData,
                headers: { 'X-Requested-With': 'XMLHttpRequest' }
            });
            const data = await res.json();

            if (data.success) {
                App.toast(`Template ${templateName} sent!`, 'success');
                this.closeModal('templates-modal');
                this.refreshMessagesSilent(this.currentConversationId);
                this.refreshInbox(true);
            }
        } catch (err) {
            App.toast('Failed to send template', 'error');
        }
    },

    async assignCurrentAgent(agentId) {
        if (!this.currentConversationId) return;
        const formData = new FormData();
        formData.append('conversation_id', this.currentConversationId);
        formData.append('agent_id', agentId);

        await fetch('/api/chat/assign', { method: 'POST', body: formData, headers: { 'X-Requested-With': 'XMLHttpRequest' } });
        App.toast('Agent assigned', 'success');
        this.refreshInbox(true);
    },

    async changeCurrentStatus(status) {
        if (!this.currentConversationId) return;
        const formData = new FormData();
        formData.append('conversation_id', this.currentConversationId);
        formData.append('status', status);

        await fetch('/api/chat/status', { method: 'POST', body: formData, headers: { 'X-Requested-With': 'XMLHttpRequest' } });
        App.toast(`Chat marked as ${status}`, 'success');
        this.refreshInbox(true);
    },

    async updateContactStage(stageId) {
        if (!this.currentContact) return;
        const formData = new FormData();
        formData.append('stage_id', stageId);

        await fetch(`/api/contacts/${this.currentContact.id}/update`, { method: 'POST', body: formData, headers: { 'X-Requested-With': 'XMLHttpRequest' } });
        App.toast('Contact stage updated', 'success');
        this.refreshInbox(true);
    },

    async addTagToCurrentContact() {
        const select = document.getElementById('add-tag-select');
        const tagId = select.value;
        if (!tagId || !this.currentContact) return;

        const currentTags = (this.currentContact.tags || []).map(t => t.id);
        if (!currentTags.includes(parseInt(tagId))) {
            currentTags.push(parseInt(tagId));
        }

        const formData = new FormData();
        currentTags.forEach(id => formData.append('tag_ids[]', id));

        await fetch(`/api/contacts/${this.currentContact.id}/update`, { method: 'POST', body: formData, headers: { 'X-Requested-With': 'XMLHttpRequest' } });
        select.value = '';
        App.toast('Tag added', 'success');
        this.selectConversation(this.currentConversationId);
    },

    async saveNotes() {
        if (!this.currentContact) return;
        const notes = document.getElementById('crm-contact-notes').value;

        const formData = new FormData();
        formData.append('notes', notes);

        await fetch(`/api/contacts/${this.currentContact.id}/update`, { method: 'POST', body: formData, headers: { 'X-Requested-With': 'XMLHttpRequest' } });
        App.toast('Notes saved', 'success');
    },

    async submitNewDeal(e) {
        e.preventDefault();
        const formData = new FormData(e.target);

        const res = await fetch('/api/deals/create', { method: 'POST', body: formData, headers: { 'X-Requested-With': 'XMLHttpRequest' } });
        const data = await res.json();

        if (data.success) {
            App.toast('Deal created!', 'success');
            this.closeModal('create-deal-modal');
            this.selectConversation(this.currentConversationId);
        }
    },

    setFilterStatus(status) {
        this.filterStatus = status;
        ['all', 'unread', 'open', 'resolved'].forEach(tab => {
            const btn = document.getElementById(`tab-${tab}`);
            if (btn) {
                if (tab === status) {
                    btn.className = 'flex-1 py-1.5 rounded-lg text-center transition bg-emerald-500/20 text-emerald-400';
                } else {
                    btn.className = 'flex-1 py-1.5 rounded-lg text-center transition text-slate-400 hover:text-slate-200';
                }
            }
        });
        this.refreshInbox();
    },

    filterConversations(query) {
        this.searchQuery = query;
        this.refreshInbox();
    },

    toggleDetailsPanel() {
        const panel = document.getElementById('contact-crm-panel');
        if (panel) panel.classList.toggle('hidden');
    },

    openQuickRepliesModal() { document.getElementById('quick-replies-modal').classList.remove('hidden'); },
    openTemplatesModal() { document.getElementById('templates-modal').classList.remove('hidden'); },
    openCreateDealModal() { document.getElementById('create-deal-modal').classList.remove('hidden'); },
    closeModal(id) { document.getElementById(id).classList.add('hidden'); },

    selectQuickReply(text) {
        this.insertQuickReply(text);
        this.closeModal('quick-replies-modal');
    },

    formatTime(dateStr) {
        if (!dateStr) return '';
        const d = new Date(dateStr.replace(' ', 'T'));
        return d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
    },

    escapeHtml(str) {
        if (!str) return '';
        return String(str)
            .replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&#039;');
    }
};

document.addEventListener('DOMContentLoaded', () => {
    Chat.init();
});
