import { App, createApp, ref } from 'vue';
import HighlightSidebar from '@/components/highlights/HighlightSidebar.vue';
import { HighlightNode } from '@/__generated__/graphql';

interface Options {
  highlight: HighlightNode;
  onUpdateText: (text: string) => void;
}

interface Instance {
  app: App;
  cleanUp: () => void;
}

// track previous instance
const previous = ref<Instance | null>(null);

export default {
  open({ highlight, onUpdateText }: Options) {
    // close previous instance
    if (previous.value) {
      previous.value.cleanUp();
      previous.value = null;
    }
    const app = document.getElementById('app');
    const mountEl = document.createElement('div');
    app?.appendChild(mountEl);

    const clickOutsideElementListener = (event: Event) => {
      const isInsidePopover = document.querySelector('.highlight-popover')?.contains(event.target as Node);
      const isInsideSidebar = mountEl.contains(event.target as Node);
      if (!(isInsidePopover || isInsideSidebar)) {
        cleanUp();
      }
    };

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

    const sidebar = createApp(HighlightSidebar, {
      highlight,
      onClose() {
        cleanUp();
      },
      onUpdateText,
    });

    previous.value = {
      app: sidebar,
      cleanUp: cleanUp,
    };

    sidebar.mount(mountEl);

    setTimeout(() => {
      document.addEventListener('click', clickOutsideElementListener);
    }, 1);
  },
};
