<template>
  <section :class="'story mode-' + story.displayMode">
    <ArticleTop :story="props.story" />
    <aside
      v-if="story.displayMode === 'EDITOR'"
      class="story-tools fixed inline-block bg-white bg-opacity-50 m-10 z-10 top-0 left-0"
    >
      <Editor :story="props.story" />
    </aside>
    <main class="story-openseadragon border-black border" ref="openSeadragonElt"></main>
    <ArticleBottom :story="props.story" />
  </section>
</template>

<script setup lang="ts">
import OpenSeadragon from 'openseadragon'
import '@/assets/plugins/openseadragon-scalebar.js'
import '@/assets/plugins/openseadragon-bookmark-url.js'
import '@/assets/plugins/openseadragon-measure.js'
import { onMounted, ref, provide, onUnmounted } from 'vue'
import type { Story, ViewerConfiguration } from '@/types/virages'
import ArticleTop from './StoryArticleTop.vue'
import ArticleBottom from './StoryArticleBottom.vue'
import Editor from './player/StoryEditor.vue'

const props = defineProps<{ story: Story }>()
const Viewer = ref()
const openSeadragonElt = ref()

provide('Viewer', Viewer)

const defaultViewerConfiguration: ViewerConfiguration = {
  prefixUrl: 'https://openseadragon.github.io/openseadragon/images/',
  crossOriginPolicy: 'Anonymous',
  animationTime: 2,
  showNavigator: false,
  sequenceMode: false,
  showNavigationControl: false,
  drawer: 'canvas',
  preventDefaultAction: true,
  visibilityRatio: 0.5,
  defaultZoomLevel: 4,
  gestureSettingsMouse: {
    scrollToZoom: true,
    clickToZoom: false,
    dblClickToZoom: false,
    dragToPan: true,
  },
}

const initViewer = () => {
  Viewer.value = OpenSeadragon({
    element: openSeadragonElt.value,
    tileSources: props.story.url,
    ...defaultViewerConfiguration,
    debugMode: false,
  })
}

const destroyViewer = () => {
  if (Viewer.value) {
    Viewer.value.destroy()
  }
}

onMounted(() => {
  initViewer()
})

onUnmounted(() => {
  destroyViewer()
})
</script>

<style lang="scss">
.story {
  transition: padding 0.5s ease-in-out;
  @apply p-8;
  &.mode-EDITOR,
  &.mode-PLAYER {
    @apply p-0 z-50;
    .story-openseadragon {
      @apply top-0 left-0 w-screen;
      position: relative !important;
    }
  }

  &.mode-HIDDEN {
    @apply p-0 h-0;
    width: 0% !important;
  }

  &.mode-ARTICLE {
    @apply w-full bg-white hover:bg-slate-200 hover:cursor-pointer;
    .openseadragon-canvas {
      pointer-events: none !important;
      touch-action: none !important;
    }
  }
}

.story-openseadragon {
  transition: height 0.5s ease-in-out;
  height: 33vh;
  .mode-EDITOR &,
  .mode-PLAYER & {
    @apply h-screen;
  }
  .mode-HIDDEN & {
    @apply h-0;
  }
}

.story-article {
  position: relative;
  top: 0;
  .mode-PLAYER & {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
  }
  .mode-EDITOR & {
    @apply p-0 h-0 w-0 overflow-hidden opacity-0;
  }

  .mode-HIDDEN & {
    @apply p-0 h-0 w-0 overflow-hidden;
  }
}
</style>
