<script>
    function pollSidebar() {
        fetch('{{ route("conversations.sidebar") }}')
            .then(response => response.text())
            .then(html => {
                document.querySelector('.inbox-list .list-scroll').innerHTML = html;
                updateToolbarState();
            })
            .catch(err => console.error('Error polling sidebar:', err));
    }
    document.addEventListener("DOMContentLoaded", function() {
        setInterval(pollSidebar, 5000);
    });

    let selectedConversations = new Set();
    let lastSelectedId = null;
    let undoStack = [];
    let redoStack = [];

    function updateToolbarState() {
        const filters = document.getElementById('inbox-filters');
        const toolbar = document.getElementById('inbox-bulk-toolbar');
        const count = document.getElementById('bulk-count');
        
        if (!filters || !toolbar) return;
        
        if (selectedConversations.size > 0) {
            filters.style.display = 'none';
            toolbar.style.display = 'flex';
            count.innerText = selectedConversations.size;
        } else {
            filters.style.display = 'flex';
            toolbar.style.display = 'none';
        }
        
        document.querySelectorAll('.conversation-row').forEach(row => {
            const id = row.getAttribute('data-id');
            const checkbox = row.querySelector('.row-checkbox');
            const icon = checkbox ? checkbox.querySelector('.ph-check') : null;
            
            if (checkbox) {
                if (selectedConversations.has(id)) {
                    row.style.background = 'var(--surface-hover)';
                    checkbox.style.display = 'flex';
                    checkbox.style.background = 'var(--primary)';
                    checkbox.style.borderColor = 'var(--primary)';
                    icon.style.display = 'block';
                    icon.style.color = '#fff';
                } else {
                    row.style.background = '';
                    checkbox.style.display = 'none';
                    checkbox.style.background = 'var(--surface)';
                    checkbox.style.borderColor = 'var(--border)';
                    icon.style.display = 'none';
                }
            }
        });
    }
    
    document.querySelector('.list-scroll')?.addEventListener('click', function(e) {
        const row = e.target.closest('.conversation-row');
        if (!row) return;

        if (e.ctrlKey || e.metaKey || e.shiftKey) {
            e.preventDefault();
            const id = row.getAttribute('data-id');
            
            if (e.shiftKey && lastSelectedId) {
                const rows = Array.from(document.querySelectorAll('.conversation-row'));
                const startIdx = rows.findIndex(r => r.getAttribute('data-id') === lastSelectedId);
                const endIdx = rows.findIndex(r => r === row);
                
                const min = Math.min(startIdx, endIdx);
                const max = Math.max(startIdx, endIdx);
                
                for (let i = min; i <= max; i++) {
                    selectedConversations.add(rows[i].getAttribute('data-id'));
                }
            } else {
                if (selectedConversations.has(id)) {
                    selectedConversations.delete(id);
                } else {
                    selectedConversations.add(id);
                }
            }
            
            lastSelectedId = id;
            updateToolbarState();
        } else if (e.target.closest('.row-avatar-wrapper')) {
            // Toggle on avatar click
            e.preventDefault();
            const id = row.getAttribute('data-id');
            if (selectedConversations.has(id)) {
                selectedConversations.delete(id);
            } else {
                selectedConversations.add(id);
            }
            lastSelectedId = id;
            updateToolbarState();
        } else if (selectedConversations.size > 0) {
            // If we are in bulk mode, clicking the row also toggles
            e.preventDefault();
            const id = row.getAttribute('data-id');
            if (selectedConversations.has(id)) {
                selectedConversations.delete(id);
            } else {
                selectedConversations.add(id);
            }
            lastSelectedId = id;
            updateToolbarState();
        }
    });

    document.getElementById('bulk-clear')?.addEventListener('click', () => {
        selectedConversations.clear();
        lastSelectedId = null;
        updateToolbarState();
    });

    function performBulkAction(action, ids) {
        return fetch('{{ route("conversations.bulk") }}', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': '{{ csrf_token() }}'
            },
            body: JSON.stringify({ action, ids: Array.from(ids) })
        }).then(r => r.json()).then(data => {
            if(data.success) {
                // If on show page and affected active convo, redirect to index
                const pathParts = window.location.pathname.split('/');
                const currentId = pathParts[pathParts.length - 1];
                if (ids.includes(currentId)) {
                    window.location.href = '{{ route("conversations.index") }}';
                } else {
                    pollSidebar();
                }
            }
        });
    }
    
    function getOppositeAction(action) {
        switch(action) {
            case 'archive': return 'unarchive';
            case 'unarchive': return 'archive';
            case 'trash': return 'restore';
            case 'restore': return 'trash';
            default: return null;
        }
    }

    document.querySelectorAll('.bulk-action-btn').forEach(btn => {
        btn.addEventListener('click', function(e) {
            const action = this.getAttribute('data-action');
            if (action === 'forceDestroy') {
                confirmAction("Are you sure you want to permanently delete these items? This cannot be undone.", "Delete Forever", "Yes, delete forever", "No, cancel", () => {
                    const ids = Array.from(selectedConversations);
                    performBulkAction(action, ids).then(() => {
                        selectedConversations.clear();
                        lastSelectedId = null;
                        updateToolbarState();
                    });
                });
                return;
            }
            
            const ids = Array.from(selectedConversations);
            performBulkAction(action, ids).then(() => {
                if (action !== 'forceDestroy') {
                    undoStack.push({ action, ids });
                    redoStack = []; 
                }
                selectedConversations.clear();
                lastSelectedId = null;
                updateToolbarState();
            });
        });
    });

    document.addEventListener('keydown', function(e) {
        if (e.ctrlKey || e.metaKey) {
            if (e.key === 'z' || e.key === 'Z') {
                if(e.shiftKey) {
                    // Redo on Ctrl+Shift+Z
                    e.preventDefault();
                    if (redoStack.length > 0) {
                        const next = redoStack.pop();
                        performBulkAction(next.action, next.ids).then(() => {
                            undoStack.push(next);
                        });
                    }
                    return;
                }
                
                e.preventDefault();
                if (undoStack.length > 0) {
                    const last = undoStack.pop();
                    const undoAction = getOppositeAction(last.action);
                    if(undoAction) {
                        performBulkAction(undoAction, last.ids).then(() => {
                            redoStack.push(last);
                        });
                    }
                }
            } else if (e.key === 'y' || e.key === 'Y') {
                e.preventDefault();
                if (redoStack.length > 0) {
                    const next = redoStack.pop();
                    performBulkAction(next.action, next.ids).then(() => {
                        undoStack.push(next);
                    });
                }
            } else if (e.key === 'a' || e.key === 'A') {
                if(document.activeElement.tagName === 'INPUT' || document.activeElement.tagName === 'TEXTAREA') return;
                e.preventDefault();
                document.querySelectorAll('.conversation-row').forEach(row => {
                    selectedConversations.add(row.getAttribute('data-id'));
                });
                updateToolbarState();
            }
        }
    });

    // Close dropdown when clicking outside
    document.addEventListener('click', function(e) {
        const menu = document.getElementById('label-filter-menu');
        if (menu && menu.style.display === 'block' && !e.target.closest('.icon-button[title="Filter by Label"]') && !e.target.closest('#label-filter-menu')) {
            menu.style.display = 'none';
        }
    });
</script>
