(() => {
  'use strict';

  const form = document.querySelector('#contactForm');
  const status = document.querySelector('#formStatus');
  const submitButton = form?.querySelector('button[type="submit"]');

  if (!form || !status || !submitButton) return;

  form.addEventListener('submit', (event) => {
    event.preventDefault();
    event.stopPropagation();

    if (!form.checkValidity()) {
      form.classList.add('was-validated');
      status.className = 'form-status show error';
      status.textContent = 'Please complete the required fields correctly.';
      return;
    }

    submitButton.disabled = true;
    submitButton.innerHTML = '<span class="spinner-border spinner-border-sm" aria-hidden="true"></span> Preparing message…';

    const data = new FormData(form);
    const name = data.get('name');
    const email = data.get('email');
    const company = data.get('company') || 'Not supplied';
    const service = data.get('service');
    const scope = data.get('scope') || 'Not supplied';
    const timeline = data.get('timeline') || 'Not supplied';
    const details = data.get('details');

    const subject = encodeURIComponent(`Portfolio enquiry: ${service}`);
    const body = encodeURIComponent(
      `Hello Adesoye,\n\nMy name is ${name}. I visited your portfolio and would like to discuss a project.\n\n` +
      `Email: ${email}\nCompany/Organisation: ${company}\nService: ${service}\nEstimated scope: ${scope}\nPreferred timeline: ${timeline}\n\nProject details:\n${details}\n`
    );

    const emailAddress = 'Adesoyemathew@gmail.com';

    window.setTimeout(() => {
      status.className = 'form-status show success';
      status.textContent = 'Your email application will now open with the project details prepared.';
      window.location.href = `mailto:${emailAddress}?subject=${subject}&body=${body}`;
      submitButton.disabled = false;
      submitButton.innerHTML = 'Send Project Enquiry <span class="btn-icon"><i class="bi bi-arrow-up-right"></i></span>';
    }, 500);
  });
})();
