/* ==================================================
   Nuclear Fancy Pants Edition™ -- NUCLEAR+++
   File: /assets/public/js/get-started.js
   Description: Onboarding wizard JS for AutoMarketer AI get-started page
   Last Edited: 2026-04-28
   ================================================== */
(function () {
  'use strict';

  var TOTAL_STEPS = 2;
  var currentStep = 1;

  function qs(sel) { return document.querySelector(sel); }
  function qsa(sel) { return document.querySelectorAll(sel); }

  var form      = qs('#amai-wizard-form');
  var errorBox  = qs('#amai-wizard-error');
  var nextBtn   = qs('#amai-wizard-next');
  var backBtn   = qs('#amai-wizard-back');
  var stepDots  = qsa('.amai-wizard__step-dot');
  var stepLines = qsa('.amai-wizard__step-line');
  var steps     = qsa('.amai-wizard__step');

  function escHtml(s) {
    return String(s)
      .replace(/&/g, '&amp;')
      .replace(/</g, '&lt;')
      .replace(/>/g, '&gt;')
      .replace(/"/g, '&quot;');
  }

  function showError(msg) {
    errorBox.textContent = msg;
    errorBox.classList.add('is-visible');
  }

  function clearError() {
    errorBox.textContent = '';
    errorBox.classList.remove('is-visible');
  }

  function validateCurrentStep() {
    clearError();

    if (currentStep === 1) {
      var firstName = (qs('[name="first_name"]') || {}).value || '';
      var email     = (qs('[name="email"]') || {}).value || '';
      if (!firstName.trim()) { showError('Please enter your first name.'); return false; }
      if (!email.trim() || !email.includes('@')) { showError('Please enter a valid email address.'); return false; }
      return true;
    }

    if (currentStep === 2) {
      var bizName = (qs('[name="business_name"]') || {}).value || '';
      var website = (qs('[name="website"]') || {}).value || '';
      var desc    = (qs('[name="business_desc"]') || {}).value || '';
      if (!bizName.trim()) { showError('Please enter your business name.'); return false; }
      if (!website.trim()) { showError('Please enter your website URL.'); return false; }
      if (!desc.trim())    { showError('Please briefly describe your business.'); return false; }
      return true;
    }

    return true;
  }

  function goToStep(n) {
    steps.forEach(function (s, i) {
      s.classList.toggle('is-active', i + 1 === n);
    });
    stepDots.forEach(function (dot, i) {
      dot.classList.remove('amai-wizard__step-dot--active', 'amai-wizard__step-dot--done');
      if (i + 1 < n)  { dot.classList.add('amai-wizard__step-dot--done'); }
      if (i + 1 === n) { dot.classList.add('amai-wizard__step-dot--active'); }
    });
    stepLines.forEach(function (line, i) {
      line.classList.toggle('amai-wizard__step-line--done', i + 1 < n);
    });
    backBtn.style.visibility = n === 1 ? 'hidden' : 'visible';
    nextBtn.textContent = n === TOTAL_STEPS ? 'Finish' : 'Continue';
    currentStep = n;
    clearError();
    window.scrollTo(0, 0);
  }

  nextBtn.addEventListener('click', function () {
    if (!validateCurrentStep()) { return; }
    if (currentStep === 1) {
      submitStep(1, function () { goToStep(2); });
    } else if (currentStep === 2) {
      submitStep(2, function () {
        var plan    = (amaiWizard.selectedPlan || '').trim();
        var billing = (amaiWizard.selectedBilling || 'yearly').trim();
        if (plan && plan !== 'free') {
          nextBtn.disabled = true;
          nextBtn.innerHTML = '<span class="amai-wizard__spinner"></span>Setting up billing...';
          var d = new FormData();
          d.append('action',      'amai_wizard_checkout');
          d.append('_ajax_nonce', amaiWizard.nonceCheckout);
          d.append('plan',        plan);
          d.append('billing',     billing);
          fetch(amaiWizard.ajaxUrl, { method: 'POST', body: d })
            .then(function (r) { return r.json(); })
            .then(function (res) {
              if (res.success && res.data && res.data.url) {
                window.location.href = res.data.url;
              } else {
                nextBtn.disabled = false;
                nextBtn.textContent = 'Finish';
                showError('Could not start checkout. Please try again or contact support.');
              }
            })
            .catch(function () {
              nextBtn.disabled = false;
              nextBtn.textContent = 'Finish';
              showError('Connection error. Please try again.');
            });
        } else {
          window.location.href = amaiWizard.setupUrl;
        }
      });
    }
  });

  backBtn.addEventListener('click', function () {
    if (currentStep > 1) { goToStep(currentStep - 1); }
  });

  function submitStep(step, onSuccess) {
    nextBtn.disabled = true;
    nextBtn.innerHTML = '<span class="amai-wizard__spinner"></span>Saving...';

    var data = new FormData(form);
    data.append('action',      'amai_wizard_step');
    data.append('_ajax_nonce', amaiWizard.nonceStep);
    data.append('step',        String(step));

    fetch(amaiWizard.ajaxUrl, { method: 'POST', body: data })
      .then(function (r) { return r.json(); })
      .then(function (res) {
        nextBtn.disabled = false;
        nextBtn.textContent = step < TOTAL_STEPS ? 'Continue' : 'Finish';
        if (res.success) {
          if (step === 1) {
            fetch(amaiWizard.ajaxUrl, {
              method: 'POST',
              body: (function () { var d = new FormData(); d.append('action', 'amai_wizard_nonces'); return d; }())
            }).then(function (r) { return r.json(); }).then(function (nr) {
              if (nr.success && nr.data) {
                amaiWizard.nonceStep = nr.data.nonceStep;
              }
              onSuccess();
            }).catch(function () { onSuccess(); });
          } else {
            onSuccess();
          }
        } else {
          showError(res.data && res.data.message ? res.data.message : 'Something went wrong. Please try again.');
        }
      })
      .catch(function () {
        nextBtn.disabled = false;
        nextBtn.textContent = step < TOTAL_STEPS ? 'Continue' : 'Finish';
        showError('Connection error. Please try again.');
      });
  }

  goToStep(parseInt(amaiWizard.currentStep, 10) || 1);

}());