/**
 * Consent Modal JavaScript
 */

(function ($) {
  'use strict';

  // Modal handling class
  class ConsentModal {
    constructor() {
      this.$modal = $('#smart-discount-consent-modal');
      this.$content = this.$modal.find('.smart-discount-modal-content');
      this.$allowBtn = $('#smart-discount-consent-yes');
      this.$denyBtn = $('#smart-discount-consent-no');

      this.bindEvents();
      this.showModal();
    }

    bindEvents() {
      this.$allowBtn.on('click', () => this.handleConsent('allowed'));
      this.$denyBtn.on('click', () => this.handleConsent('denied'));

      // Close modal on escape key
      $(document).on('keyup', (e) => {
        if (e.key === 'Escape') {
          this.hideModal();
        }
      });

      // Prevent modal content clicks from bubbling
      this.$content.on('click', (e) => e.stopPropagation());
    }

    showModal() {
      this.$modal.addClass('show');
      $('body').addClass('modal-open');
    }

    hideModal() {
      this.$modal.removeClass('show');
      $('body').removeClass('modal-open');

      setTimeout(() => {
        this.$modal.hide();
      }, 300);
    }

    showNotice(message, type = 'success') {
      const noticeClass = type === 'success' ? 'notice-success' : 'notice-error';
      const $notice = $('<div/>', {
        class: `notice ${noticeClass} is-dismissible`,
        html: `<p>${message}</p>`
      });

      // Remove existing notices
      $('.notice').remove();

      // Add new notice after the modal
      this.$modal.after($notice);

      // Auto dismiss after 3 seconds
      setTimeout(() => {
        $notice.fadeOut(() => $notice.remove());
      }, 3000);
    }

    handleConsent(consent) {
      const self = this;

      $.ajax({
        url: smartDiscountConsent.ajaxurl,
        type: 'POST',
        data: {
          action: 'smart_discount_handle_consent',
          consent: consent,
          nonce: smartDiscountConsent.nonce
        },
        beforeSend: function () {
          // Disable buttons during request
          self.$allowBtn.prop('disabled', true);
          self.$denyBtn.prop('disabled', true);
        },
        success: function (response) {
          if (response.success) {
            self.showNotice(
              consent === 'allowed'
                ? smartDiscountConsent.i18n.success
                : response.data.message
            );
            self.hideModal();
          } else {
            self.showNotice(response.data.message, 'error');
          }
        },
        error: function () {
          self.showNotice(smartDiscountConsent.i18n.error, 'error');
        },
        complete: function () {
          // Re-enable buttons
          self.$allowBtn.prop('disabled', false);
          self.$denyBtn.prop('disabled', false);
        }
      });
    }
  }

  // Initialize on document ready
  $(document).ready(function () {
    new ConsentModal();
  });

})(jQuery);