/* ==================================================
   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-27
   ================================================== */
(function () {
  'use strict';

  var TOTAL_STEPS = 5;
  var currentStep = 1;
  var validatedAiKey = false;
  var validatedImgKey = false;

  // -- DOM refs --
  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');

  // -- Provider selection --
  qsa('.amai-wizard__provider').forEach(function (card) {
    card.addEventListener('click', function () {
      var radio   = card.querySelector('input[type="radio"]');
      var group   = card.closest('.amai-wizard__providers');
      if (!radio || !group) { return; }
      group.querySelectorAll('.amai-wizard__provider').forEach(function (c) {
        c.classList.remove('is-selected');
      });
      card.classList.add('is-selected');
      radio.checked = true;
      // Reset validation state when provider changes
      var stepEl = card.closest('.amai-wizard__step');
      if (stepEl) {
        var statusEl = stepEl.querySelector('.amai-wizard__key-status');
        var keyInput = stepEl.querySelector('.amai-wizard__input[name="ai_key"], .amai-wizard__input[name="img_key"]');
        if (statusEl) { statusEl.innerHTML = ''; statusEl.className = 'amai-wizard__key-status'; }
        if (keyInput) { keyInput.value = ''; keyInput.classList.remove('is-error'); }
        if (stepEl.id === 'amai-step-3') { validatedAiKey = false; }
        if (stepEl.id === 'amai-step-4') { validatedImgKey = false; }
      }
    });
  });

  // -- Validate key buttons --
  function wireValidateBtn(stepId, keyName, nonceName, action, validatedFlag) {
    var stepEl  = qs('#' + stepId);
    if (!stepEl) { return; }
    var btn     = stepEl.querySelector('.amai-wizard__validate-btn');
    var input   = stepEl.querySelector('.amai-wizard__input[name="' + keyName + '"]');
    var status  = stepEl.querySelector('.amai-wizard__key-status');
    if (!btn || !input || !status) { return; }

    btn.addEventListener('click', function () {
      var key      = input.value.trim();
      var radio    = stepEl.querySelector('input[type="radio"]:checked');
      var provider = radio ? radio.value : '';

      if (!key || !provider) {
        showStatus(status, 'error', 'Select a provider and enter your API key.');
        return;
      }

      btn.disabled = true;
      btn.textContent = 'Checking...';
      status.innerHTML = '';
      status.className = 'amai-wizard__key-status';

      var nonce  = amaiWizard[nonceName] || '';
      var data   = new FormData();
      data.append('action',      action);
      data.append('_ajax_nonce', nonce);
      data.append('provider_id', provider);
      data.append('api_key',     key);

      fetch(amaiWizard.ajaxUrl, { method: 'POST', body: data })
        .then(function (r) { return r.json(); })
        .then(function (res) {
          btn.disabled = false;
          btn.textContent = 'Validate';
          if (res.success) {
            showStatus(status, 'ok', 'Key validated successfully.');
            input.classList.remove('is-error');
            if (keyName === 'ai_key')  { validatedAiKey  = true; }
            if (keyName === 'img_key') { validatedImgKey = true; }
          } else {
            showStatus(status, 'error', res.data && res.data.message ? res.data.message : 'Invalid key. Please check and try again.');
            input.classList.add('is-error');
            if (keyName === 'ai_key')  { validatedAiKey  = false; }
            if (keyName === 'img_key') { validatedImgKey = false; }
          }
        })
        .catch(function () {
          btn.disabled = false;
          btn.textContent = 'Validate';
          showStatus(status, 'error', 'Connection error. Please try again.');
        });
    });
  }

  wireValidateBtn('amai-step-3', 'ai_key',  'nonceValidateAi',  'amai_wizard_validate_ai',  'validatedAiKey');
  wireValidateBtn('amai-step-4', 'img_key', 'nonceValidateImg', 'amai_wizard_validate_img', 'validatedImgKey');

  function showStatus(el, type, msg) {
    el.className = 'amai-wizard__key-status amai-wizard__key-status--' + type;
    el.innerHTML = '<span class="amai-wizard__key-status-dot"></span>' + escHtml(msg);
  }

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

  // -- Navigation --
  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;
    }

    if (currentStep === 3) {
      var aiRadio = qs('#amai-step-3 input[type="radio"]:checked');
      var aiKey   = (qs('[name="ai_key"]') || {}).value || '';
      if (!aiRadio) { showError('Please select an AI writing provider.'); return false; }
      if (!aiKey.trim()) { showError('Please enter your API key.'); return false; }
      if (!validatedAiKey) { showError('Please validate your API key before continuing.'); return false; }
      return true;
    }

    if (currentStep === 4) {
      var imgRadio = qs('#amai-step-4 input[type="radio"]:checked');
      var imgKey   = (qs('[name="img_key"]') || {}).value || '';
      if (!imgRadio) { showError('Please select an AI image provider.'); return false; }
      if (!imgKey.trim()) { showError('Please enter your API key.'); return false; }
      if (!validatedImgKey) { showError('Please validate your API key before continuing.'); 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';
    if (n === TOTAL_STEPS) {
      nextBtn.textContent = 'Connect Facebook';
    } else {
      nextBtn.textContent = 'Continue';
    }
    currentStep = n;
    clearError();
    window.scrollTo(0, 0);
  }

  nextBtn.addEventListener('click', function () {
    if (!validateCurrentStep()) { return; }

    if (currentStep < TOTAL_STEPS) {
      // Steps 1-2: POST to server to persist data before advancing
      if (currentStep === 1 || currentStep === 2) {
        submitStep(currentStep, function () { goToStep(currentStep + 1); });
      } else if (currentStep === 3) {
        submitStep(3, function () { goToStep(4); });
      } else if (currentStep === 4) {
        submitStep(4, function () { goToStep(5); });
      } else {
        goToStep(currentStep + 1);
      }
    } else {
      // Step 5: go to Facebook connect
      window.location.href = amaiWizard.fbConnectUrl;
    }
  });

  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 - 1 ? 'Continue' : (step === TOTAL_STEPS - 1 ? 'Connect Facebook' : 'Continue');
        if (res.success) {
          onSuccess();
        } else {
          showError(res.data && res.data.message ? res.data.message : 'Something went wrong. Please try again.');
        }
      })
      .catch(function () {
        nextBtn.disabled = false;
        nextBtn.textContent = 'Continue';
        showError('Connection error. Please try again.');
      });
  }

  // -- Init --
  goToStep(amaiWizard.currentStep || 1);

}());