jQuery(document).ready(function($) {
  const $form = $('#lockee-migration-form');
  const $progress = $('#lockee-migration-progress');
  const $progressBar = $progress.find('.progress-bar-fill');
  const $progressText = $progress.find('.progress-bar-text');
  const $progressMessage = $progress.find('.progress-message');
  const $buttons = $('.lockee-migrate-action');
  const $forms = $('.lockee-migrate-form');
  let progressInterval;

  function updateProgress() {
    $progress.show();
    $.ajax({
      url: lockeeMigration.ajaxurl,
      type: 'POST',
      data: {
        action: 'lockee_migration_progress',
        nonce: lockeeMigration.nonce
      },
      success: function(response) {
        if (!response.success) {
          clearInterval(progressInterval);
          $progressMessage.text(lockeeMigration.i18n.error);
          $buttons.prop('disabled', false);
          return;
        }

        const progress = response.data;
        
        if (progress.status === 'not_started') {
          return;
        }

        if (progress.status === 'error') {
          clearInterval(progressInterval);
          $progressMessage.text(progress.message);
          $buttons.prop('disabled', false);
          return;
        }

        if (progress.status === 'completed') {
          $progressBar.css('width', '100%');
          $progressText.text('100%');
          $progressMessage.text(progress.message);
           setTimeout(function() {
            window.location.reload();
          }, 2000);
          return;
        }

        if (progress.status === 'progress') {
          const percent = progress.total > 0 ? Math.round((progress.current / progress.total) * 100) : 0;
          $progressBar.css('width', percent + '%');
          $progressText.text(percent + '%');
          $progressMessage.text(progress.message);
        }
      },
      error: function() {
        clearInterval(progressInterval);
        $progressMessage.text(lockeeMigration.i18n.error);
        $buttons.prop('disabled', false);
      }
    });
  }

  $forms.on('submit', function(e) {
    e.preventDefault();
    $buttons.prop('disabled', true);
    $progress.show();
    $progressBar.css('width', '0%');
    $progressText.text('0%');
    $progressMessage.text(lockeeMigration.i18n.migrating);

    progressInterval = setInterval(updateProgress, 1000);

    $.ajax({
      url: window.location.href,
      type: 'POST',
      data: $(this).serialize()
    });
  });

  if(lockeeMigrationReload) {
    $buttons.prop('disabled', true);
    progressInterval = setInterval(updateProgress, 1000);
  }
});