---
import { getLangFromUrl, t } from '../i18n/utils';

const lang = getLangFromUrl(Astro.url);
---

<div class="form-wrapper">
  <form
    id="soumission-form"
    class="soumission-form"
    novalidate
    aria-label={t(lang, 'soumission.title')}
  >
    <div class="form-row">
      <div class="form-group">
        <label for="nom" class="form-label">
          {t(lang, 'form.nom')}
          <span class="form-required" aria-hidden="true">*</span>
        </label>
        <input
          type="text"
          id="nom"
          name="nom"
          class="form-input"
          placeholder={t(lang, 'form.nom.placeholder')}
          required
          autocomplete="name"
        />
        <span class="form-error" id="nom-error" role="alert" aria-live="polite"></span>
      </div>

      <div class="form-group">
        <label for="courriel" class="form-label">
          {t(lang, 'form.courriel')}
          <span class="form-required" aria-hidden="true">*</span>
        </label>
        <input
          type="email"
          id="courriel"
          name="courriel"
          class="form-input"
          placeholder={t(lang, 'form.courriel.placeholder')}
          required
          autocomplete="email"
        />
        <span class="form-error" id="courriel-error" role="alert" aria-live="polite"></span>
      </div>
    </div>

    <div class="form-row">
      <div class="form-group">
        <label for="telephone" class="form-label">
          {t(lang, 'form.telephone')}
          <span class="form-required" aria-hidden="true">*</span>
        </label>
        <input
          type="tel"
          id="telephone"
          name="telephone"
          class="form-input"
          placeholder={t(lang, 'form.telephone.placeholder')}
          required
          autocomplete="tel"
        />
        <span class="form-error" id="telephone-error" role="alert" aria-live="polite"></span>
      </div>

      <div class="form-group">
        <label for="type_service" class="form-label">
          {t(lang, 'form.type_service')}
          <span class="form-required" aria-hidden="true">*</span>
        </label>
        <select
          id="type_service"
          name="type_service"
          class="form-input form-select"
          required
        >
          <option value="">{t(lang, 'form.type_service.placeholder')}</option>
          <option value="interieur">{t(lang, 'form.type_service.interieur')}</option>
          <option value="exterieur">{t(lang, 'form.type_service.exterieur')}</option>
          <option value="commercial">{t(lang, 'form.type_service.commercial')}</option>
          <option value="decoration">{t(lang, 'form.type_service.decoration')}</option>
          <option value="autre">{t(lang, 'form.type_service.autre')}</option>
        </select>
        <span class="form-error" id="type_service-error" role="alert" aria-live="polite"></span>
      </div>
    </div>

    <div class="form-group">
      <label for="adresse" class="form-label">
        {t(lang, 'form.adresse')}
      </label>
      <input
        type="text"
        id="adresse"
        name="adresse"
        class="form-input"
        placeholder={t(lang, 'form.adresse.placeholder')}
        autocomplete="street-address"
      />
    </div>

    <div class="form-group">
      <label for="message" class="form-label">
        {t(lang, 'form.message')}
        <span class="form-required" aria-hidden="true">*</span>
      </label>
      <textarea
        id="message"
        name="message"
        class="form-input form-textarea"
        placeholder={t(lang, 'form.message.placeholder')}
        required
        rows="5"
      ></textarea>
      <span class="form-error" id="message-error" role="alert" aria-live="polite"></span>
    </div>

    <button type="submit" class="btn-primary form-submit-btn" id="submit-btn">
      <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" aria-hidden="true">
        <line x1="22" y1="2" x2="11" y2="13"/>
        <polygon points="22,2 15,22 11,13 2,9"/>
      </svg>
      <span id="submit-text">{t(lang, 'form.envoyer')}</span>
    </button>
  </form>

  <!-- Success message -->
  <div class="form-success" id="form-success" aria-live="polite" aria-hidden="true">
    <div class="form-success-icon">
      <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" aria-hidden="true">
        <path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/>
        <polyline points="22,4 12,14.01 9,11.01"/>
      </svg>
    </div>
    <h3>{t(lang, 'form.success.title')}</h3>
    <p>{t(lang, 'form.success.message')}</p>
  </div>

  <!-- Error message -->
  <div class="form-error-msg" id="form-error-msg" aria-live="assertive" aria-hidden="true">
    <div class="form-error-icon">
      <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" aria-hidden="true">
        <circle cx="12" cy="12" r="10"/>
        <line x1="15" y1="9" x2="9" y2="15"/>
        <line x1="9" y1="9" x2="15" y2="15"/>
      </svg>
    </div>
    <div>
      <strong>{t(lang, 'form.error.title')}</strong>
      <p>{t(lang, 'form.error.message')}</p>
    </div>
  </div>
</div>

<style>
  .form-wrapper {
    width: 100%;
  }

  .soumission-form {
    display: flex;
    flex-direction: column;
    gap: 1.25rem;
  }

  .form-row {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 1.25rem;
  }

  .form-group {
    display: flex;
    flex-direction: column;
    gap: 0;
  }

  .form-required {
    color: #c0392b;
    margin-left: 2px;
  }

  .form-select {
    appearance: none;
    background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 24 24' fill='none' stroke='%23444445' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='6 9 12 15 18 9'/%3E%3C/svg%3E");
    background-repeat: no-repeat;
    background-position: right 0.875rem center;
    padding-right: 2.5rem;
    cursor: pointer;
  }

  .form-textarea {
    resize: vertical;
    min-height: 120px;
  }

  .form-error {
    display: block;
    font-size: 0.8125rem;
    color: #c0392b;
    margin-top: 0.25rem;
    min-height: 1.125rem;
  }

  .form-submit-btn {
    width: 100%;
    justify-content: center;
    padding: 1rem;
    font-size: 1.0625rem;
    margin-top: 0.5rem;
  }

  .form-success,
  .form-error-msg {
    display: none;
    border-radius: 8px;
    padding: 2rem;
    text-align: center;
  }

  .form-success[aria-hidden="false"],
  .form-error-msg[aria-hidden="false"] {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 1rem;
  }

  .form-success {
    background-color: var(--color-brand-50);
    border: 1.5px solid var(--color-brand-300);
    color: var(--color-brand-600);
  }

  .form-success-icon {
    width: 64px;
    height: 64px;
    border-radius: 50%;
    background-color: var(--color-brand-600);
    color: #ffffff;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .form-success h3 {
    font-size: 1.25rem;
    color: var(--color-brand-600);
  }

  .form-success p {
    color: var(--color-gray-dark);
    opacity: 0.8;
  }

  .form-error-msg {
    background-color: #fef2f2;
    border: 1.5px solid #fca5a5;
    color: #b91c1c;
    flex-direction: row;
    text-align: left;
    gap: 1rem;
  }

  .form-error-icon {
    flex-shrink: 0;
    color: #b91c1c;
  }

  .form-error-msg p {
    margin-top: 0.25rem;
    font-size: 0.9rem;
    opacity: 0.85;
  }

  @media (max-width: 540px) {
    .form-row {
      grid-template-columns: 1fr;
    }
  }
</style>

<script>
  const form = document.getElementById('soumission-form') as HTMLFormElement | null;
  const submitBtn = document.getElementById('submit-btn') as HTMLButtonElement | null;
  const submitText = document.getElementById('submit-text');
  const successDiv = document.getElementById('form-success');
  const errorDiv = document.getElementById('form-error-msg');

  function showError(fieldId: string, message: string) {
    const el = document.getElementById(`${fieldId}-error`);
    const input = document.getElementById(fieldId);
    if (el) el.textContent = message;
    if (input) input.setAttribute('aria-invalid', 'true');
  }

  function clearErrors() {
    ['nom', 'courriel', 'telephone', 'type_service', 'message'].forEach(id => {
      const el = document.getElementById(`${id}-error`);
      const input = document.getElementById(id);
      if (el) el.textContent = '';
      if (input) input.removeAttribute('aria-invalid');
    });
  }

  function validateForm(data: FormData): boolean {
    let valid = true;
    clearErrors();

    const nom = data.get('nom') as string;
    const courriel = data.get('courriel') as string;
    const telephone = data.get('telephone') as string;
    const type_service = data.get('type_service') as string;
    const message = data.get('message') as string;

    if (!nom?.trim()) {
      showError('nom', 'Le nom est requis.');
      valid = false;
    }

    if (!courriel?.trim() || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(courriel)) {
      showError('courriel', 'Une adresse courriel valide est requise.');
      valid = false;
    }

    if (!telephone?.trim()) {
      showError('telephone', 'Le numéro de téléphone est requis.');
      valid = false;
    }

    if (!type_service) {
      showError('type_service', 'Veuillez sélectionner un type de service.');
      valid = false;
    }

    if (!message?.trim()) {
      showError('message', 'Un message est requis.');
      valid = false;
    }

    return valid;
  }

  form?.addEventListener('submit', async (e) => {
    e.preventDefault();

    if (!submitBtn || !submitText || !successDiv || !errorDiv) return;

    const formData = new FormData(form);

    if (!validateForm(formData)) return;

    // Disable form during submission
    submitBtn.disabled = true;
    submitText.textContent = 'Envoi en cours...';

    try {
      const body = {
        nom: formData.get('nom'),
        courriel: formData.get('courriel'),
        telephone: formData.get('telephone'),
        type_service: formData.get('type_service'),
        adresse: formData.get('adresse'),
        message: formData.get('message'),
      };

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

      if (!res.ok) throw new Error('Server error');

      form.style.display = 'none';
      errorDiv.setAttribute('aria-hidden', 'true');
      errorDiv.style.display = 'none';
      successDiv.setAttribute('aria-hidden', 'false');
      successDiv.style.display = 'flex';

    } catch {
      submitBtn.disabled = false;
      submitText.textContent = 'Envoyer ma demande';
      errorDiv.setAttribute('aria-hidden', 'false');
      errorDiv.style.display = 'flex';
    }
  });
</script>
