css(`
    email-join-form {
        display: flex
    }
`)

export default class EmailJoinForm extends HTMLElement {
    constructor() {
        super();
    }

    connectedCallback() {
        this.querySelector('#submit-button').addEventListener('click', () => this.submitEmail());
    }

    isValidEmail(email) {
        const emailRegex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,16}$/;
        return emailRegex.test(email);
    }

    showError(message) {
        $(this).find('#form-message')
            .css('color', 'red')
            .text(message);
    }

    showSuccess(message) {
        $(this).find('#form-message')
            .css('color', 'green')
            .text(message);
    }

    clearError() {
        this.querySelector('#form-message').textContent = '';
    }

    async submitEmail() {
        const email = this.querySelector('#email-input').value.trim();
        this.clearError();

        if (!this.isValidEmail(email)) {
            this.showError('Please enter a valid email address.');
            return;
        }

        const res = await fetch('/api/join', {
            method: 'POST',
            headers: {
            'Content-Type': 'application/json',
            },
            body: JSON.stringify({ email }),
        });

        if (res.ok) {
            this.showSuccess('Email sent.');
        } else {
            const error = await res.text();
            this.showError(error)
        }
    }
}

customElements.define("email-join-form", EmailJoinForm);