document.addEventListener('DOMContentLoaded', function() {
    // Handle city form submission
    const cityForm = document.querySelector('form[action*="add_city"]');
    if (cityForm) {
        cityForm.addEventListener('submit', function(e) {
            e.preventDefault();
            
            const formData = new FormData(cityForm);
            const submitButton = cityForm.querySelector('button[type="submit"]');
            const originalButtonText = submitButton.innerHTML;
            
            // Show loading state
            submitButton.disabled = true;
            submitButton.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Adding City...';
            
            fetch(window.location.href, {
                method: 'POST',
                body: formData
            })
            .then(response => response.text())
            .then(html => {
                // Create a temporary element to parse the response
                const temp = document.createElement('div');
                temp.innerHTML = html;
                
                // Check for success/error messages
                const successMsg = temp.querySelector('.bg-green-100');
                const errorMsg = temp.querySelector('.bg-red-100');
                
                if (successMsg) {
                    // Show success message
                    showMessage('success', successMsg.textContent.trim());
                    // Reset form
                    cityForm.reset();
                    // Reload the page to show updated list
                    setTimeout(() => window.location.reload(), 1500);
                } else if (errorMsg) {
                    showMessage('error', errorMsg.textContent.trim());
                } else {
                    // If no specific message, just reload
                    window.location.reload();
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showMessage('error', 'An error occurred while adding the city.');
            })
            .finally(() => {
                submitButton.disabled = false;
                submitButton.innerHTML = originalButtonText;
            });
        });
    }
});

// Function to show messages
function showMessage(type, message) {
    // Remove any existing messages
    const existingMessages = document.querySelectorAll('.message-toast');
    existingMessages.forEach(msg => msg.remove());
    
    // Create message element
    const messageEl = document.createElement('div');
    messageEl.className = `fixed top-4 right-4 p-4 rounded-lg shadow-lg z-50 message-toast ${
        type === 'success' ? 'bg-green-100 text-green-800 border-green-200' : 'bg-red-100 text-red-800 border-red-200'
    } border`;
    
    messageEl.innerHTML = `
        <div class="flex items-center">
            <i class="fas ${type === 'success' ? 'fa-check-circle' : 'fa-exclamation-circle'} mr-2"></i>
            <span>${message}</span>
        </div>
    `;
    
    document.body.appendChild(messageEl);
    
    // Auto-remove after 5 seconds
    setTimeout(() => {
        messageEl.remove();
    }, 5000);
}
