// DOM Elements
const signupCard = document.getElementById('signupCard');
const successCard = document.getElementById('successCard');
const signupForm = document.getElementById('signupForm');
const emailInput = document.getElementById('email');
const errorMessage = document.getElementById('errorMessage');
const confirmedEmail = document.getElementById('confirmedEmail');
const dismissBtn = document.getElementById('dismissBtn');

// Email validation regex
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

// Form submission handler
signupForm.addEventListener('submit', function(e) {
    e.preventDefault();
    
    const email = emailInput.value.trim();
    
    // Clear previous error states
    clearError();
    
    // Validate email
    if (!email) {
        showError('Email is required');
        return;
    }
    
    if (!emailRegex.test(email)) {
        showError('Valid email required');
        return;
    }
    
    // If validation passes, show success message
    showSuccessMessage(email);
});

// Email input event listeners
emailInput.addEventListener('input', function() {
    if (emailInput.classList.contains('error')) {
        clearError();
    }
});

emailInput.addEventListener('focus', function() {
    if (emailInput.classList.contains('error')) {
        clearError();
    }
});

// Dismiss button handler
dismissBtn.addEventListener('click', function() {
    showSignupForm();
    emailInput.value = '';
});

// Helper functions
function showError(message) {
    errorMessage.textContent = message;
    errorMessage.classList.add('show');
    emailInput.classList.add('error');
}

function clearError() {
    errorMessage.textContent = '';
    errorMessage.classList.remove('show');
    emailInput.classList.remove('error');
}

function showSuccessMessage(email) {
    confirmedEmail.textContent = email;
    signupCard.classList.add('hidden');
    successCard.classList.remove('hidden');
}

function showSignupForm() {
    successCard.classList.add('hidden');
    signupCard.classList.remove('hidden');
    clearError();
}

// Initialize the application
document.addEventListener('DOMContentLoaded', function() {
    // Ensure the signup form is visible on load
    signupCard.classList.remove('hidden');
    successCard.classList.add('hidden');
    
    // Focus on email input for better UX
    emailInput.focus();
});

// Handle browser back button
window.addEventListener('popstate', function() {
    showSignupForm();
});

// Add keyboard navigation support
document.addEventListener('keydown', function(e) {
    // ESC key to go back to signup form from success message
    if (e.key === 'Escape' && !successCard.classList.contains('hidden')) {
        showSignupForm();
        emailInput.value = '';
    }
});
