jQuery(function($){
    // API key validation
    $('#myaio-validate-key-btn').on('click', function(){
      $('#myaio-validate-key-result').text('Validating…');
      $.post(MYAIO.ajaxUrl, {
        action: 'myaio_validate_api_key',
        nonce: MYAIO.nonce
      }).done(function(res){
        if(res.success){
          $('#myaio-validate-key-result').text(res.data.message);
          if(res.data.redirect) window.location = res.data.redirect;
        } else {
          $('#myaio-validate-key-result').text(res.data && res.data.message ? res.data.message : 'Validation failed.');
        }
      });
    });
  
    function runSetupStep(){
      var $wrap = $('#myaio-setup-status');
      var runId = $wrap.data('runid');
      $('#myaio-progress-text').text('Running…');
  
      $.post(MYAIO.ajaxUrl, {
        action: 'myaio_setup_step',
        nonce: MYAIO.nonce,
        runId: runId
      }).done(function(res){
        if(!res.success){
          $('#myaio-progress-text').text(res.data && res.data.message ? res.data.message : 'Error.');
          return;
        }
  
        if(res.data.blocked){
          $('#myaio-progress-text').text(res.data.message);
          $('#myaio-blocked-plugins-list').empty();
          (res.data.blockedPlugins || []).forEach(function(p){
            $('#myaio-blocked-plugins-list').append('<li><code>' + p.plugin + '</code> — ' + p.name + '</li>');
          });
          $('#myaio-blocked-plugins').show();
          return;
        }
  
        $('#myaio-blocked-plugins').hide();
  
        if(res.data.done){
          $('#myaio-progress-text').text(res.data.message);
          if(res.data.redirect) window.location = res.data.redirect;
          return;
        }
  
        $('#myaio-progress-text').text(res.data.message);
        // Keep stepping while page is open
        setTimeout(runSetupStep, 300);
      });
    }
  
    $('#myaio-start-setup-btn').on('click', function(){
      runSetupStep();
    });
  
    $('#myaio-retry-check-btn').on('click', function(){
      $.post(MYAIO.ajaxUrl, {
        action: 'myaio_retry_check_plugins',
        nonce: MYAIO.nonce
      }).done(function(res){
        if(res.success && res.data.ok){
          if(res.data.redirect) window.location = res.data.redirect;
          return;
        }
        // still blocked
        $('#myaio-blocked-plugins-list').empty();
        (res.data.blockedPlugins || []).forEach(function(p){
          $('#myaio-blocked-plugins-list').append('<li><code>' + p.plugin + '</code> — ' + p.name + '</li>');
        });
      });
    });
  
    $('#myaio-view-log-btn').on('click', function(){
      alert('Progress JSON is stored in: wp-content/plugins/myaio/storage/snapshots/<runId>/progress.json');
    });
  });
  