// SmartINBOX Main JavaScript

document.addEventListener('DOMContentLoaded', function() {
    console.log('SmartINBOX application loaded');
    
    // Handle contact form submission
    const contactForm = document.getElementById('contactForm');
    if (contactForm) {
        contactForm.addEventListener('submit', function(e) {
            e.preventDefault();
            
            const name = document.getElementById('name').value;
            const email = document.getElementById('email').value;
            const subject = document.getElementById('subject').value;
            const message = document.getElementById('message').value;
            
            // In a real application, you would send this data to your server
            console.log('Form submitted:', { name, email, subject, message });
            
            // Show success message
            alert('Thank you for your message! We will get back to you soon.');
            
            // Reset form
            contactForm.reset();
        });
    }
    
    // Smooth scrolling for anchor links
    document.querySelectorAll('a[href^="#"]').forEach(anchor => {
        anchor.addEventListener('click', function(e) {
            e.preventDefault();
            
            const target = document.querySelector(this.getAttribute('href'));
            if (target) {
                window.scrollTo({
                    top: target.offsetTop - 80, // Adjust for header height
                    behavior: 'smooth'
                });
            }
        });
    });
    
    // Check if we're on the dashboard page
    if (window.location.pathname.includes('/dashboard')) {
        // Load emails from API
        fetchEmails();
    }
});

// Function to fetch emails from the API
function fetchEmails() {
    fetch('/api/emails')
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            return response.json();
        })
        .then(emails => {
            console.log('Emails loaded:', emails);
            displayEmails(emails);
        })
        .catch(error => {
            console.error('Error fetching emails:', error);
            showErrorMessage('Failed to load emails. Please try again later.');
        });
}

// Function to display emails in the UI
function displayEmails(emails) {
    const emailList = document.getElementById('email-list');
    if (!emailList) return;
    
    emailList.innerHTML = '';
    
    if (emails.length === 0) {
        emailList.innerHTML = '<div class="empty-state">No emails found</div>';
        return;
    }
    
    emails.forEach(email => {
        const date = new Date(email.date);
        const formattedDate = date.toLocaleDateString() + ' ' + date.toLocaleTimeString();
        
        const emailItem = document.createElement('div');
        emailItem.className = 'email-item';
        emailItem.innerHTML = `
            <div class="email-subject">${email.subject}</div>
            <div class="email-from">From: ${email.from}</div>
            <div class="email-date">${formattedDate}</div>
        `;
        
        emailItem.addEventListener('click', function() {
            showEmailDetails(email);
        });
        
        emailList.appendChild(emailItem);
    });
}

// Function to show email details
function showEmailDetails(email) {
    const modal = document.createElement('div');
    modal.className = 'email-modal';
    
    modal.innerHTML = `
        <div class="email-modal-content">
            <span class="close-modal">&times;</span>
            <h3>${email.subject}</h3>
            <div class="email-meta">
                <div>From: ${email.from}</div>
                <div>To: ${email.to}</div>
                <div>Date: ${new Date(email.date).toLocaleString()}</div>
            </div>
            <div class="email-body">${email.body}</div>
            <div class="email-actions">
                <button class="reply-btn">Reply</button>
                <button class="forward-btn">Forward</button>
                <button class="delete-btn">Delete</button>
            </div>
        </div>
    `;
    
    document.body.appendChild(modal);
    
    // Close modal when clicking the close button
    modal.querySelector('.close-modal').addEventListener('click', function() {
        document.body.removeChild(modal);
    });
    
    // Close modal when clicking outside the content
    modal.addEventListener('click', function(e) {
        if (e.target === modal) {
            document.body.removeChild(modal);
        }
    });
    
    // Handle reply button
    modal.querySelector('.reply-btn').addEventListener('click', function() {
        alert(`Reply to: ${email.from}\nSubject: Re: ${email.subject}`);
    });
    
    // Handle forward button
    modal.querySelector('.forward-btn').addEventListener('click', function() {
        alert(`Forward email: ${email.subject}`);
    });
    
    // Handle delete button
    modal.querySelector('.delete-btn').addEventListener('click', function() {
        if (confirm('Are you sure you want to delete this email?')) {
            alert('Email deleted');
            document.body.removeChild(modal);
            // In a real app, you would call an API to delete the email
        }
    });
}

// Function to show error messages
function showErrorMessage(message) {
    const errorDiv = document.createElement('div');
    errorDiv.className = 'error-message';
    errorDiv.textContent = message;
    
    document.body.appendChild(errorDiv);
    
    // Remove the error message after 5 seconds
    setTimeout(() => {
        document.body.removeChild(errorDiv);
    }, 5000);
}

// Add a global error handler
window.addEventListener('error', function(e) {
    console.error('Global error:', e.error);
    showErrorMessage('An error occurred. Please try again later.');
});