/* ExpertAims AimsHub CMS — contact form → enquiry inbox
 * ---------------------------------------------------------------------------
 * Progressive upgrade of the approved static contact form. render.php tags the
 * form with data-cms="enquiry" and injects the server-rendered captcha + CSRF
 * token + honeypot. This binds a CAPTURE-phase submit handler (so it runs
 * before site.js's data-mailto handler and can stop it), validates, and POSTs
 * to ?capture=enquiry. On success the enquiry lands in the CMS inbox (and the
 * HQ "unread enquiries" metric). On a network failure it shows the direct
 * email / WhatsApp fallback — the form is never a dead end.
 */
(function () {
  'use strict';
  function val(form, sel) { var el = form.querySelector(sel); return el && el.value ? el.value.trim() : ''; }
  function slug() { return (location.pathname.split('/').pop() || 'contact').replace('.html', '') || 'contact'; }

  function subjectOf(form) {
    var chip = form.querySelector('.ct-chip.on');
    if (chip && chip.getAttribute('data-subject')) return chip.getAttribute('data-subject');
    return form.getAttribute('data-subject') || 'Consultation request';
  }

  function note(form, html, ok) {
    var box = form.querySelector('.cms-note');
    if (!box) {
      box = document.createElement('div');
      box.className = 'cms-note';
      var btn = form.querySelector('button[type="submit"]');
      (btn ? btn.parentNode : form).insertBefore(box, btn || null);
    }
    box.className = 'cms-note ' + (ok ? 'cms-ok' : 'cms-bad');
    box.innerHTML = html;
    box.setAttribute('role', 'status');
  }

  function bind(form) {
    form.addEventListener('submit', function (ev) {
      var name = val(form, '[name="name"]');
      var email = val(form, '[name="email"]');
      var msg = val(form, '[name="msg"]') || val(form, '[name="message"]');
      var sum = val(form, '[name="sum"]');
      // client-side courtesy checks (the server re-checks everything)
      if (!name || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email) || !msg || !/^\d{1,4}$/.test(sum)) {
        return; // let the browser's native required/validation + site.js handle it
      }
      // valid → take over: stop the mailto handler and post into the CMS
      ev.preventDefault();
      ev.stopImmediatePropagation();

      var company = val(form, '[name="company"]');
      var fd = new FormData();
      fd.append('name', name);
      fd.append('email', email);
      fd.append('phone', '');
      fd.append('subject', subjectOf(form));
      fd.append('message', msg + (company ? '\n\nCompany: ' + company : ''));
      fd.append('sum', sum);
      fd.append('_token', val(form, '[name="_token"]'));
      fd.append('company_website', val(form, '[name="company_website"]'));
      fd.append('_page', slug());

      var btn = form.querySelector('button[type="submit"]');
      if (btn) { btn.disabled = true; btn.dataset.lbl = btn.textContent; btn.textContent = 'Sending…'; }

      fetch('?capture=enquiry', { method: 'POST', body: fd, credentials: 'same-origin' })
        .then(function (r) { return r.json(); })
        .then(function (j) {
          if (j && j.ok) {
            var wrap = form.parentNode;
            form.style.display = 'none';
            var ok = document.createElement('div');
            ok.className = 'frm-ok';
            ok.setAttribute('tabindex', '-1');
            ok.innerHTML = '<h3>Thank you — your enquiry is in.<span class="aim" aria-hidden="true"></span></h3>'
              + '<p>We reply within one working day. For anything urgent, WhatsApp '
              + '<a href="https://wa.me/96590908625" target="_blank" rel="noopener">+965 9090 8625</a>.</p>';
            wrap.insertBefore(ok, form);
            ok.focus();
            ok.scrollIntoView({ behavior: 'smooth', block: 'center' });
            return;
          }
          if (btn) { btn.disabled = false; btn.textContent = btn.dataset.lbl || 'Send enquiry'; }
          var err = (j && j.err) || '';
          if (err === 'captcha') note(form, 'The quick-check answer doesn&rsquo;t match — please try again.', false);
          else if (err === 'rate') note(form, 'Too many messages from this connection. Please try again later, or WhatsApp <a href="https://wa.me/96590908625" target="_blank" rel="noopener">+965 9090 8625</a>.', false);
          else if (err === 'session') note(form, 'Your session expired — please reload the page and send again.', false);
          else note(form, 'Something went wrong. Please email <a href="mailto:info@expertaims.com">info@expertaims.com</a> or WhatsApp <a href="https://wa.me/96590908625" target="_blank" rel="noopener">+965 9090 8625</a>.', false);
        })
        .catch(function () {
          if (btn) { btn.disabled = false; btn.textContent = btn.dataset.lbl || 'Send enquiry'; }
          note(form, 'Couldn&rsquo;t reach the server. Email <a href="mailto:info@expertaims.com">info@expertaims.com</a> or WhatsApp <a href="https://wa.me/96590908625" target="_blank" rel="noopener">+965 9090 8625</a>.', false);
        });
    }, true); // capture phase — runs before site.js's bubble-phase mailto handler
  }

  function esc(s) {
    return String(s).replace(/[&<>"']/g, function (c) {
      return { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c];
    });
  }

  // Careers "Apply" modal → CMS applications inbox (+ email to careers@).
  // Maps the approved static form's fields onto the ?capture=application API,
  // uploads the CV, and shows a real (server-confirmed) success panel. Falls
  // through to the native/mailto flow if invalid or JS/network fails.
  function bindApply(form) {
    form.addEventListener('submit', function (ev) {
      var name = val(form, '[name="name"]');
      var email = val(form, '[name="email"]');
      var msg = val(form, '[name="msg"]');
      var sum = val(form, '[name="sum"]');
      if (!name || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email) || !msg || !/^\d{1,4}$/.test(sum)) {
        return; // let native validation + site.js/mailto handle it
      }
      ev.preventDefault();
      ev.stopImmediatePropagation();

      var role = val(form, '[name="company"]');
      if (!role) { var rl = document.getElementById('appRole'); role = rl ? rl.textContent.trim() : 'Open application'; }
      var work = val(form, '[name="msg2"]');
      var parts = name.split(/\s+/);
      var first = parts.shift() || name;
      var last = parts.join(' ') || '—';

      var fd = new FormData();
      fd.append('first_name', first);
      fd.append('last_name', last);
      fd.append('email', email);
      fd.append('phone', val(form, '[name="phone"]'));
      fd.append('job_title', role);
      fd.append('message', msg + (work ? '\n\nWork / portfolio: ' + work : ''));
      if (/^https?:\/\/(www\.|m\.)?(youtube\.com|youtu\.be)\//i.test(work)) fd.append('video_url', work);
      var cv = form.querySelector('[name="cv"]');
      if (cv && cv.files && cv.files[0]) fd.append('file_resume', cv.files[0]);
      fd.append('sum', sum);
      fd.append('_token', val(form, '[name="_token"]'));
      fd.append('company_website', val(form, '[name="company_website"]'));
      fd.append('_page', 'careers');

      var btn = form.querySelector('button[type="submit"]');
      if (btn) { btn.disabled = true; btn.dataset.lbl = btn.textContent; btn.textContent = 'Sending…'; }

      fetch('?capture=application', { method: 'POST', body: fd, credentials: 'same-origin' })
        .then(function (r) { return r.json(); })
        .then(function (j) {
          if (j && j.ok) {
            var wrap = form.parentNode;
            form.style.display = 'none';
            var ok = document.createElement('div');
            ok.className = 'frm-ok';
            ok.setAttribute('tabindex', '-1');
            ok.innerHTML = '<h3>Application received.<span class="aim" aria-hidden="true"></span></h3>'
              + '<p>Thanks, ' + esc(first) + ' — it&rsquo;s with our team. A person replies within a week, including the noes.</p>'
              + (j.filenote ? '<p style="color:var(--mut)">We couldn&rsquo;t attach your file — please email it to <a href="mailto:careers@expertaims.com">careers@expertaims.com</a>.</p>' : '');
            wrap.insertBefore(ok, form);
            ok.focus();
            ok.scrollIntoView({ behavior: 'smooth', block: 'center' });
            return;
          }
          if (btn) { btn.disabled = false; btn.textContent = btn.dataset.lbl || 'Send my application'; }
          var err = (j && j.err) || '';
          if (err === 'captcha') note(form, 'The quick-check answer doesn&rsquo;t match — please try again.', false);
          else if (err === 'filesize') note(form, 'That CV is too large (max 10&nbsp;MB). Attach a smaller file, or email it to <a href="mailto:careers@expertaims.com">careers@expertaims.com</a>.', false);
          else if (err === 'filetype') note(form, 'That file type isn&rsquo;t accepted — please attach a PDF or DOC/DOCX.', false);
          else if (err === 'rate') note(form, 'Too many applications from this connection. Please try later, or email <a href="mailto:careers@expertaims.com">careers@expertaims.com</a>.', false);
          else if (err === 'session' || err === 'blocked') note(form, 'Your session expired — please reload the page and apply again.', false);
          else note(form, 'Something went wrong. Please email <a href="mailto:careers@expertaims.com">careers@expertaims.com</a> directly.', false);
        })
        .catch(function () {
          if (btn) { btn.disabled = false; btn.textContent = btn.dataset.lbl || 'Send my application'; }
          note(form, 'Couldn&rsquo;t reach the server. Please email <a href="mailto:careers@expertaims.com">careers@expertaims.com</a> or WhatsApp <a href="https://wa.me/96590908625" target="_blank" rel="noopener">+965 9090 8625</a>.', false);
        });
    }, true); // capture phase — beats site.js's bubble-phase mailto handler
  }

  function init() {
    document.querySelectorAll('form[data-cms="enquiry"]').forEach(bind);
    document.querySelectorAll('form[data-cms="application"]').forEach(bindApply);
  }
  if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', init);
  else init();
})();
