/**
 * Global Admin Banner JavaScript
 *
 * Handles trial start from the global admin banners and dashboard widget.
 */

(function ($) {
  'use strict';

  /**
   * Initialize global banner functionality.
   */
  function initGlobalBanner() {
    // Handle "Start Free Trial" button click on global banners
    $(document).on('click', '.saiap-global-banner .saiap-start-trial-btn', handleStartTrial);

    // Handle "Start Free Trial" button click on dashboard widget
    $(document).on('click', '.saiap-widget .saiap-start-trial-btn', handleStartTrial);

    // Handle banner dismissal
    $(document).on('click', '.saiap-global-banner .notice-dismiss', handleDismiss);
  }

  /**
   * Handle the Start Trial button click.
   *
   * @param {Event} e Click event.
   */
  function handleStartTrial(e) {
    e.preventDefault();
    e.stopPropagation(); // Prevent event bubbling

    var $btn = $(this);
    var originalText = $btn.text();

    // Check if saiapGlobalBanner is available
    if (typeof saiapGlobalBanner === 'undefined') {
      console.error('saiapGlobalBanner not defined');
      alert('Configuration error. Please refresh the page.');
      return;
    }

    // Disable button and show loading state
    $btn.prop('disabled', true).text('Starting trial...');

    $.ajax({
      url: saiapGlobalBanner.ajaxurl,
      type: 'POST',
      data: {
        action: 'saiap_start_trial',
        nonce: saiapGlobalBanner.trialNonce,
        email: saiapGlobalBanner.adminEmail || ''
      },
      success: function (response) {
        if (response.success) {
          // Check if wizard should be shown (empty site)
          if (response.data && response.data.show_wizard) {
            // Show the onboarding wizard instead of redirecting
            $btn.prop('disabled', false).text(originalText);
            if (typeof window.saiapShowOnboardingWizard === 'function') {
              window.saiapShowOnboardingWizard();
            } else {
              // Wizard JS not loaded on this page — redirect to plugin dashboard
              window.location.href = 'admin.php?page=saiap&tab=dashboard&trial_started=1';
            }
            return;
          }

          // Success! Redirect to Dashboard with trial_started flag for tracking consent
          window.location.href = 'admin.php?page=saiap&tab=dashboard&trial_started=1';
        } else {
          // Show error message
          var message =
            response.data && response.data.message
              ? response.data.message
              : 'Failed to start trial. Please try again.';

          alert(message);
          $btn.prop('disabled', false).text(originalText);
        }
      },
      error: function () {
        alert('Network error. Please check your connection and try again.');
        $btn.prop('disabled', false).text(originalText);
      }
    });
  }

  /**
   * Handle banner dismissal.
   */
  function handleDismiss(e) {
    var $banner = $(this).closest('.saiap-global-banner');
    var scenario = $banner.data('scenario');

    // For upgrade scenarios, also dismiss via AJAX to persist
    if (scenario === 'no_trial_has_keys') {
      $.ajax({
        url: saiapGlobalBanner.ajaxurl,
        type: 'POST',
        data: {
          action: 'saiap_dismiss_global_banner',
          nonce: saiapGlobalBanner.trialNonce
        }
      });
    }
  }

  // Initialize when DOM is ready
  $(document).ready(initGlobalBanner);
})(jQuery);

