(function () {
  'use strict';

  var cfg = typeof window.neurogenesisThemeDashboard === 'object' && window.neurogenesisThemeDashboard ? window.neurogenesisThemeDashboard : {};

  var statusClasses = {
    not_installed: ['bg-slate-200', 'text-slate-600'],
    inactive: ['bg-amber-100', 'text-amber-800'],
    active: ['bg-emerald-100', 'text-emerald-800'],
  };

  function applyStatusBadge(badge, status, label) {
    if (!badge) {
      return;
    }

    badge.textContent = label || badge.textContent;
    badge.classList.remove(
      'bg-slate-200',
      'text-slate-600',
      'bg-amber-100',
      'text-amber-800',
      'bg-emerald-100',
      'text-emerald-800'
    );

    var classes = statusClasses[status] || statusClasses.not_installed;
    classes.forEach(function (cls) {
      badge.classList.add(cls);
    });
  }

  function setActionLabel(button, label) {
    if (!button) {
      return;
    }

    var icon = button.querySelector('svg');
    button.textContent = '';
    button.appendChild(document.createTextNode(label));

    if (icon) {
      button.appendChild(icon);
    }
  }

  function installRecommendedPlugin() {
    if (!cfg.ajaxUrl || !cfg.nonce) {
      return Promise.reject(new Error((cfg.i18n && cfg.i18n.error) || 'Installation failed.'));
    }

    var formData = new FormData();
    formData.append('action', 'neurogenesis_theme_install_recommended_plugin');
    formData.append('nonce', cfg.nonce);

    return fetch(cfg.ajaxUrl, {
      method: 'POST',
      body: formData,
      credentials: 'same-origin',
    })
      .then(function (response) {
        return response.json();
      })
      .then(function (payload) {
        if (!payload || !payload.success) {
          var message =
            payload && payload.data && payload.data.message
              ? payload.data.message
              : (cfg.i18n && cfg.i18n.error) || 'Installation failed.';
          throw new Error(message);
        }

        return payload.data || {};
      });
  }

  function updateRecommendedPluginCard(data) {
    var button = document.getElementById('neurogenesis-theme-install-recommended-plugin');
    var statusBadge = document.getElementById('neurogenesis-theme-recommended-plugin-status');
    var i18n = cfg.i18n || {};

    if (statusBadge && data.status_label) {
      applyStatusBadge(statusBadge, data.status, data.status_label);
    }

    if (!button) {
      return;
    }

    if (data.status === 'active') {
      var success = document.createElement('span');
      success.className = 'neurogenesis-theme-dashboard-card__active';
      success.textContent = i18n.active || 'Active';
      button.replaceWith(success);
      return;
    }

    if (data.status === 'inactive') {
      button.disabled = false;
      setActionLabel(button, data.action_label || i18n.activate || 'Activate');
      if (data.message) {
        window.alert(data.message);
      }
    }
  }

  function formatStepsCompleted(completed, total) {
    var template = (cfg.i18n && cfg.i18n.stepsCompleted) || '%1$d of %2$d steps completed';
    return template.replace('%1$d', String(completed)).replace('%2$d', String(total));
  }

  function updateQuickSetupProgress() {
    var steps = document.querySelectorAll('.neurogenesis-theme-dashboard-quick-setup__step');
    var total = steps.length;
    var completed = document.querySelectorAll('.neurogenesis-theme-dashboard-quick-setup__step-link--completed').length;
    var percent = total > 0 ? Math.round((completed / total) * 100) : 0;
    var subtitle = document.querySelector('.neurogenesis-theme-dashboard-quick-setup__subtitle');
    var percentEl = document.querySelector('.neurogenesis-theme-dashboard-quick-setup__percent');
    var progress = document.querySelector('.neurogenesis-theme-dashboard-quick-setup__progress');
    var progressBar = document.querySelector('.neurogenesis-theme-dashboard-quick-setup__progress-bar');

    if (subtitle) {
      subtitle.textContent = formatStepsCompleted(completed, total);
    }

    if (percentEl) {
      percentEl.textContent = String(percent) + '%';
    }

    if (progress) {
      progress.setAttribute('aria-valuenow', String(percent));
    }

    if (progressBar) {
      progressBar.style.width = String(percent) + '%';
    }
  }

  function markQuickSetupStepCompleted(stepItem) {
    var control = stepItem.querySelector('[data-neurogenesis-theme-quick-setup-action]');
    if (!control) {
      return;
    }

    var icon = stepItem.querySelector('.neurogenesis-theme-dashboard-quick-setup__step-icon');
    var replacement = document.createElement('span');
    replacement.className = control.className + ' neurogenesis-theme-dashboard-quick-setup__step-link--completed';

    if (icon) {
      icon.classList.add('neurogenesis-theme-dashboard-quick-setup__step-icon--completed');
      if (cfg.checkIconHtml) {
        icon.innerHTML = cfg.checkIconHtml;
      }
    }

    replacement.innerHTML = control.innerHTML;
    control.replaceWith(replacement);
    updateQuickSetupProgress();
  }

  function setQuickSetupStepLoading(control, loading) {
    var stepItem = control.closest('.neurogenesis-theme-dashboard-quick-setup__step');
    var label = stepItem ? stepItem.querySelector('.neurogenesis-theme-dashboard-quick-setup__step-label') : null;
    var i18n = cfg.i18n || {};

    if (!control.dataset.defaultLabel && label) {
      control.dataset.defaultLabel = label.textContent.trim();
    }

    control.disabled = loading;

    if (label) {
      label.textContent = loading ? i18n.installing || 'Installing…' : control.dataset.defaultLabel || label.textContent;
    }
  }

  function setStartBuildingBusy(cta, busy, label) {
    if (!cta) {
      return;
    }

    if (busy) {
      cta.setAttribute('aria-busy', 'true');
      cta.classList.add('is-busy');
      if (label) {
        cta.dataset.originalLabel = cta.textContent;
        cta.textContent = label;
      }
      return;
    }

    cta.removeAttribute('aria-busy');
    cta.classList.remove('is-busy');
    if (cta.dataset.originalLabel) {
      cta.textContent = cta.dataset.originalLabel;
      delete cta.dataset.originalLabel;
    }
  }

  function bindStartBuildingCta() {
    var cta = document.querySelector('[data-start-building-cta]');
    if (!cta) {
      return;
    }

    cta.addEventListener('click', function (event) {
      var status = cta.getAttribute('data-plugin-status') || 'not_installed';
      var i18n = cfg.i18n || {};

      if (status === 'active') {
        return;
      }

      event.preventDefault();

      if (cta.getAttribute('aria-busy') === 'true') {
        return;
      }

      var busyLabel = status === 'inactive' ? i18n.activating || 'Activating…' : i18n.installing || 'Installing…';
      setStartBuildingBusy(cta, true, busyLabel);

      installRecommendedPlugin()
        .then(function (data) {
          updateRecommendedPluginCard(data);
          // Prefer post-activation URLs from AJAX (admin.php once the plugin owns the menu).
          window.location.href =
            data.redirect_url ||
            data.dashboard_url ||
            cfg.importUrl ||
            cfg.dashboardUrl ||
            cta.getAttribute('href') ||
            window.location.href;
        })
        .catch(function (error) {
          setStartBuildingBusy(cta, false);
          window.alert(error && error.message ? error.message : i18n.error || 'Installation failed.');
        });
    });
  }

  document.addEventListener('DOMContentLoaded', function () {
    var i18n = cfg.i18n || {};
    var button = document.getElementById('neurogenesis-theme-install-recommended-plugin');

    bindStartBuildingCta();

    if (button && cfg.ajaxUrl && cfg.nonce) {
      button.addEventListener('click', function () {
        if (button.disabled) {
          return;
        }

        var defaultLabel = button.firstChild ? button.firstChild.textContent.trim() : button.textContent.trim();
        button.disabled = true;
        setActionLabel(button, i18n.installing || 'Installing…');

        installRecommendedPlugin()
          .then(function (data) {
            updateRecommendedPluginCard(data);

            if (data.status !== 'active') {
              button.disabled = false;
              setActionLabel(button, data.action_label || defaultLabel);
            }
          })
          .catch(function (error) {
            button.disabled = false;
            setActionLabel(button, defaultLabel);
            window.alert(error && error.message ? error.message : i18n.error || 'Installation failed.');
          });
      });
    }

    document.querySelectorAll('[data-neurogenesis-theme-quick-setup-action="install_recommended_plugin"]').forEach(function (control) {
      control.addEventListener('click', function () {
        if (control.disabled) {
          return;
        }

        setQuickSetupStepLoading(control, true);

        installRecommendedPlugin()
          .then(function (data) {
            updateRecommendedPluginCard(data);

            if (data.status === 'active') {
              var stepItem = control.closest('.neurogenesis-theme-dashboard-quick-setup__step');
              if (stepItem) {
                markQuickSetupStepCompleted(stepItem);
              }
              return;
            }

            setQuickSetupStepLoading(control, false);

            if (data.message) {
              window.alert(data.message);
            }
          })
          .catch(function (error) {
            setQuickSetupStepLoading(control, false);
            window.alert(error && error.message ? error.message : i18n.error || 'Installation failed.');
          });
      });
    });
  });
})();
