import HighlightPopover from '@/components/highlights/HighlightPopover.vue';
import { createApp } from 'vue';

type ResolveReject = (v?: unknown) => void;

interface Options {
  wrapper: HTMLElement;
  offsetTop: number;
  onChooseColor: (color: string) => void;
}

export default {
  show({ wrapper, offsetTop, onChooseColor }: Options) {
    const mountEl = document.createElement('div');
    wrapper.appendChild(mountEl);

    let _resolve: ResolveReject, _reject: ResolveReject;

    const promise = new Promise((resolve, reject) => {
      _resolve = resolve;
      _reject = reject;
    });

    const clickOutsideElementListener = (event: Event) => {
      // inspired by https://stackoverflow.com/a/3028037/6071058
      if (!mountEl.contains(event.target as Node)) {
        _reject();
        cleanUp();
      }
    };

    const cleanUp = () => {
      mountEl?.parentNode?.removeChild(mountEl);
      document.removeEventListener('click', clickOutsideElementListener);
      popover.unmount();
    };

    const popover = createApp(HighlightPopover, {
      top: `${Math.floor(offsetTop)}px`,
      onConfirm() {
        cleanUp();
        _resolve();
      },
      onClose() {
        cleanUp();
        _reject();
      },
      onChooseColor,
    });

    popover.mount(mountEl);

    setTimeout(() => {
      document.addEventListener('click', clickOutsideElementListener);
    }, 1); // do not triger ont the same event that created the popover
    return promise;
  },
};
