(function ($) {
  function logLine(msg) {
    var $log = $('#sac-setup-log');
    if (!$log.length) return;
    var time = new Date().toLocaleTimeString();
    $log.append('<div style="margin:4px 0;"><strong>[' + time + ']</strong> ' + escapeHtml(msg) + '</div>');
    $log.scrollTop($log.prop('scrollHeight'));
  }

  function escapeHtml(str) {
    return String(str)
      .replace(/&/g, '&amp;')
      .replace(/</g, '&lt;')
      .replace(/>/g, '&gt;')
      .replace(/"/g, '&quot;')
      .replace(/'/g, '&#039;');
  }

  function setActions(html) {
    $('#sac-setup-actions').html(html || '');
  }

  function ajaxStep(step, runId) {
    setActions('');

    $.post(SAC_SETUP.ajax_url, {
      action: 'sac_setup_step',
      nonce: SAC_SETUP.nonce,
      step: step,
      run_id: runId || ''
    })
      .done(function (resp) {
        if (!resp || !resp.success) {
          var msg = (resp && resp.data && resp.data.message) ? resp.data.message : 'Unknown error.';
          logLine('❌ ' + msg);

          // ✅ Show backend details (WP_Error / HTTP code / body) if provided
          if (resp && resp.data && resp.data.details) {
            var d = resp.data.details;

            if (d.error) logLine('⚠️ Details: ' + d.error);
            if (d.code) logLine('ℹ️ HTTP Code: ' + d.code);

            if (d.body) {
              try {
                var json = JSON.parse(d.body);
                logLine('📦 Response Body: ' + JSON.stringify(json, null, 2));
              } catch (e) {
                logLine('📦 Response Body: ' + d.body);
              }
            }
          }

          setActions('<button class="button button-primary" id="sac-retry">Retry</button>');
          $('#sac-retry').on('click', function () {
            ajaxStep(step, runId);
          });
          return;
        }

        var data = resp.data || {};
        var newRunId = data.run_id || runId;
        logLine('✅ ' + (data.message || 'Step completed.'));

        // If the server says redirect to Settings
        if (data.needs_settings && data.redirect) {
          logLine('➡️ Redirecting…');
          window.location = data.redirect;
          return;
        }

        // If user must deactivate SEO plugins
        if (data.needs_user_action) {
          var plugins = (data.active_plugins || []).map(escapeHtml).join(', ');
          logLine('⚠️ Conflicting SEO plugins detected: ' + plugins);

          setActions(
            '<div style="padding:12px;border:1px solid #ddd;background:#fff;max-width:900px;">' +
              '<p><strong>Please deactivate these SEO plugins:</strong></p>' +
              '<p>' + plugins + '</p>' +
              '<p>After deactivating, click the button below.</p>' +
              '<button class="button button-primary" id="sac-check-again">I have deactivated them</button>' +
              '</div>'
          );

          $('#sac-check-again').on('click', function () {
            retryCheckPlugins();
          });

          return;
        }

        // Continue to next step
        if (data.next_step) {
          ajaxStep(data.next_step, newRunId);
          return;
        }

        // Done (rare in this flow)
        if (data.done) {
          logLine('🎉 Setup finished.');
          if (data.redirect) {
            window.location = data.redirect;
          }
          return;
        }

        // Fallback
        logLine('ℹ️ Setup response received.');
      })
      .fail(function (xhr) {
        logLine('❌ AJAX request failed. ' + (xhr && xhr.status ? ('HTTP ' + xhr.status) : ''));
        if (xhr && xhr.responseText) {
          logLine('📦 Server response: ' + xhr.responseText);
        }
        setActions('<button class="button button-primary" id="sac-retry">Retry</button>');
        $('#sac-retry').on('click', function () {
          ajaxStep(step, runId);
        });
      });
  }

  function retryCheckPlugins() {
    $.post(SAC_SETUP.ajax_url, {
      action: 'sac_retry_check_plugins',
      nonce: SAC_SETUP.nonce
    })
      .done(function (resp) {
        if (!resp || !resp.success) {
          logLine('❌ Could not re-check plugins. Try again.');
          return;
        }

        var data = resp.data || {};
        if (!data.ok) {
          var plugins = (data.active_plugins || []).join(', ');
          logLine('⚠️ Still active: ' + plugins);
          return;
        }

        logLine('✅ No conflicting SEO plugins detected.');
        if (data.redirect) {
          logLine('➡️ Redirecting to Settings…');
          window.location = data.redirect;
        }
      })
      .fail(function () {
        logLine('❌ Plugin re-check failed due to network/server error.');
      });
  }

  $(function () {
    if (typeof SAC_SETUP === 'undefined') return;
    logLine('Starting setup…');
    ajaxStep(0, '');
  });
})(jQuery);
