jQuery(document).ready(function () {
    jQuery('#new_account_btn').click(function() {
      jQuery('#integrazo-wz-select_account_section').hide();
      jQuery('#integrazo-wz-new_account_name').show();
      jQuery('#integrazo-wz-new_account_fields').slideDown();
      jQuery('.integrazo-wz-setup-step2-save-btn').hide();
      jQuery('#step2_auth').parent('div').show();
  });
  // -------------------------------------------------------- Common
  var urlParams = new URLSearchParams(window.location.search);
  var step = (typeof integrazo_wz_setup !== 'undefined' && integrazo_wz_setup.current_step)
    ? String(integrazo_wz_setup.current_step)
    : urlParams.get('step');

  function integrazoWzSetToggleState(header, isOpen) {
    var label = isOpen ? 'Click to close' : 'Click to expand';
    header.find('.integrazo-wz-setup-toggle-icon').text(isOpen ? '−' : '+').attr('title', label);
    header.find('.integrazo-wz-setup-toggle-hint').text(label);
  }

  if (step === '2') {
    jQuery('#step2 .integrazo-wz-setup-accordion-content').slideDown();
    integrazoWzSetToggleState(jQuery('#step2 .integrazo-wz-setup-accordion-header'), true);
  } else if (step === '3') {
    jQuery('#step3 .integrazo-wz-setup-accordion-content').slideDown();
    integrazoWzSetToggleState(jQuery('#step3 .integrazo-wz-setup-accordion-header'), true);
  } else if (step === '4') {
    // Fully configured — leave every section collapsed; the +/- icons are
    // already rendered correctly server-side, no JS override needed here.
  } else {
    jQuery('#step1 .integrazo-wz-setup-accordion-content').slideDown();
    integrazoWzSetToggleState(jQuery('#step1 .integrazo-wz-setup-accordion-header'), true);
  }

  jQuery('.integrazo-wz-setup-accordion-header').on('click', function () {
    var header = jQuery(this);
    var content = header.next('.integrazo-wz-setup-accordion-content');

    if (content.is(':visible')) {
      content.slideUp();
      integrazoWzSetToggleState(header, false);
    } else {
      jQuery('.integrazo-wz-setup-accordion-content').slideUp();
      jQuery('.integrazo-wz-setup-accordion-header').each(function () {
        integrazoWzSetToggleState(jQuery(this), false);
      });
      content.slideDown();
      integrazoWzSetToggleState(header, true);
    }
  });

  // Keep exactly one Step 1 card highlighted as "do this next": the trigger until it's
  // picked, then the destination. A card that isn't its turn yet is dimmed instead.
  function integrazoWzRefreshStep1Attention() {
    var hasPlugin  = String(jQuery('input[name="from_plugin"]').val() || '').trim() !== '';
    var hasProduct = String(jQuery('input[name="to_product"]').val() || '').trim() !== '';
    var $trigger   = jQuery('[data-target="#integrazo-wz-plugin-popup"]');
    var $dest      = jQuery('[data-target="#integrazo-wz-product-popup"]');

    jQuery('.integrazo-wz-setup-step1-box')
      .removeClass('integrazo-wz-setup-step1-box-attention integrazo-wz-setup-step1-box-waiting');

    // A card holding a service goes solid-bordered; the empty ones stay dashed.
    $trigger.toggleClass('integrazo-wz-setup-step1-box-filled', hasPlugin);
    $dest.toggleClass('integrazo-wz-setup-step1-box-filled', hasProduct);

    if (!hasPlugin) {
      $trigger.addClass('integrazo-wz-setup-step1-box-attention');
      if (!hasProduct) {
        $dest.addClass('integrazo-wz-setup-step1-box-waiting');
      }
    } else if (!hasProduct) {
      $dest.addClass('integrazo-wz-setup-step1-box-attention');
    }
  }

  // -------------------------------------------------------- Step 1: tile select (plugin/product)
// Works for BOTH free (.integrazo-wz-setup-step1-plugin-item) and pro (.integrazo-wz-pro-plugin).
// Pro tiles are treated as disabled: no selection action.
jQuery(document).on('click', '[data-group="plugin"], [data-group="product"]', function () {
  var $tile = jQuery(this);

  // ⛔ Show PRO upgrade popup for pro tiles
  if ($tile.hasClass('integrazo-wz-pro-plugin')) {
    var proName = String($tile.attr('data-name') || $tile.find('.integrazo-wz-setup-step1-plugin-title').text() || '');
    integrazoWzShowProPopup(proName);
    return;
  }

  var group     = String($tile.attr('data-group')  || '');
  var name      = String($tile.attr('data-name')   || '');
  var plugin_id = String($tile.attr('data-id')     || '');
  var source    = String($tile.attr('data-source') || '');

  // Set hidden input values
  if (source === 'from') {
    jQuery('input[name="from_plugin"]').val(plugin_id);
  } else {
    jQuery('input[name="to_product"]').val(plugin_id);
  }

  // Update selection highlight
  jQuery('[data-group="' + group + '"]').removeClass('selected');
  $tile.addClass('selected');

  // Update main selection box: rebuild it to match the "selected" state (thumb + name +
  // Connected status), replacing the empty-state badge/description/CTA button. It stays
  // clickable (expand-toggle + data-target) so the user can still change it before saving —
  // it only becomes permanently locked once the integration is actually saved (server-rendered).
  var $box = (group === 'plugin')
    ? jQuery('[data-target="#integrazo-wz-plugin-popup"]')
    : jQuery('[data-target="#integrazo-wz-product-popup"]');

  $box.removeClass('integrazo-wz-setup-step1-box-attention');
  $box.attr('title', 'Click to change');
  $box.empty();
  jQuery('<div/>', { 'class': 'integrazo-wz-setup-step1-plugin-thumb ' + plugin_id }).appendTo($box);
  jQuery('<span/>', { 'class': 'integrazo-wz-setup-step1-plugin-title', text: name }).appendTo($box);
  var $status = jQuery('<span/>', { 'class': 'integrazo-wz-setup-step1-status integrazo-wz-setup-step1-status-connected' }).appendTo($box);
  jQuery('<span/>', { 'class': 'dashicons dashicons-yes-alt', 'aria-hidden': 'true' }).appendTo($status);
  $status.append(document.createTextNode(' Connected'));

  // Re-check whether both sides are now selected, and enable Save and Next once they are.
  var bothSelected = String(jQuery('input[name="from_plugin"]').val() || '').trim() !== ''
    && String(jQuery('input[name="to_product"]').val() || '').trim() !== '';
  if (bothSelected) {
    jQuery('#step1_next').prop('disabled', false);
  }

  // Hand the "do this next" highlight over to whichever card is still empty.
  integrazoWzRefreshStep1Attention();

  // Close popup
  jQuery('#integrazo-wz-' + group + '-popup')
    .removeClass('integrazo-wz-setup-step1-fullscreen-popup')
    .hide();
  jQuery('#integrazo-wz-' + group + '-popup-close').hide();

  // Optional (if you use “expand” triggers by id):
  jQuery('#integrazo-wz-' + group + '-popup-expand').hide();
});


  // Validate buttons
  jQuery('#step1_next').on('click', function (e) {
    var integrationName = String(jQuery('#integration_name').val() || '').trim();
    var selectedPlugin  = String(jQuery('[name="from_plugin"]').val() || '').trim();
    var selectedProduct = String(jQuery('[name="to_product"]').val() || '').trim();

    if (!integrationName) {
      alert('Please enter an Integration Name.');
      e.preventDefault();
      return false;
    }

    if (!selectedPlugin || !selectedProduct) {
      alert('Please select both a trigger and a destination app.');
      e.preventDefault();
      return false;
    }

    return true;
  });

  jQuery('#step1_save_only').on('click', function (e) {
    var integrationName = String(jQuery('#integration_name').val() || '').trim();
    if (!integrationName) {
      alert('Please enter an Integration Name.');
      e.preventDefault();
      return false;
    }
    return true;
  });

  // Open/Close popups
  jQuery('.integrazo-wz-setup-step1-expand-toggle').on('click', function () {
    var targetSelector = jQuery(this).attr('data-target');
    var $container = jQuery(targetSelector);
    var $closeBtn = $container.find('.integrazo-wz-setup-step1-popup-close');

    if ($container.hasClass('integrazo-wz-setup-step1-fullscreen-popup')) {
      $container.removeClass('integrazo-wz-setup-step1-fullscreen-popup').hide();
      $closeBtn.hide();
    } else {
      $container.addClass('integrazo-wz-setup-step1-fullscreen-popup').show();
      $closeBtn.show();
    }

    // Re-run search to ensure empty state visibility on open
    if (targetSelector === '#integrazo-wz-plugin-popup') {
      runSearch(jQuery('#integrazo-wz-plugin-popup-search'), '#integrazo-wz-plugin-popup-list', 'plugin');
    } else if (targetSelector === '#integrazo-wz-product-popup') {
      runSearch(jQuery('#integrazo-wz-product-popup-search'), '#integrazo-wz-product-popup-list', 'product');
    }
  });

  jQuery('.integrazo-wz-setup-step1-popup-close').on('click', function () {
    var $popup = jQuery(this).closest('.integrazo-wz-setup-step1-overlay');
    $popup.removeClass('integrazo-wz-setup-step1-fullscreen-popup').hide();
    jQuery(this).hide();
  });

  // -------------------------------------------------------- Search (both free + pro) with empty-state (no inline styles)
  var REQUEST_LINK = 'https://integrazo.com/pages/request-feature';

  function ensureEmptyState(listSelector, type) {
    var $list  = jQuery(listSelector);
    var cls    = 'integrazo-wz-empty-state';
    var $empty = $list.children('.' + cls);

    if ($empty.length === 0) {
      var text = (type === 'plugin')
        ? 'Your searched plugin is not available at the moment. Kindly raise your requirement at this link and we will try to add it as soon as possible.'
        : 'Your searched product is not available at the moment. Kindly raise your requirement at this link and we will try to add it as soon as possible.';

      $empty = jQuery(
        '<div class="' + cls + '">' +
          '<span class="integrazo-wz-empty-state-text">' + text + '</span>' +
          '<a class="integrazo-wz-empty-state-link" href="' + REQUEST_LINK + '" target="_blank" rel="noopener noreferrer">Raise your requirement</a>' +
        '</div>'
      );
      $list.append($empty);
    }
    return $empty;
  }

  function runSearch($input, listSelector, group) {
    var $list   = jQuery(listSelector);
    var val     = String($input.val() || '').toLowerCase().trim();
    var $cards  = $list.find('[data-group="' + group + '"]');

    var visibleCount = 0;
    $cards.each(function () {
      var $el   = jQuery(this);
      var name  = String($el.attr('data-name') || '').toLowerCase();
      var id    = String($el.attr('data-id')   || '').toLowerCase();
      var title = String($el.find('.integrazo-wz-setup-step1-plugin-title').text() || '').toLowerCase();
      var hay   = (name + ' ' + id + ' ' + title);
      var show  = (val === '' || hay.indexOf(val) !== -1);
      $el.toggle(show);
      if (show) visibleCount++;
    });

    var $empty = ensureEmptyState(listSelector, group);
    if (visibleCount === 0) {
      $empty.show();
    } else {
      $empty.hide();
    }
  }

  // Plugin popup search
  jQuery('#integrazo-wz-plugin-popup-search').on('input', function () {
    runSearch(jQuery(this), '#integrazo-wz-plugin-popup-list', 'plugin');
  });

  // Product popup search
  jQuery('#integrazo-wz-product-popup-search').on('input', function () {
    runSearch(jQuery(this), '#integrazo-wz-product-popup-list', 'product');
  });
});
