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

interface Options {
  wrapper: HTMLElement;
  offsetTop: number;
  onChooseColor: (color: string) => void;
  // we don't use the id as a param here, because the calling component knows already which entity it is
  onDelete?: () => void;
  onNote?: () => void;
}

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

    const clickOutsideElementListener = (event: Event) => {
      // inspired by https://stackoverflow.com/a/3028037/6071058
      const isInsidePopover = mountEl.contains(event.target as Node); // the click happened inside the Popover
      // const isInsideWrapper = wrapper.contains(event.target as Node); // the click happened inside the wrapper
      const isInsideSidebar = document.querySelector('.highlight-sidebar')?.contains(event.target as Node); // the click happened inside the HighlightSidebar
      if (!(isInsidePopover || isInsideSidebar)) {
        cleanUp();
      }
    };

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

    const popover = createApp(HighlightPopover, {
      top: `${Math.floor(offsetTop)}px`,
      showDelete: !!onDelete,
      onConfirm() {
        cleanUp();
      },
      onNote() {
        if (onNote) {
          onNote();
        }
      },
      onClose() {
        cleanUp();
      },
      onDelete() {
        if (onDelete) {
          onDelete();
        }
        cleanUp();
      },
      onChooseColor,
    });

    popover.mount(mountEl);

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