(function ($) {
  'use strict';

  function applyState() {
    const $checkbox = $('#foodord_toggle_country');
    const $select = $('#billing_country');

    if ($select.length === 0 || $checkbox.length === 0) {
      return;
    }

    const $row = $select.closest('.form-row');
    // Store original required state on first run.
    if (typeof $select.data('foodordRequired') === 'undefined') {
      const wasRequired = $select.prop('required') || ($row.hasClass('validate-required'));
      $select.data('foodordRequired', wasRequired);
    }

    const enable = $checkbox.is(':checked');

    if (enable) {
      // Enable field and restore required state if it was required.
      $select.prop('disabled', false);
      if ($select.data('foodordRequired')) {
        $select.prop('required', true);
        $row.addClass('validate-required');
      }
      $row.removeClass('foodord-country-disabled');
    } else {
      // Disable field and relax validation.
      $select.prop('disabled', true);
      $select.prop('required', false);
      $row.removeClass('validate-required').addClass('foodord-country-disabled');
    }

    // Notify select2/selectWoo and WC checkout that value/state may have changed.
    $select.trigger('change');
    $(document.body).trigger('update_checkout');
  }

  function updateLabel() {
    const $checkbox = $('#foodord_toggle_country');
    const $label = $('.foodord-country-toggle__text');
    if ($checkbox.length && $label.length) {
      const on = $label.data('on');
      const off = $label.data('off');
      $label.text($checkbox.is(':checked') ? on : off);
    }
  }

  function bindEvents() {
    $(document).on('change', '#foodord_toggle_country', function () {
      applyState();
      updateLabel();
    });

    // Re-apply after WC updates the checkout DOM.
    $(document.body).on('updated_checkout', function () {
      applyState();
      updateLabel();
    });
  }

  $(function () {
    bindEvents();
    // Initial run.
    applyState();
    updateLabel();
  });
})(jQuery);
