$(document).ready(function() {
    let currentFolder = 'inbox';

    // Common email domains for autocomplete
    const emailDomains = [
        'gmail.com', 'yahoo.com', 'outlook.com', 'hotmail.com', 'icloud.com',
        'aol.com', 'protonmail.com', 'mail.com', 'yandex.com', 'zoho.com'
    ];

    // Load messages for any folder
    function loadMessages(folder = 'inbox') {
        currentFolder = folder;

        let action = 'get_' + folder;
        if (folder === 'trash') action = 'get_trash';
        if (folder === 'starred') action = 'get_starred';

        $('#message-list').html(`
            <div class="text-center p-5 text-muted">
                <div class="spinner-border text-primary mb-3" role="status"></div>
                <p>Loading messages...</p>
            </div>
        `);

        $.get('functions.php?action=' + action)
         .done(function(html) {
             $('#message-list').html(html);
             updateToolbar();
         })
         .fail(function() {
             $('#message-list').html('<div class="p-5 text-center text-danger">Failed to load messages. Please try again.</div>');
         });
    }

    // Update unread count
    function updateUnreadCount() {
        $.getJSON('functions.php?action=get_unread_count')
         .done(function(data) {
             const count = data.count || 0;
             $('#unread-count, #sidebar-unread').text(count);

             if (count > 0) {
                 $('#notification-bell')
                     .addClass('text-danger animate__animated animate__heartBeat')
                     .attr('title', count + ' unread message' + (count > 1 ? 's' : ''));
             } else {
                 $('#notification-bell')
                     .removeClass('text-danger animate__animated animate__heartBeat')
                     .attr('title', 'No unread messages');
             }

             if (count > 0 && document.hidden && Notification.permission === 'granted') {
                 new Notification('School Mail', {
                     body: `You have ${count} new message${count > 1 ? 's' : ''}`,
                     icon: 'icon-192.png',
                     badge: 'icon-192.png',
                     tag: 'unread-count'
                 });
             }
         });
    }

    // Update toolbar
    function updateToolbar() {
        if (currentFolder === 'trash') {
            $('#delete-btn i').removeClass('fa-trash').addClass('fa-trash-restore').attr('title', 'Delete Forever');
            $('#mark-read-btn i').removeClass('fa-envelope-open').addClass('fa-undo').attr('title', 'Restore');
            $('#mark-read-btn').off('click').on('click', restoreSelected);
        } else {
            $('#delete-btn i').removeClass('fa-trash-restore').addClass('fa-trash').attr('title', 'Move to Trash');
            $('#mark-read-btn i').removeClass('fa-undo').addClass('fa-envelope-open').attr('title', 'Mark as Read');
            $('#mark-read-btn').off('click');
        }
    }

    // Initial
    loadMessages('inbox');
    updateUnreadCount();
    setInterval(updateUnreadCount, 5000);

    // Folder navigation
    $(document).on('click', '[data-folder]', function(e) {
        e.preventDefault();
        $('[data-folder]').removeClass('active text-primary fw-bold');
        $(this).addClass('active text-primary fw-bold');
        loadMessages($(this).data('folder'));
    });

    // Refresh
    $('#refresh-btn').click(function() {
        loadMessages(currentFolder);
    });

    // Global search
    let searchTimeout;
    $('#search-input').on('input', function() {
        clearTimeout(searchTimeout);
        const q = $(this).val().trim();
        searchTimeout = setTimeout(function() {
            if (q.length >= 2) {
                $.get('functions.php?action=search&q=' + encodeURIComponent(q), function(html) {
                    $('#message-list').html(html);
                });
            } else if (q === '') {
                loadMessages(currentFolder);
            }
        }, 300);
    });

    // Open internal compose
    $('.compose-btn-main').click(function() {
        $('#to-search').val('').focus();
        $('#receiver_id').val('');
        $('#user-suggestions').hide().empty();
        $('#compose-form').removeData('reply_to');
        $('#compose-form input[name="subject"]').val('');
        $('#email-warning').remove();
        $('#composeModal').modal('show');
    });

    // Recipient autocomplete (internal)
    $(document).on('input focus', '#to-search', function() {
        const q = $(this).val().trim();
        if (q.length < 2) {
            $('#user-suggestions').hide().empty();
            return;
        }

        $.getJSON('functions.php?action=search_users&q=' + encodeURIComponent(q))
         .done(function(users) {
             $('#user-suggestions').empty();
             if (users.length === 0) {
                 $('#user-suggestions').hide();
                 return;
             }
             users.forEach(user => {
                 const fullName = `${user.first_name} ${user.last_name}`;
                 const initials = fullName.split(' ').map(w => w[0].toUpperCase()).join('');
                 const roleClass = user.role === 'admin' ? 'bg-warning text-dark' : 
                                   user.role === 'teacher' ? 'bg-success' : 'bg-secondary';
                 const emailDisplay = user.email ? user.email : '<span class="text-warning">No email (internal only)</span>';

                 $('#user-suggestions').append(`
                     <div class="p-3 border-bottom user-select hover-bg-light" data-id="${user.id}" style="cursor:pointer;">
                         <div class="d-flex align-items-center">
                             <div class="avatar-placeholder me-3">${initials}</div>
                             <div>
                                 <strong>${fullName}</strong>
                                 <span class="badge ${roleClass} ms-2">${user.role.charAt(0).toUpperCase() + user.role.slice(1)}</span>
                                 <small class="d-block text-muted">${emailDisplay}</small>
                             </div>
                         </div>
                     </div>
                 `);
             });
             $('#user-suggestions').show();
         });
    });

    // Hide suggestions when clicking outside
    $(document).on('click', function(e) {
        if (!$(e.target).closest('#to-search, #user-suggestions').length) {
            $('#user-suggestions').hide();
        }
    });

    // Select recipient (internal) - with warning
    $(document).on('click', '.user-select', function() {
        const id = $(this).data('id');
        const name = $(this).find('strong').text().trim();
        const email = $(this).find('small').text().trim().replace(/<[^>]*>/g, '').trim();

        $('#to-search').val(`${name} <${email || 'No email'}>`);
        $('#receiver_id').val(id);
        $('#user-suggestions').hide();

        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        if (!email || !emailRegex.test(email)) {
            $('#email-warning').remove();
            $('#compose-form .modal-body').prepend(
                '<div id="email-warning" class="alert alert-warning mt-2" role="alert">' +
                '<i class="fas fa-exclamation-triangle"></i> ' +
                'This user has no valid email address. Message saved internally only.' +
                '</div>'
            );
        } else {
            $('#email-warning').remove();
        }
    });

    // Send internal message
    $('#compose-form').submit(function(e) {
        e.preventDefault();

        const receiver_id = $('#receiver_id').val();
        const subject = $('#compose-form input[name="subject"]').val().trim();
        const body = $('#compose-form textarea[name="body"]').val().trim();

        if (!receiver_id || !subject || !body) {
            alert('Please fill all fields and select a recipient.');
            return;
        }

        const reply_to = $('#compose-form').data('reply_to') || '';
        let data = $(this).serialize();
        if (reply_to) data += '&reply_to=' + encodeURIComponent(reply_to);

        $.post('functions.php?action=send_message', data)
         .done(function(res) {
             if (res.success) {
                 $('#composeModal').modal('hide');
                 $('#compose-form')[0].reset();
                 $('#compose-form').removeData('reply_to');
                 $('#email-warning').remove();
                 loadMessages(currentFolder);
                 updateUnreadCount();
                 alert('Internal message sent!');
             } else {
                 alert('Failed: ' + (res.message || 'Error'));
             }
         })
         .fail(function() {
             alert('Network error.');
         });
    });

    // === EXTERNAL EMAIL MODAL FEATURES ===

    // Domain autocomplete suggestions
    let externalSuggestions = [];

    function showExternalSuggestions(email, suggestions) {
        $('#external-suggestions').remove();
        if (suggestions.length === 0) return;

        const $list = $('<div id="external-suggestions" class="position-absolute bg-white border shadow w-100 mt-1" style="max-height:200px;overflow-y:auto;z-index:1000;border-radius:8px;"></div>');
        suggestions.forEach(sugg => {
            $list.append(`<div class="p-2 px-3 hover-bg-light" style="cursor:pointer;">${email.split('@')[0]}@${sugg}</div>`);
        });

        $('input[name="to_email"]').after($list);

        $list.on('click', 'div', function() {
            $('input[name="to_email"]').val($(this).text());
            $('#external-suggestions').remove();
        });
    }

    // REAL-TIME EMAIL VALIDATION (Optional Deep Check)
    let emailValid = true; // Default to true (allow send if verification fails)

    $('input[name="to_email"]').on('input blur keyup', function(e) {
        const $input = $(this);
        const email = $input.val().trim();
        const $container = $input.closest('.mb-3');
        $container.find('.email-feedback, #external-suggestions').remove();
        $input.removeClass('is-valid is-invalid');

        if (email === '') {
            $container.append('<small class="email-feedback text-danger mt-1">Email is required</small>');
            $input.addClass('is-invalid');
            emailValid = false;
            return;
        }

        const parts = email.split('@');
        if (parts.length !== 2 || parts[1] === '') {
            $container.append('<small class="email-feedback text-danger mt-1">Invalid format</small>');
            $input.addClass('is-invalid');
            emailValid = false;
            return;
        }

        const domain = parts[1].toLowerCase();
        const matchingDomains = emailDomains.filter(d => d.startsWith(domain));
        if (matchingDomains.length > 0 && e.type !== 'blur') {
            showExternalSuggestions(email, matchingDomains);
        } else {
            $('#external-suggestions').remove();
        }

        // Basic format check (always required)
        const formatRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
        if (!formatRegex.test(email)) {
            $container.append('<small class="email-feedback text-danger mt-1">Invalid email format</small>');
            $input.addClass('is-invalid');
            emailValid = false;
            return;
        }

        // Optional deep check
        $container.append('<small class="email-feedback text-muted mt-1">Checking deliverability (optional)...</small>');

        fetch(`https://rapid-email-verifier.fly.dev/?email=${encodeURIComponent(email)}`)
            .then(r => r.json())
            .then(data => {
                $container.find('.email-feedback').remove();

                if (data.valid && !data.disposable) {
                    $container.append('<small class="email-feedback text-success mt-1">✓ Valid & deliverable email</small>');
                    $input.addClass('is-valid');
                    emailValid = true;
                } else {
                    let msg = data.disposable ? 'Disposable email detected' : 'Risky or undeliverable email';
                    if (data.reason) msg += `: ${data.reason}`;
                    $container.append(`<small class="email-feedback text-warning mt-1">${msg} (can still send)</small>`);
                    $input.addClass('is-valid'); // Allow send
                    emailValid = true;
                }
            })
            .catch(() => {
                $container.find('.email-feedback').remove();
                $container.append('<small class="email-feedback text-warning mt-1">Verification unavailable - using format check only (can send)</small>');
                $input.addClass('is-valid');
                emailValid = true; // Allow send
            });
    });



    // Hide external suggestions on outside click
    $(document).on('click', function(e) {
        if (!$(e.target).closest('input[name="to_email"], #external-suggestions').length) {
            $('#external-suggestions').remove();
        }
    });

    // Expand thread and mark as read
    $(document).on('click', '.thread-header', function(e) {
        if ($(e.target).closest('.star-btn, .message-checkbox, input, button').length) return;
        const $header = $(this);
        $header.next('.thread-body').slideToggle(300);

        if ($header.hasClass('unread')) {
            const threadId = $header.data('thread-id');
            $.post('functions.php?action=mark_read', {msg_id: threadId});
            $header.removeClass('unread');
            updateUnreadCount();
        }
    });

    // STAR
    $(document).on('click', '.star-btn', function(e) {
        e.stopPropagation();
        const $icon = $(this);
        const msgId = $icon.data('msg-id');

        $.post('functions.php?action=toggle_star', {msg_id: msgId})
         .done(function() {
             $icon.toggleClass('far fas text-muted text-warning');
         });
    });

    // REPLY
    $(document).on('click', '.reply-btn', function(e) {
        e.stopPropagation();

        const msgId = $(this).data('id');
        const senderId = $(this).data('sender');
        const subject = $(this).data('subject');
        const senderName = $(this).data('sender-name');

        $('#to-search').val(senderName);
        $('#receiver_id').val(senderId);
        const replySubject = subject.startsWith('Re: ') ? subject : 'Re: ' + subject;
        $('#compose-form input[name="subject"]').val(replySubject);
        $('#compose-form').data('reply_to', msgId);
        $('#composeModal').modal('show');
    });

    // Select all / Delete / Restore
    $('#select-all').change(function() {
        $('.message-checkbox').prop('checked', this.checked);
    });

    $('#delete-btn').click(function() {
        const msgIds = [];
        $('.message-checkbox:checked').each(function() {
            const threadId = $(this).closest('.thread-header').data('thread-id');
            if (threadId) msgIds.push(threadId);
        });

        if (msgIds.length === 0) {
            alert('Please select at least one conversation');
            return;
        }

        const action = currentFolder === 'trash' ? 'permanent_delete' : 'move_to_trash';

        $.post('functions.php?action=' + action, {msg_ids: msgIds})
         .done(function() {
             loadMessages(currentFolder);
         });
    });

    function restoreSelected() {
        const msgIds = [];
        $('.message-checkbox:checked').each(function() {
            const threadId = $(this).closest('.thread-header').data('thread-id');
            if (threadId) msgIds.push(threadId);
        });

        if (msgIds.length === 0) return;

        $.post('functions.php?action=restore_from_trash', {msg_ids: msgIds})
         .done(function() {
             loadMessages(currentFolder);
         });
    }

    // Dark mode
    $('#dark-mode-toggle').click(function() {
        $('html').toggleClass('dark-mode');
        const isDark = $('html').hasClass('dark-mode');
        $(this).find('i').toggleClass('fa-moon fa-sun');
        localStorage.setItem('darkMode', isDark);
    });

    if (localStorage.getItem('darkMode') === 'true') {
        $('html').addClass('dark-mode');
        $('#dark-mode-toggle i').removeClass('fa-moon').addClass('fa-sun');
    }

    // Initial toolbar
    updateToolbar();
});