
/**
 * @license
 * SPDX-License-Identifier: Apache-2.0
 */

document.addEventListener('DOMContentLoaded', () => {
    const newsletterForm = document.getElementById('newsletterForm') as HTMLFormElement | null;
    const emailInput = document.getElementById('email') as HTMLInputElement | null;
    const formMessage = document.getElementById('formMessage') as HTMLDivElement | null;
    const currentYearSpan = document.getElementById('currentYear') as HTMLSpanElement | null;

    if (currentYearSpan) {
        currentYearSpan.textContent = new Date().getFullYear().toString();
    }

    if (newsletterForm && emailInput && formMessage) {
        newsletterForm.addEventListener('submit', (event) => {
            event.preventDefault();
            formMessage.textContent = '';
            formMessage.className = ''; // Clear existing classes

            const email = emailInput.value.trim();

            if (!validateEmail(email)) {
                displayMessage('Por favor, insira um endereço de e-mail válido.', 'error');
                emailInput.focus();
                return;
            }

            // Simulate API call
            displayMessage('Obrigado por se inscrever! Fique de olho na sua caixa de entrada.', 'success');
            emailInput.value = ''; // Clear input after successful submission

            // In a real application, you would send the email to your backend/service here.
            // Example:
            // try {
            //   const response = await fetch('/api/subscribe', {
            //     method: 'POST',
            //     headers: { 'Content-Type': 'application/json' },
            //     body: JSON.stringify({ email })
            //   });
            //   if (response.ok) {
            //     displayMessage('Obrigado por se inscrever!', 'success');
            //     emailInput.value = '';
            //   } else {
            //     const errorData = await response.json();
            //     displayMessage(errorData.message || 'Ocorreu um erro. Tente novamente.', 'error');
            //   }
            // } catch (error) {
            //   displayMessage('Falha na conexão. Tente novamente mais tarde.', 'error');
            // }
        });
    }

    function validateEmail(email: string): boolean {
        // Basic email validation regex
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        return emailRegex.test(email);
    }

    function displayMessage(message: string, type: 'success' | 'error') {
        if (formMessage) {
            formMessage.textContent = message;
            formMessage.className = type; // Applies .success or .error class
        }
    }
});
