/* Khemisi — contact form submission + captcha loader */
(function () {
  var CONTACT_ENDPOINT = 'backend/contact.php';
  var CAPTCHA_ENDPOINT = 'backend/captcha.php';

  var form       = document.getElementById('contact-form');
  if (!form) return;

  var img        = document.getElementById('captcha-img');
  var fallback   = document.getElementById('captcha-fallback');
  var refreshBtn = document.getElementById('captcha-refresh');
  var input      = document.getElementById('captcha-input');
  var msg        = document.getElementById('form-msg');
  var submitBtn  = form.querySelector('button[type="submit"]');

  async function reloadCaptcha() {
    if (!img) return;
    if (input) input.value = '';
    try {
      var res = await fetch(CAPTCHA_ENDPOINT + '?t=' + Date.now(), { credentials: 'same-origin' });
      if (!res.ok) throw new Error('http ' + res.status);
      var ct = res.headers.get('content-type') || '';
      if (ct.indexOf('image') === -1) throw new Error('not_image');
      var blob = await res.blob();
      img.src = URL.createObjectURL(blob);
      img.style.display = 'block';
      if (fallback) fallback.style.display = 'none';
    } catch (e) {
      img.style.display = 'none';
      if (fallback) fallback.style.display = 'flex';
    }
  }
  reloadCaptcha();

  if (refreshBtn) refreshBtn.addEventListener('click', function () {
    reloadCaptcha(); setMsg('', ''); if (input) input.focus();
  });
  if (img) img.addEventListener('click', reloadCaptcha);

  function setMsg(text, kind) {
    if (!msg) return;
    msg.textContent = text;
    msg.className = 'form-msg' + (kind ? ' ' + kind : '');
  }
  function markInvalid(field, invalid) {
    var parent = field.closest('label, .captcha-field');
    if (parent) parent.classList.toggle('invalid', !!invalid);
  }
  function clientValidate() {
    var required = form.querySelectorAll('[required]');
    var firstInvalid = null;
    required.forEach(function (el) {
      var bad = !el.value || el.value.trim() === '';
      if (el.type === 'email' && el.value) {
        bad = !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(el.value);
      }
      markInvalid(el, bad);
      if (bad && !firstInvalid) firstInvalid = el;
    });
    return firstInvalid;
  }

  var ERR_LABELS = {
    'rate_limited':           'Trop de tentatives. Patientez quelques minutes.',
    'captcha_expired':        'Le code a expiré. Un nouveau a été généré.',
    'captcha_invalid':        'Code incorrect. Un nouveau a été généré.',
    'captcha_too_many_tries': 'Trop d\u2019échecs captcha. Rafraîchissez la page.',
    'validation':             'Merci de compléter correctement les champs requis.',
    'mail_failure':           'Erreur d\u2019envoi côté serveur. Réessayez ou écrivez à contact@khemisi.com.',
    'method_not_allowed':     'Requête invalide.'
  };

  form.addEventListener('submit', async function (e) {
    e.preventDefault();
    setMsg('', '');

    var hp = form.querySelector('input[name="website"]');
    if (hp && hp.value.trim() !== '') { return; }

    var firstInvalid = clientValidate();
    if (firstInvalid) {
      setMsg('Merci de compléter les champs requis.', 'err');
      firstInvalid.focus();
      return;
    }

    var fd = new FormData(form);
    var payload = {};
    fd.forEach(function (v, k) { payload[k] = (typeof v === 'string') ? v : String(v); });

    if (submitBtn) { submitBtn.disabled = true; submitBtn.style.opacity = '0.6'; }
    setMsg('Envoi en cours…', '');

    try {
      var res = await fetch(CONTACT_ENDPOINT, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' },
        credentials: 'same-origin',
        body: JSON.stringify(payload)
      });
      var body = null; try { body = await res.json(); } catch (_) {}

      if (res.ok && body && body.ok) {
        var firstName = ((payload.name || '').split(' ')[0] || '').trim();
        setMsg('Demande envoyée · réf. ' + (body.ref || '—') + '. Merci ' + (firstName || '') + ', à très vite.', 'ok');
        form.reset();
        reloadCaptcha();
      } else {
        var code = (body && body.error) ? body.error : 'mail_failure';
        var label = ERR_LABELS[code] || 'Une erreur est survenue. Réessayez dans un instant.';
        if (body && body.fields) {
          form.querySelectorAll('label.invalid, .captcha-field.invalid').forEach(function (f) { f.classList.remove('invalid'); });
          Object.keys(body.fields).forEach(function (name) {
            var el = form.querySelector('[name="' + name + '"]');
            if (el) markInvalid(el, true);
          });
        }
        if (code === 'captcha_invalid' || code === 'captcha_expired') {
          reloadCaptcha(); markInvalid(input, true);
        }
        setMsg(label, 'err');
      }
    } catch (err) {
      setMsg('Réseau indisponible. Réessayez, ou écrivez à contact@khemisi.com.', 'err');
    } finally {
      if (submitBtn) { submitBtn.disabled = false; submitBtn.style.opacity = ''; }
    }
  });

  form.querySelectorAll('input, textarea, select').forEach(function (el) {
    el.addEventListener('input',  function () { markInvalid(el, false); });
    el.addEventListener('change', function () { markInvalid(el, false); });
  });
})();
