document.addEventListener('DOMContentLoaded', () => {
    let currentFolder = 'inbox';
    let selectedMessages = new Set();
    let currentView = 'list';
    let currentMessageUid = null;

    const views = {
        list: document.getElementById('mail-list-view'),
        detail: document.getElementById('mail-detail-view'),
        compose: document.getElementById('compose-view')
    };

    function showView(viewName) {
        currentView = viewName;
        Object.keys(views).forEach(key => {
            views[key].classList.toggle('hidden', key !== viewName);
        });
    }

    async function loadMessages(folder = 'inbox', page = 1) {
        try {
            const response = await fetch(`inbox/fetch_messages.php?folder=${folder}&page=${page}`);
            const data = await response.json();
            
            if (!data.success) throw new Error(data.error);
            
            const container = document.getElementById('mails-container');
            container.innerHTML = data.messages.map(message => `
                <div class="mail-item p-4 border-b border-gray-200 dark:border-gray-700 cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors ${message.seen ? '' : 'font-bold bg-gray-50 dark:bg-gray-700'}"
                     data-uid="${message.uid}">
                    <div class="flex items-center">
                        <input type="checkbox" class="message-select mr-4" data-uid="${message.uid}">
                        <div class="flex-1">
                            <div class="flex justify-between items-start">
                                <span class="text-sm">${message.from}</span>
                                <span class="text-xs text-gray-500">${message.date}</span>
                            </div>
                            <div class="mt-1">
                                <h3 class="text-base">${message.subject}</h3>
                                <p class="text-sm text-gray-600 dark:text-gray-400 truncate">
                                    ${message.preview || 'No preview available'}
                                </p>
                            </div>
                            ${message.hasAttachments ? '<i class="fas fa-paperclip text-gray-400 mt-2"></i>' : ''}
                        </div>
                    </div>
                </div>
            `).join('');

            updateMessageCount(data.pagination.total);
            attachMessageListeners();
            
        } catch (error) {
            showNotification(error.message, 'error');
        }
    }

    async function loadMessageDetail(uid) {
        try {
            const response = await fetch(`inbox/get_message.php?uid=${uid}`);
            const data = await response.json();
            
            if (!data.success) throw new Error(data.error);
            
            currentMessageUid = uid;
            const content = document.getElementById('mail-detail-content');
            content.innerHTML = `
                <div class="mb-6">
                    <h2 class="text-2xl font-medium mb-4">${data.message.subject}</h2>
                    <div class="flex justify-between items-start text-sm text-gray-600 dark:text-gray-400">
                        <div>
                            <p><strong>From:</strong> ${data.message.from}</p>
                            <p><strong>To:</strong> ${data.message.to}</p>
                            ${data.message.cc ? `<p><strong>CC:</strong> ${data.message.cc}</p>` : ''}
                        </div>
                        <p>${data.message.date}</p>
                    </div>
                </div>
                ${data.message.attachments.length > 0 ? `
                    <div class="mb-6 p-4 bg-gray-50 dark:bg-gray-700 rounded-lg">
                        <h3 class="text-sm font-medium mb-2">Attachments</h3>
                        <div class="flex flex-wrap gap-2">
                            ${data.message.attachments.map(att => `
                                <a href="inbox/attachments.php?uid=${uid}&part=${att.part}" 
                                   class="flex items-center p-2 bg-white dark:bg-gray-600 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-500 transition-colors">
                                    <i class="fas fa-paperclip mr-2"></i>
                                    <span class="text-sm">${att.name}</span>
                                </a>
                            `).join('')}
                        </div>
                    </div>
                ` : ''}
                <div class="prose dark:prose-invert max-w-none">
                    ${data.message.body}
                </div>
            `;
            
            showView('detail');
            markAsRead([uid]);
            
        } catch (error) {
            showNotification(error.message, 'error');
        }
    }

    function initializeCompose(type = 'new', originalMessage = null) {
        const composeView = views.compose;
        const subject = composeView.querySelector('input[placeholder="Subject"]');
        const to = composeView.querySelector('input[placeholder="To"]');
        const editor = composeView.querySelector('[contenteditable="true"]');
        
        subject.value = '';
        to.value = '';
        editor.innerHTML = '';
        
        if (type === 'reply' && originalMessage) {
            subject.value = `Re: ${originalMessage.subject}`;
            to.value = originalMessage.from;
            editor.innerHTML = `<br><br>On ${originalMessage.date}, ${originalMessage.from} wrote:<br><blockquote>${originalMessage.body}</blockquote>`;
        } else if (type === 'forward' && originalMessage) {
            subject.value = `Fwd: ${originalMessage.subject}`;
            editor.innerHTML = `<br><br>---------- Forwarded message ----------<br>
                From: ${originalMessage.from}<br>
                Date: ${originalMessage.date}<br>
                Subject: ${originalMessage.subject}<br>
                To: ${originalMessage.to}<br><br>
                ${originalMessage.body}`;
        }
        
        showView('compose');
    }

    async function sendMessage(draft = false) {
        try {
            const composeView = views.compose;
            const formData = new FormData();
            
            formData.append('to', composeView.querySelector('input[placeholder="To"]').value);
            formData.append('subject', composeView.querySelector('input[placeholder="Subject"]').value);
            formData.append('content', composeView.querySelector('[contenteditable="true"]').innerHTML);
            
            if (currentMessageUid) {
                formData.append('in_reply_to', currentMessageUid);
            }
            
            const response = await fetch(draft ? 'inbox/save_draft.php' : 'inbox/send_message.php', {
                method: 'POST',
                body: formData
            });
            
            const data = await response.json();
            if (!data.success) throw new Error(data.error);
            
            showNotification(draft ? 'Draft saved' : 'Message sent successfully', 'success');
            showView('list');
            loadMessages(currentFolder);
            
        } catch (error) {
            showNotification(error.message, 'error');
        }
    }

    function updateMessageCount(count) {
        const countElement = document.querySelector('.mail-count');
        if (countElement) {
            countElement.textContent = count;
        }
    }

    function attachMessageListeners() {
        document.querySelectorAll('.mail-item').forEach(item => {
            item.addEventListener('click', (e) => {
                if (!e.target.classList.contains('message-select')) {
                    loadMessageDetail(item.dataset.uid);
                }
            });
        });

        document.querySelectorAll('.message-select').forEach(checkbox => {
            checkbox.addEventListener('change', (e) => {
                const uid = e.target.dataset.uid;
                if (e.target.checked) {
                    selectedMessages.add(uid);
                } else {
                    selectedMessages.delete(uid);
                }
                updateBulkActions();
            });
        });
    }

    function updateBulkActions() {
        const actions = document.querySelectorAll('.bulk-action');
        const hasSelection = selectedMessages.size > 0;
        actions.forEach(action => {
            action.disabled = !hasSelection;
        });
    }

    function showNotification(message, type = 'success') {
        const notification = document.createElement('div');
        notification.className = `fixed top-4 right-4 p-4 rounded-lg shadow-lg z-50 ${
            type === 'success' ? 'bg-green-500' : 'bg-red-500'
        } text-white`;
        notification.textContent = message;
        document.body.appendChild(notification);
        setTimeout(() => notification.remove(), 3000);
    }

    // Event Listeners
    document.querySelectorAll('.mail-folder').forEach(folder => {
        folder.addEventListener('click', () => {
            currentFolder = folder.dataset.folder;
            loadMessages(currentFolder);
            document.querySelectorAll('.mail-folder').forEach(f => {
                f.classList.remove('bg-gray-200', 'dark:bg-gray-700');
            });
            folder.classList.add('bg-gray-200', 'dark:bg-gray-700');
        });
    });

    document.getElementById('compose-mail').addEventListener('click', () => {
        initializeCompose();
    });

    document.getElementById('back-to-list').addEventListener('click', () => {
        showView('list');
    });

    document.getElementById('close-compose').addEventListener('click', () => {
        if (confirm('Discard this message?')) {
            showView('list');
        }
    });

    document.getElementById('send-mail').addEventListener('click', () => {
        sendMessage();
    });

    document.getElementById('save-draft').addEventListener('click', () => {
        sendMessage(true);
    });

    document.getElementById('refresh-mails').addEventListener('click', () => {
        loadMessages(currentFolder);
    });

    // Initialize
    loadMessages();
    showView('list');
});