/* global TomSelect, MeprCouponSearch, jQuery */

/**
 * Initialize a Tom Select coupon search dropdown.
 *
 * @param {string|Element} selector - CSS selector or DOM element for the <select>.
 * @param {object}         opts     - Overrides: maxItems, closeAfterSelect, plugins, etc.
 * @return {TomSelect}
 */
window.meprCouponSearch = function(selector, opts) {
  opts = opts || {};
  var isSingle = opts.maxItems === 1;

  var config = {
    valueField:       'id',
    labelField:       'text',
    searchField:      'text',
    plugins:          ['remove_button'],
    preload:          'focus',
    persist:          false,
    closeAfterSelect: true,
    loadThrottle:     300,

    onItemAdd: isSingle ? function() { this.blur(); } : null,

    shouldLoad: function(query) {
      return query.length === 0 || query.length >= 2;
    },

    load: function(query, callback) {
      var self = this;
      var exclude = Object.keys(self.items).map(Number);
      var extra = self.settings.excludeExtra;
      if (Array.isArray(extra) && extra.length) {
        exclude = exclude.concat(extra);
      }

      jQuery.post(MeprCouponSearch.ajax_url, {
        action:  'mepr_search_coupons',
        nonce:   MeprCouponSearch.nonce,
        q:       query,
        exclude: exclude,
      }, function(response) {
        callback((response && response.results) || []);
      }).fail(function() {
        callback();
      });
    },

    render: {
      loading: function() {
        return '<div class="no-results">' + MeprCouponSearch.l10n.loading + '</div>';
      },
      no_results: function(data) {
        var msg = data.input.length < 2
          ? MeprCouponSearch.l10n.type_to_search
          : MeprCouponSearch.l10n.no_results;
        return '<div class="no-results">' + msg + '</div>';
      },
    },
  };

  return new TomSelect(selector, jQuery.extend({}, config, opts || {}));
};

/*
 * Self-init for server-rendered coupon rows (e.g. the group edit screen).
 * Lives here so scripts on shared screens have no coupon dependency; the
 * tomselect guard keeps this idempotent if a row was already initialized.
 */
jQuery(function($) {
  $('ol#sortable-coupons .mepr-coupon-search-select').each(function() {
    if (!this.tomselect) {
      window.meprCouponSearch(this, { maxItems: 1 });
    }
  });
});
