(function () {
  'use strict';

  const PROXY_URL = '/api/brevo-newsletter-proxy.php';

  async function subscribeToNewsletter(email, attributes = {}) {
    const response = await fetch(PROXY_URL, {
      method: 'POST',
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ email, attributes }),
    });

    const data = await response.json();

    if (!response.ok) {
      const error = new Error(
        data.user_message || data.message || 'Subscription error'
      );
      error.code = data.error;
      error.data = data;
      throw error;
    }

    return data;
  }

  function showMessage(form, text, isError = false) {
    const oldMessages = form.parentNode.querySelectorAll('.newsletter-message');
    oldMessages.forEach((msg) => msg.remove());

    const message = document.createElement('p');
    message.className = 'newsletter-message';
    message.textContent = text;
    message.style.marginTop = '0.5rem';
    message.style.fontSize = '0.9rem';
    message.style.color = isError
      ? 'var(--color-error, #ef4444)'
      : 'var(--color-success, #22c55e)';

    form.parentNode.insertBefore(message, form.nextSibling);

    if (!isError) {
      setTimeout(() => message.remove(), 5000);
    }
  }

  async function handleFormSubmit(event) {
    event.preventDefault();

    const form = event.target;
    const emailInput = form.querySelector('input[type="email"]');
    const submitButton = form.querySelector('button[type="submit"]');

    if (!emailInput || !emailInput.value) {
      const message = location.pathname.includes('/en/')
        ? 'Please enter a valid email address.'
        : 'Veuillez entrer une adresse email valide.';
      showMessage(form, messsage, true);
      return;
    }

    const email = emailInput.value.trim();
    submitButton.disabled = true;

    try {
      await subscribeToNewsletter(email);
      const message = location.pathname.includes('/en/')
        ? 'Thank you! Your subscription has been confirmed.'
        : 'Merci, votre inscription est confirmée !';
      showMessage(form, message, false);
      form.reset();
    } catch (error) {
      const isAlreadySubscribed = error.code === 'email_already_exists';
      showMessage(form, error.message, !isAlreadySubscribed);
    } finally {
      submitButton.disabled = false;
    }
  }

  function initNewsletterForms() {
    const forms = document.querySelectorAll('.form__newsletter');
    forms.forEach((form) => form.addEventListener('submit', handleFormSubmit));
  }

  document.addEventListener('DOMContentLoaded', initNewsletterForms);
})();
