var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
import { createDynamicSlimmer, InjectVegaSlimmer, MapToComponentField, MapToComponentMethod, methodPlaceholder, VegaSlimmer, } from 'vega-slimmer/core';
import { findParent } from '../../../../utils/ui';
import { VegaModalOpenState } from '../models/vega-modal-open-state';
import { AriaDialogFocusableTrapSlimmer } from '../../../../helpers/slimmers/aria-dialog-focusable-trap-slimmer';
/**
 * Modal open state controller
 */
export class VegaModalOpenStateController extends VegaSlimmer {
  constructor() {
    super(...arguments);
    this.ariaDialogFocusableTrapSlimmer = createDynamicSlimmer(VegaModalOpenStateController, AriaDialogFocusableTrapSlimmer, [], [{ mapFrom: 'ariaDialogToggle', mapTo: 'toggle' }], [
      {
        // eslint-disable-next-line jsdoc/require-jsdoc
        triggerEl: () => null,
        // eslint-disable-next-line jsdoc/require-jsdoc
        dialogEl: () => this.renderer.getModalContainerRef(),
      },
    ]);
    /*
     * The below method is e2e-test covered in
     * @see{module:vega-modal-toggle-interactive-e2e}
     */
    /* istanbul ignore next */
    /**
     * Listen modal close event and close modal.
     *
     * @param {MouseEvent} e - Close modal event.
     */
    this.onModalClose = (e) => {
      e.preventDefault();
      e.stopPropagation();
      if (!this.handleClose || this.handleClose()) {
        this.close('close-button');
      }
    };
  }
  /**
   * Component lifecycle - [disconnectedCallback]
   */
  disconnectedCallback() {
    this.close('remove-node');
  }
  /**
   * Component lifecycle - [componentDidLoad]
   */
  componentDidLoad() {
    if (this.openState.isOpen) {
      this.toggle();
    }
  }
  /**
   * Component lifecycle - [componentDidRender]
   */
  componentDidRender() {
    methodPlaceholder();
  }
  /**
   * Toggle modal while openState changed.
   *
   * @param {VegaModalOpenState} newState Specifies the new openState.
   * @param {VegaModalOpenState} oldState Specifies the old openState.
   */
  watchOpenState(newState, oldState) {
    if (newState.isOpen !== oldState.isOpen) {
      this.toggle();
      this.open = newState.isOpen;
    }
  }
  /**
   * Listen the target element clicked has a `data-target='modal'` attribute and open the modal if it does.
   *
   * @param {MouseEvent} e - Open modal event.
   */
  listenDataTarget(e) {
    /*
     * vega-backdrop cannot be clicked and is completely covered by vega-modal. Click events cannot be added to the backdrop.
     */
    const target = e.composedPath()[0];
    if (target.tagName === 'VEGA-MODAL' && this.backdrop === 'default' && target === this.host) {
      /**
       * The below method is e2e-test covered in
       *
       * @see module:vega-modal-backdrop-mousedown-mouseup-e2e
       */
      /* istanbul ignore next */
      if (this.backdropMouseDownOnHost && this.backdropMouseUpOnHost) {
        this.close('backdrop');
      }
      else {
        this.changeOpenState(true, 'backdrop');
      }
      this.resetBackdropClickFlags();
    }
    if (this.host.id &&
      (target.getAttribute('data-target') === this.host.id ||
        findParent(target, `[data-target=${this.host.id}]`))) {
      e.preventDefault();
      this.changeOpenState(true, 'data-target');
    }
  }
  /*
   * The below method is e2e-test covered in
   * @see{module:vega-modal-toggle-interactive-e2e}
   */
  /* istanbul ignore next */
  /**
   * Listen the target element clicked has a `data-dismiss='modal'` attribute and closes the modal if it does.
   *
   * @param {MouseEvent} e - Close modal event.
   */
  listenDataDismiss(e) {
    const target = e.target.closest(`[data-dismiss='modal']`);
    if (target) {
      e.preventDefault();
      this.close('data-dismiss');
    }
  }
  /*
   * The below method is e2e-test covered in
   * @see{@module:vega-modal-backdrop-mousedown-mouseup-e2e}
   */
  /* istanbul ignore next */
  /**
   * Listen the target element mousedown event
   *
   * @param {MouseEvent} e - mousedown event.
   */
  listenMouseDown(e) {
    this.backdropMouseDownOnHost = this.isBackdropClickTargeted(e);
  }
  /*
   * The below method is e2e-test covered in
   * @see{@module:vega-modal-backdrop-mousedown-mouseup-e2e}
   */
  /* istanbul ignore next */
  /**
   * Listen the target element mousedown event
   *
   * @param {MouseEvent} e - mousedown event.
   */
  listenMouseUp(e) {
    this.backdropMouseUpOnHost = this.isBackdropClickTargeted(e);
  }
  /* The below method is e2e-test covered in
   * @see{module:vega-modal-toggle-interactive-e2e}
   */
  /**
   * Handles the public modal API (`show` / `hide`).
   *
   * @param {'show' | 'hide'} option - Determines which state change to perform.
   */
  modal(option) {
    switch (option) {
      case 'show':
        this.changeOpenState(true, 'method');
        break;
      default:
        this.close('method');
        break;
    }
  }
  /**
   * Close the modal via the provided trigger and emit the pending detail.
   *
   * @param {VegaModalOpenStateChangeTrigger} trigger - Indicates what initiated the close.
   */
  close(trigger) {
    if (!this.openState.isOpen) {
      return;
    }
    const event = this.closeEventEmitter.emit({ trigger });
    if (!(event && event.defaultPrevented)) {
      this.changeOpenState(false, trigger);
    }
  }
  /**
   * Toggles the aria-dialog attribute based on the open state.
   *
   * @param {boolean} isOpen - Indicates whether the modal is open.
   */
  ariaDialogToggle(isOpen) {
    methodPlaceholder(isOpen);
  }
  /**
   * Updates the internal open state snapshot so watchers can react to the new value.
   *
   * @param {boolean} isOpen - Desired open flag for the modal.
   * @param {VegaModalOpenStateChangeTrigger} triggerBy - Source that initiated the change.
   */
  changeOpenState(isOpen, triggerBy) {
    if (this.openState.isOpen === isOpen) {
      return;
    }
    this.openState = new VegaModalOpenState(isOpen, triggerBy);
  }
  /*
   * The below method is e2e-test covered in
   * @see{module:vega-modal-toggle-interactive-e2e}
   */
  /* istanbul ignore next */
  /**
   * Manages the visibility and behavior of a modal by updating various properties
   * and emitting an event.
   */
  toggle() {
    this.openState.isOpen
      ? this.openedModalStackController.push()
      : this.openedModalStackController.remove();
    this.updateDocumentRootOverflow();
    this.backdropController.setBackdrop();
    this.zIndexController.setModalZIndex();
    this.removeBackdropWhileNoModalShow();
    this.emitEvent();
    this.setModalVisibility();
    this.ariaDialogToggle(this.openState.isOpen);
  }
  /*
   * The below method is e2e-test covered in
   * @see{module:vega-modal-toggle-interactive-e2e}
   */
  /* istanbul ignore next */
  /**
   * Toggles the display property of a modal element between 'flex' and
   * 'none' based on the value of the `open` property.
   */
  setModalVisibility() {
    this.host.style['display'] = this.openState.isOpen ? 'flex' : 'none';
  }
  /**
   * Emits either an open or close event based on the value of the `open` property.
   */
  emitEvent() {
    if (this.openState.isOpen) {
      this.openEventEmitter.emit();
      return;
    }
    if (this.openState.triggerBy === 'property') {
      this.closeEventEmitter.emit({ trigger: 'property' });
    }
  }
  /**
   * In desktop, we should add 'overflow: hidden' to the body to prevent the body scroll.
   */
  updateDocumentRootOverflow() {
    if (this.backdrop === 'none')
      return;
    const openedModalStackLength = this.openedModalStackController.length();
    if (this.openState.isOpen && openedModalStackLength === 1) {
      // eslint-disable-next-line no-restricted-globals
      document.body.classList.add('disable-scroll-in-desktop');
    }
    else if (!this.openState.isOpen && openedModalStackLength === 0) {
      // eslint-disable-next-line no-restricted-globals
      document.body.classList.remove('disable-scroll-in-desktop');
    }
  }
  /*
   * The below method is e2e-test covered in
   * @see{module:vega-modal-disconnected-callback-e2e }
   */
  /* istanbul ignore next */
  /**
   * Removes the backdrop element if no modals are currently visible.
   */
  removeBackdropWhileNoModalShow() {
    if (!this.openState.isOpen && this.openedModalStackController.length() === 0) {
      this.backdropController.removeBackdrop();
    }
  }
  /*
   * The below method is e2e-test covered in
   * @see{@module:vega-modal-backdrop-mousedown-mouseup-e2e}
   */
  /* istanbul ignore next */
  /**
   * Check if mouse event originates from vega-modal backdrop.
   *
   * @param {MouseEvent} e - The mousedown or mouseup event.
   * @returns { boolean } Return true if is within backdrop otherwise, false
   */
  isBackdropClickTargeted(e) {
    const target = e.composedPath()[0];
    return target.tagName === 'VEGA-MODAL' && target === this.host;
  }
  /**
   * Reset backdrop click flags.
   */
  resetBackdropClickFlags() {
    this.backdropMouseDownOnHost = false;
    this.backdropMouseUpOnHost = false;
  }
}
__decorate([
  MapToComponentField()
], VegaModalOpenStateController.prototype, "host", void 0);
__decorate([
  MapToComponentField({ writable: true })
], VegaModalOpenStateController.prototype, "open", void 0);
__decorate([
  MapToComponentField({ writable: true })
], VegaModalOpenStateController.prototype, "openState", void 0);
__decorate([
  MapToComponentField()
], VegaModalOpenStateController.prototype, "backdrop", void 0);
__decorate([
  MapToComponentField()
], VegaModalOpenStateController.prototype, "handleClose", void 0);
__decorate([
  MapToComponentField()
], VegaModalOpenStateController.prototype, "closeEventEmitter", void 0);
__decorate([
  MapToComponentField()
], VegaModalOpenStateController.prototype, "openEventEmitter", void 0);
__decorate([
  MapToComponentField()
], VegaModalOpenStateController.prototype, "backdropController", void 0);
__decorate([
  MapToComponentField()
], VegaModalOpenStateController.prototype, "openedModalStackController", void 0);
__decorate([
  MapToComponentField()
], VegaModalOpenStateController.prototype, "zIndexController", void 0);
__decorate([
  MapToComponentField()
], VegaModalOpenStateController.prototype, "renderer", void 0);
__decorate([
  InjectVegaSlimmer()
], VegaModalOpenStateController.prototype, "ariaDialogFocusableTrapSlimmer", void 0);
__decorate([
  MapToComponentMethod('disconnectedCallback')
], VegaModalOpenStateController.prototype, "disconnectedCallback", null);
__decorate([
  MapToComponentMethod('componentDidLoad')
], VegaModalOpenStateController.prototype, "componentDidLoad", null);
__decorate([
  MapToComponentMethod('componentDidRender')
], VegaModalOpenStateController.prototype, "componentDidRender", null);
__decorate([
  MapToComponentMethod('watchOpenState')
], VegaModalOpenStateController.prototype, "watchOpenState", null);
__decorate([
  MapToComponentMethod('listenDataTarget')
], VegaModalOpenStateController.prototype, "listenDataTarget", null);
__decorate([
  MapToComponentMethod('listenDataDismiss')
], VegaModalOpenStateController.prototype, "listenDataDismiss", null);
__decorate([
  MapToComponentMethod('listenMouseDown')
], VegaModalOpenStateController.prototype, "listenMouseDown", null);
__decorate([
  MapToComponentMethod('listenMouseUp')
], VegaModalOpenStateController.prototype, "listenMouseUp", null);
__decorate([
  MapToComponentMethod('modal')
], VegaModalOpenStateController.prototype, "modal", null);
