document.addEventListener('DOMContentLoaded', () => {
    // Global variables
    let selectedTicketId = null;
    let ticketsUpdateInterval = null;

    // DOM Elements
    const searchInput = document.getElementById('global-search');
    const userCards = document.querySelectorAll('.user-card');
    const documentItems = document.querySelectorAll('.document-item');
    const usersCount = document.getElementById('users-count');
    const documentsCount = document.getElementById('documents-count');
    const userModal = document.getElementById('user-modal');
    const profileModal = document.getElementById('profile-modal');
    const closeButtons = document.querySelectorAll('.close-modal, #close-modal');
    const tabs = document.querySelectorAll('[data-tab]');
    const contents = document.querySelectorAll('.tab-content');
    const themeToggle = document.getElementById('theme-toggle');
    const addUserBtn = document.getElementById('add-user-btn');

    // Initialize theme based on localStorage or system preference
    function initTheme() {
        if (localStorage.theme === 'dark' || (!('theme' in localStorage) && window.matchMedia('(prefers-color-scheme: dark)').matches)) {
            document.documentElement.classList.add('dark');
        } else {
            document.documentElement.classList.remove('dark');
        }
    }

    // Theme toggle handler
    themeToggle.addEventListener('click', () => {
        document.documentElement.classList.toggle('dark');
        localStorage.theme = document.documentElement.classList.contains('dark') ? 'dark' : 'light';
    });

    // Update counts for users and documents
    function updateCounts() {
        const visibleUsers = document.querySelectorAll('.user-card:not(.hidden)').length;
        const visibleDocs = document.querySelectorAll('.document-item:not(.hidden)').length;
        
        if (usersCount) {
            usersCount.textContent = `Showing ${visibleUsers} user${visibleUsers !== 1 ? 's' : ''}`;
        }
        
        if (documentsCount) {
            documentsCount.textContent = `Showing ${visibleDocs} document${visibleDocs !== 1 ? 's' : ''}`;
        }
    }

    // Highlight search text in elements
    function highlightText(element, searchText) {
        if (!element) return;
        
        const originalText = element.textContent;
        if (searchText && originalText.toLowerCase().includes(searchText.toLowerCase())) {
            const regex = new RegExp(`(${searchText.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')})`, 'gi');
            element.innerHTML = originalText.replace(regex, '<mark class="search-highlight">$1</mark>');
        } else {
            element.textContent = originalText;
        }
    }

    // Load websites monitoring status
    function loadSites() {
        const sitesList = document.getElementById('sites-list');
        if (!sitesList) return;
        
        sitesList.innerHTML = `
            <div class="flex justify-center items-center p-8">
                <div class="animate-spin rounded-full h-8 w-8 border-2 border-gray-500 border-t-black dark:border-t-white"></div>
            </div>
        `;

        fetch('check_sites.php')
            .then(response => response.json())
            .then(data => {
                sitesList.innerHTML = '';
                if (data && data.results) {
                    data.results.forEach(site => {
                        const div = document.createElement('div');
                        div.className = 'flex items-center justify-between p-4 bg-white dark:bg-gray-900 rounded-lg fade-in';
                        
                        const statusClass = site.status ? 'text-green-500' : 'text-red-500';
                        const statusIcon = site.status ? 'fa-check-circle' : 'fa-exclamation-circle';
                        const statusIndicator = site.status ? 'status-online' : 'status-offline';
                        
                        div.innerHTML = `
                            <div class="flex items-center space-x-3">
                                <i class="fas fa-globe text-gray-500 dark:text-gray-400"></i>
                                <a href="${site.url}" target="_blank" class="hover:underline">${site.url}</a>
                            </div>
                            <div class="flex items-center space-x-4">
                                <div class="flex items-center space-x-1 ${statusClass}">
                                    <span class="status-indicator ${statusIndicator}"></span>
                                    <i class="fas ${statusIcon}"></i>
                                    <span>${site.status ? 'Online' : 'Offline'}</span>
                                </div>
                                <span class="text-xs text-gray-500 dark:text-gray-400">
                                    <i class="far fa-clock mr-1"></i>${site.timestamp || ''}
                                </span>
                            </div>
                        `;
                        
                        sitesList.appendChild(div);
                    });
                }
            })
            .catch(error => {
                console.error('Error:', error);
                sitesList.innerHTML = `
                    <div class="bg-red-100 dark:bg-red-900 border-l-4 border-red-500 text-red-700 dark:text-red-300 p-4 rounded">
                        <div class="flex items-center space-x-2">
                            <i class="fas fa-exclamation-circle"></i>
                            <span>Unable to load sites. Please try again later.</span>
                        </div>
                    </div>
                `;
            });
    }

    // Search functionality
    if (searchInput) {
        searchInput.addEventListener('input', (e) => {
            const searchText = e.target.value.toLowerCase();

            userCards.forEach(card => {
                const searchableText = card.dataset.searchable.toLowerCase();
                const visible = searchableText.includes(searchText);
                card.classList.toggle('hidden', !visible);

                if (visible) {
                    card.querySelectorAll('.username, .email, .note, .roleimators').forEach(element => {
                        highlightText(element, searchText);
                    });
                }
            });

            documentItems.forEach(item => {
                const searchableText = item.dataset.searchable.toLowerCase();
                const visible = searchableText.includes(searchText);
                item.classList.toggle('hidden', !visible);

                if (visible) {
                    highlightText(item.querySelector('.document-name'), searchText);
                }
            });

            updateCounts();
        });
    }

    // Tab navigation
    tabs.forEach(tab => {
        tab.addEventListener('click', () => {
            tabs.forEach(t => {
                t.classList.remove('border-black', 'dark:border-white', 'active');
                t.classList.add('border-transparent');
            });
            
            tab.classList.remove('border-transparent');
            tab.classList.add('border-black', 'dark:border-white', 'active');
            
            contents.forEach(content => content.classList.add('hidden'));
            document.getElementById(`${tab.dataset.tab}-content`).classList.remove('hidden');

            if (tab.dataset.tab === 'sites') {
                loadSites();
            }
            
            if (tab.dataset.tab === 'tickets') {
                loadTickets();
                setupTicketsRefresh();
            } else {
                clearInterval(ticketsUpdateInterval);
            }
        });
    });

    // User card click handler - open edit modal
    userCards.forEach(card => {
        card.addEventListener('click', () => {
            userModal.classList.remove('hidden');
            document.getElementById('user-modal-title').innerHTML = `
                <i class="fas fa-user-edit text-gray-600 dark:text-gray-400"></i>
                <span>Edit User</span>
            `;
            document.getElementById('user-id').value = card.dataset.userId;
            document.getElementById('email').value = card.dataset.email;
            document.getElementById('username').value = card.dataset.username;
            document.getElementById('note').value = card.dataset.note;
            document.getElementById('role').value = card.dataset.role || "0";
            document.getElementById('roleimators').value = card.dataset.roleimators || "";
            
            // Show delete button for edit mode
            document.getElementById('delete-user-btn').classList.remove('hidden');
        });
    });

    // Add user button handler
    if (addUserBtn) {
        addUserBtn.addEventListener('click', () => {
            userModal.classList.remove('hidden');
            document.getElementById('user-modal-title').innerHTML = `
                <i class="fas fa-user-plus text-gray-600 dark:text-gray-400"></i>
                <span>Add New User</span>
            `;
            document.getElementById('edit-user-form').reset();
            document.getElementById('user-id').value = '';
            
            // Hide delete button for add mode
            document.getElementById('delete-user-btn').classList.add('hidden');
        });
    }

    // Close modal buttons
    closeButtons.forEach(button => {
        button.addEventListener('click', () => {
            userModal.classList.add('hidden');
            profileModal.classList.add('hidden');
        });
    });

    // User edit/add form submission
    document.getElementById('edit-user-form').addEventListener('submit', async (e) => {
        e.preventDefault();
        const form = e.target;
        const submitButton = form.querySelector('button[type="submit"]');
        const originalContent = submitButton.innerHTML;
        const isNewUser = !document.getElementById('user-id').value;
        
        showLoadingOverlay();
        submitButton.disabled = true;
        submitButton.innerHTML = `
            <div class="flex items-center space-x-2">
                <div class="animate-spin rounded-full h-4 w-4 border-2 border-gray-500 border-t-white"></div>
                <span>${isNewUser ? 'Creating...' : 'Saving...'}</span>
            </div>
        `;

        try {
            const formData = new FormData(form);
            const response = await fetch(isNewUser ? 'add_user.php' : 'update_user.php', {
                method: 'POST',
                body: formData
            });
            
            const result = await response.json();
            if(result.success) {
                userModal.classList.add('hidden');
                showNotification(`User ${isNewUser ? 'created' : 'updated'} successfully!`, 'success');
                setTimeout(() => {
                    window.location.href = '?success=1';
                }, 1000);
            } else {
                throw new Error(result.message || `Failed to ${isNewUser ? 'create' : 'update'} user`);
            }
        } catch(error) {
            console.error('Error:', error);
            showNotification(error.message, 'error');
        } finally {
            hideLoadingOverlay();
            submitButton.disabled = false;
            submitButton.innerHTML = originalContent;
        }
    });

    // Delete user button handler
    document.getElementById('delete-user-btn').addEventListener('click', async () => {
        if (confirm('Are you sure you want to delete this user? This action cannot be undone.')) {
            const userId = document.getElementById('user-id').value;
            const button = document.getElementById('delete-user-btn');
            const originalContent = button.innerHTML;
            
            showLoadingOverlay();
            button.disabled = true;
            button.innerHTML = `
                <div class="flex items-center space-x-2">
                    <div class="animate-spin rounded-full h-4 w-4 border-2 border-gray-500 border-t-white"></div>
                    <span>Deleting...</span>
                </div>
            `;

            try {
                const response = await fetch('delete_user.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: `user_id=${userId}`
                });
                
                const result = await response.json();
                if(result.success) {
                    userModal.classList.add('hidden');
                    showNotification('User deleted successfully!', 'success');
                    setTimeout(() => {
                        window.location.href = '?success=1';
                    }, 1000);
                } else {
                    throw new Error(result.message || 'Delete failed');
                }
            } catch(error) {
                console.error('Error:', error);
                showNotification(error.message, 'error');
            } finally {
                hideLoadingOverlay();
                button.disabled = false;
                button.innerHTML = originalContent;
            }
        }
    });

    // Check email server status
    async function checkEmailServer() {
        const statusDiv = document.getElementById('email-server-status');
        if (!statusDiv) return;
        
        try {
            const response = await fetch('check_email_server.php');
            const data = await response.json();
            
            if (data.success) {
                statusDiv.innerHTML = `
                    <div class="flex items-center space-x-2 text-green-500">
                        <i class="fas fa-check-circle"></i>
                        <span>${data.message}</span>
                    </div>
                `;
            } else {
                throw new Error(data.message);
            }
        } catch (error) {
            statusDiv.innerHTML = `
                <div class="flex items-center space-x-2 text-red-500">
                    <i class="fas fa-exclamation-circle"></i>
                    <span>Email server error: ${error.message}</span>
                </div>
            `;
        }
    }

    // Email editor functionality
    const editor = document.getElementById('email-editor');
    const formatButtons = document.querySelectorAll('[data-format]');
    
    if (editor && formatButtons) {
        formatButtons.forEach(button => {
            button.addEventListener('click', () => {
                const format = button.dataset.format;
                
                if (format === 'link') {
                    const url = prompt('Enter URL:');
                    if (url) {
                        document.execCommand('createLink', false, url);
                    }
                } else {
                    document.execCommand(format, false, null);
                }
                
                updatePreview();
            });
        });
    }

    // Update email preview
    function updatePreview() {
        const preview = document.getElementById('email-preview');
        const recipientSelect = document.getElementById('email-recipient');
        if (!preview || !recipientSelect || !editor) return;
        
        const selectedOption = recipientSelect.options[recipientSelect.selectedIndex];
        const username = selectedOption ? selectedOption.dataset.username : '{username}';
        
        let content = editor.innerHTML;
        content = content.replace(/{username}/g, username);
        
        preview.innerHTML = `
            <div class="prose dark:prose-invert max-w-none">
                ${content}
            </div>
            <div class="mt-8 pt-6 border-t border-gray-200 dark:border-gray-700">
                <p class="text-sm text-gray-600 dark:text-gray-400 text-center">
                    This email was sent by an official Imators team member.<br>
                    © ${new Date().getFullYear()} Imators. All rights reserved.
                </p>
            </div>
        `;
    }

    // Email form submission
    const emailForm = document.getElementById('send-email-form');
    if (emailForm) {
        emailForm.addEventListener('submit', async (e) => {
            e.preventDefault();
            const submitButton = emailForm.querySelector('button[type="submit"]');
            const originalContent = submitButton.innerHTML;
            
            showLoadingOverlay();
            submitButton.disabled = true;
            submitButton.innerHTML = `
                <div class="flex items-center space-x-2">
                    <div class="animate-spin rounded-full h-4 w-4 border-2 border-gray-500 border-t-white"></div>
                    <span>Sending...</span>
                </div>
            `;

            try {
                const recipient = document.getElementById('email-recipient');
                const subject = document.getElementById('email-subject');
                const content = document.getElementById('email-editor');

                const formData = new FormData();
                formData.append('recipient_id', recipient.value);
                formData.append('subject', subject.value);
                formData.append('content', content.innerHTML);

                const response = await fetch('send_email.php', {
                    method: 'POST',
                    body: formData
                });

                const result = await response.json();
                if (result.success) {
                    emailForm.reset();
                    editor.innerHTML = '';
                    updatePreview();
                    showNotification('Email sent successfully!', 'success');
                } else {
                    throw new Error(result.error || 'Failed to send email');
                }
            } catch (error) {
                console.error('Error:', error);
                showNotification(error.message, 'error');
            } finally {
                hideLoadingOverlay();
                submitButton.disabled = false;
                submitButton.innerHTML = originalContent;
            }
        });
    }

    // Profile menu functionality
    const profileMenu = document.getElementById('profile-menu');
    const profileDropdown = document.getElementById('profile-dropdown');
    const profileMenuDesktop = document.getElementById('profile-menu-desktop');
    const profileDropdownDesktop = document.getElementById('profile-dropdown-desktop');
    const viewProfileBtns = document.querySelectorAll('#view-profile, #view-profile-desktop');

    function setupMenuToggle(menuBtn, dropdown) {
        if (menuBtn && dropdown) {
            menuBtn.addEventListener('click', (e) => {
                e.stopPropagation();
                dropdown.classList.toggle('hidden');
            });
        }
    }

    setupMenuToggle(profileMenu, profileDropdown);
    setupMenuToggle(profileMenuDesktop, profileDropdownDesktop);

    document.addEventListener('click', (e) => {
        if (profileMenu && profileDropdown && !profileMenu.contains(e.target)) {
            profileDropdown.classList.add('hidden');
        }
        if (profileMenuDesktop && profileDropdownDesktop && !profileMenuDesktop.contains(e.target)) {
            profileDropdownDesktop.classList.add('hidden');
        }
    });

    viewProfileBtns.forEach(btn => {
        if (btn && profileModal) {
            btn.addEventListener('click', (e) => {
                e.preventDefault();
                profileModal.classList.remove('hidden');
                profileModal.classList.add('flex');
                
                if (profileDropdown) profileDropdown.classList.add('hidden');
                if (profileDropdownDesktop) profileDropdownDesktop.classList.add('hidden');
            });
        }
    });

    if (profileModal) {
        const closeProfileModalBtns = document.querySelectorAll('.close-profile-modal');
        closeProfileModalBtns.forEach(btn => {
            btn.addEventListener('click', () => {
                profileModal.classList.add('hidden');
                profileModal.classList.remove('flex');
            });
        });

        profileModal.addEventListener('click', (e) => {
            if (e.target === profileModal) {
                profileModal.classList.add('hidden');
                profileModal.classList.remove('flex');
            }
        });
    }

    // Helper for showing notifications
    function showNotification(message, type = 'success') {
        const notification = document.createElement('div');
        notification.className = `fixed top-4 right-4 px-6 py-3 rounded-lg shadow-lg z-50 ${
            type === 'success' ? 'bg-green-500' : 'bg-red-500'
        } text-white fade-in`;
        
        notification.innerHTML = `
            <div class="flex items-center space-x-2">
                <i class="fas ${type === 'success' ? 'fa-check-circle' : 'fa-exclamation-circle'}"></i>
                <span>${message}</span>
            </div>
        `;
        
        document.body.appendChild(notification);
        setTimeout(() => {
            notification.style.opacity = '0';
            notification.style.transform = 'translateY(-10px)';
            notification.style.transition = 'opacity 0.3s, transform 0.3s';
            setTimeout(() => notification.remove(), 300);
        }, 3000);
    }

    // Loading overlay helpers
    function showLoadingOverlay() {
        const overlay = document.querySelector('.loading-overlay');
        if (overlay) {
            overlay.classList.remove('hidden');
        }
    }

    function hideLoadingOverlay() {
        const overlay = document.querySelector('.loading-overlay');
        if (overlay) {
            overlay.classList.add('hidden');
        }
    }

    // Tickets functionality
    function formatDate(dateString) {
        const options = { 
            year: 'numeric', 
            month: 'short', 
            day: 'numeric',
            hour: '2-digit', 
            minute: '2-digit'
        };
        return new Date(dateString).toLocaleDateString('fr-FR', options);
    }

    async function loadTickets() {
        try {
            const ticketsList = document.getElementById('tickets-list');
            if (!ticketsList) return;
            
            ticketsList.innerHTML = `
                <div class="flex justify-center items-center p-8">
                    <div class="animate-spin rounded-full h-8 w-8 border-2 border-gray-500 border-t-black dark:border-t-white"></div>
                </div>
            `;
            
            const response = await fetch('get_tickets.php');
            const tickets = await response.json();
            
            ticketsList.innerHTML = tickets.length ? '' : `
                <div class="p-4 text-center text-gray-500 dark:text-gray-400">
                    No tickets found
                </div>
            `;
            
            tickets.forEach(ticket => {
                const ticketItem = document.createElement('div');
                ticketItem.className = `ticket-item cursor-pointer p-4 border-b border-gray-200 dark:border-gray-700 
                            hover:bg-gray-200 dark:hover:bg-gray-700 transition-colors
                            ${selectedTicketId === ticket.id ? 'bg-gray-200 dark:bg-gray-700' : ''}`;
                ticketItem.dataset.ticketId = ticket.id;
                
                ticketItem.innerHTML = `
                    <div class="flex justify-between items-start">
                        <div class="flex-grow">
                            <h3 class="font-medium">${ticket.subject}</h3>
                            <p class="text-sm text-gray-600 dark:text-gray-400 mt-1">
                                ${(ticket.description || '').substring(0, 100)}...

                            </p>
                        </div>
                        <div class="flex flex-col items-end ml-4">
                            <span class="px-2 py-1 text-xs rounded-full text-white ${getStatusColor(ticket.status)}">
                                ${ticket.status}
                            </span>
                            ${ticket.taken_by ? `
                                <span class="mt-2 text-xs bg-blue-100 dark:bg-blue-900 text-blue-800 dark:text-blue-200 px-2 py-1 rounded-full">
                                    ${ticket.taken_by_username}
                                </span>
                            ` : ''}
                        </div>
                    </div>
                    <div class="mt-2 text-xs text-gray-500 flex items-center justify-between">
                        <div>
                            <i class="fas fa-user"></i>
                            User #${ticket.user_id} · ${formatDate(ticket.created_at)}
                        </div>
                        ${ticket.taken_at ? `
                            <div>
                                <i class="fas fa-clock"></i>
                                Taken ${formatDate(ticket.taken_at)}
                            </div>
                        ` : ''}
                    </div>
                `;
                
                ticketsList.appendChild(ticketItem);
                
                ticketItem.addEventListener('click', () => selectTicket(ticket.id));
            });
            
            if (selectedTicketId) {
                const selectedTicket = tickets.find(t => t.id === selectedTicketId);
                if (selectedTicket) {
                    updateConversationView(selectedTicket);
                }
            }
        } catch (error) {
            console.error('Error loading tickets:', error);
            showNotification('Failed to load tickets', 'error');
        }
    }

    function setupTicketsRefresh() {
        clearInterval(ticketsUpdateInterval);
        ticketsUpdateInterval = setInterval(loadTickets, 30000);
    }

    async function selectTicket(ticketId) {
        selectedTicketId = ticketId;
        
        document.querySelectorAll('.ticket-item').forEach(item => {
            item.classList.toggle('bg-gray-200', item.dataset.ticketId == ticketId);
            item.classList.toggle('dark:bg-gray-700', item.dataset.ticketId == ticketId);
        });

        try {
            const response = await fetch(`get_ticket.php?id=${ticketId}`);
            const ticket = await response.json();
            
            if (ticket && ticket.id) {
                updateConversationView(ticket);
            } else {
                throw new Error('Ticket not found');
            }
        } catch (error) {
            console.error('Error loading ticket:', error);
            showNotification('Failed to load ticket details', 'error');
        }
    }

    function updateConversationView(ticket) {
        const subject = document.getElementById('selected-ticket-subject');
        const ticketId = document.getElementById('selected-ticket-id');
        const messages = document.getElementById('conversation-messages');
        const status = document.getElementById('ticket-status');
        const replyInput = document.getElementById('reply-message');
        const sendButton = document.getElementById('send-reply');
        
        if (!subject || !ticketId || !messages || !status || !replyInput || !sendButton) return;

        subject.textContent = ticket.subject;
        ticketId.textContent = `Ticket #${ticket.id}`;
        status.value = ticket.status;
        status.classList.remove('hidden');
        replyInput.disabled = false;
        sendButton.disabled = false;

        messages.innerHTML = `
            <div class="bg-gray-200 dark:bg-gray-700 p-4 rounded-lg">
                <div class="flex items-center gap-2 mb-2">
                    <i class="fas fa-user"></i>
                    <span class="font-medium">${ticket.creator_username || `User #${ticket.user_id}`}</span>
                    <span class="text-xs text-gray-500">${formatDate(ticket.created_at)}</span>
                </div>
                <p>${ticket.description}</p>
            </div>
        `;
        
        if (ticket.responses && ticket.responses.length) {
            ticket.responses.forEach(response => {
                const messageDiv = document.createElement('div');
                messageDiv.className = `p-4 rounded-lg ${response.is_staff ? 
                    'bg-blue-100 dark:bg-blue-900 ml-8' : 
                    'bg-gray-200 dark:bg-gray-700 mr-8'}`;
                
                messageDiv.innerHTML = `
                    <div class="flex items-center gap-2 mb-2">
                        <i class="fas fa-user"></i>
                        <span class="font-medium">
                            ${response.is_staff ? (response.username || 'Staff') : (response.username || `User #${response.user_id}`)}
                        </span>
                        <span class="text-xs text-gray-500">
                            ${formatDate(response.created_at)}
                        </span>
                    </div>
                    <p>${response.response}</p>
                `;
                
                messages.appendChild(messageDiv);
            });
        }

        messages.scrollTop = messages.scrollHeight;
    }

    function getStatusColor(status) {
        const colors = {
            'open': 'bg-yellow-500',
            'in_progress': 'bg-blue-500',
            'resolved': 'bg-green-500',
            'closed': 'bg-gray-500'
        };
        return colors[status] || 'bg-gray-500';
    }

    // Setup ticket status change handler
    const ticketStatus = document.getElementById('ticket-status');
    if (ticketStatus) {
        ticketStatus.addEventListener('change', async (e) => {
            if (!selectedTicketId) return;

            try {
                showLoadingOverlay();
                
                const response = await fetch('update_ticket_status.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        ticketId: selectedTicketId,
                        status: e.target.value
                    })
                });

                const result = await response.json();
                
                if (!result.success) {
                    throw new Error(result.message || 'Failed to update status');
                }

                showNotification('Status updated successfully', 'success');
                loadTickets();
            } catch (error) {
                console.error('Error updating status:', error);
                showNotification(error.message || 'Failed to update status', 'error');
            } finally {
                hideLoadingOverlay();
            }
        });
    }

    // Setup ticket reply handler
    const replyMessage = document.getElementById('reply-message');
    const sendReply = document.getElementById('send-reply');
    
    if (replyMessage && sendReply) {
        replyMessage.addEventListener('keypress', (e) => {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                sendReply.click();
            }
        });

        sendReply.addEventListener('click', async () => {
            if (!selectedTicketId) return;

            const message = replyMessage.value.trim();
            if (!message) return;

            const originalContent = sendReply.innerHTML;
            replyMessage.disabled = true;
            sendReply.disabled = true;
            sendReply.innerHTML = `
                <div class="flex items-center space-x-2">
                    <div class="animate-spin rounded-full h-4 w-4 border-2 border-white border-t-transparent"></div>
                    <span>Sending...</span>
                </div>
            `;

            try {
                const response = await fetch('add_ticket_response.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        ticketId: selectedTicketId,
                        message: message,
                        isStaff: true
                    })
                });

                const result = await response.json();
                
                if (!result.success) {
                    throw new Error(result.message || 'Failed to send response');
                }

                // Add new message to conversation
                const messages = document.getElementById('conversation-messages');
                const messageDiv = document.createElement('div');
                messageDiv.className = 'p-4 rounded-lg bg-blue-100 dark:bg-blue-900 ml-8 fade-in';
                
                messageDiv.innerHTML = `
                    <div class="flex items-center gap-2 mb-2">
                        <i class="fas fa-user"></i>
                        <span class="font-medium">
                            ${result.response.username || 'Staff'}
                        </span>
                        <span class="text-xs text-gray-500">
                            ${formatDate(result.response.created_at)}
                        </span>
                    </div>
                    <p>${message}</p>
                `;
                
                messages.appendChild(messageDiv);
                messages.scrollTop = messages.scrollHeight;
                replyMessage.value = '';
                
                showNotification('Response sent successfully', 'success');
                
                // Refresh ticket list after a delay
                setTimeout(() => {
                    loadTickets();
                }, 1000);
            } catch (error) {
                console.error('Error:', error);
                showNotification(error.message || 'Failed to send response', 'error');
            } finally {
                replyMessage.disabled = false;
                sendReply.disabled = false;
                sendReply.innerHTML = originalContent;
            }
        });
    }

    // Initialize everything
    initTheme();
    updateCounts();
    checkEmailServer();
    
    if (document.getElementById('email-preview')) {
        updatePreview();
    }
    
    if (document.getElementById('refresh-preview')) {
        document.getElementById('refresh-preview').addEventListener('click', updatePreview);
    }
    
    if (document.getElementById('refresh-sites')) {
        document.getElementById('refresh-sites').addEventListener('click', loadSites);
    }
    
    if (document.getElementById('email-editor')) {
        document.getElementById('email-editor').addEventListener('input', updatePreview);
    }
    
    if (document.getElementById('email-recipient')) {
        document.getElementById('email-recipient').addEventListener('change', updatePreview);
    }
    
    // Setup initial tabs based on URL hash if present
    const hash = window.location.hash.substring(1);
    if (hash) {
        const tabToActivate = document.querySelector(`[data-tab="${hash}"]`);
        if (tabToActivate) {
            tabToActivate.click();
        }
    }
    
    // Update URL hash when tab changes
    tabs.forEach(tab => {
        tab.addEventListener('click', () => {
            window.location.hash = tab.dataset.tab;
        });
    });
});