import { injectStyle } from '@descope-ui/common/components-helpers';

export const draggableMixin = (superclass) =>
  class DraggableMixinClass extends superclass {
    constructor() {
      super();

      injectStyle(`:host([draggable="true"]) * { cursor: inherit!important }`, this);
    }

    get isDraggable() {
      return this.hasAttribute('draggable') && this.getAttribute('draggable') !== 'false';
    }

    init() {
      // because we are delegating the focus from the outer component,
      // the D&D is not working well in the page editor
      // in order to solve it we are making the inner component focusable on mouse down
      // and removing it on complete
      this.addEventListener('mousedown', (e) => {
        if (this.isDraggable) {
          const prevTabIndex = this.baseElement.getAttribute('tabindex');
          this.baseElement.setAttribute('tabindex', '-1');

          const onComplete = () => {
            prevTabIndex
              ? this.baseElement.setAttribute('tabindex', prevTabIndex)
              : this.baseElement.removeAttribute('tabindex');

            e.target.removeEventListener('mouseup', onComplete);
            e.target.removeEventListener('dragend', onComplete);
          };

          e.target.addEventListener('mouseup', onComplete, { once: true });
          e.target.addEventListener('dragend', onComplete, { once: true });
        }
      });

      super.init?.();
    }
  };
