<template>
  <div class="outlines">
    <div class="outline-item" :class="isOutlineActive && 'selected'" @click="goToOutline">
      <div class="outline-item-toggle" :class="isExpanded && 'active'" :style="{ marginLeft: 12 * outline.level + 'px' }">
        <TreeArrow v-if="outline.children.length" @click="toggleOutline" />
      </div>
      <div class="outline-item-title">{{ outline.title }}</div>
    </div>
    <template v-if="isExpanded">
      <Outlines v-for="outline in outline.children" :outline="outline" />
    </template>
  </div>
</template>

<script setup>
import core from '@/core'
import { ref, computed } from 'vue'
import { useViewerStore } from '@/stores/modules/viewer'
import { useDocumentStore } from '@/stores/modules/document'
import { isMobile } from '@/helpers/device'

const emits = defineEmits()
const useDocument = useDocumentStore()
const useViewer = useViewerStore()

const { outline } = defineProps({
  outline: {
    type: Object,
    required: true
  }
})

const splitter = '-'
const getOutlineId = (outline) => {
  const name = outline.title
  const path = getPath(outline)

  return `${path}${splitter}${name}`
}

const getPath = (outline) => {
  return getPathArray(outline).reverse().join(splitter)
}

const getPathArray = (outline) => {
  const paths = []

  let curr = outline
  while (curr) {
    paths.push(curr.index)
    curr = curr.parent
  }

  return paths
}

const outlineId = computed(() => getOutlineId(outline))

const isExpanded = ref(false)
const isOutlineActive = computed(() => useDocument.getActiveOutlineId === outlineId.value)

const goToOutline = () => {
  useDocument.setActiveOutlineId(outlineId.value)
  core.pageNumberChanged({
    value: outline.pageNumber
  })
  isMobile && useViewer.closeElement('leftPanel')
}

const toggleOutline = (e) => {
  e.stopPropagation()
  isExpanded.value = !isExpanded.value
}
</script>

<style lang="scss">
.outline-item {
  display: flex;
  align-items: center;
  padding: 8px 16px;
  &.selected {
    background-color: var(--c-side-outline-bg-active);
  }
}
.outline-item-toggle {
  display: flex;
  align-items: center;
  min-width: 16px;
  margin-right: 8px;
  transition: transform .1s ease;
  &.active {
    transform: rotate(90deg);
  }
}
.outline-item-title {
  color: var(--c-side-outline-text);
  font-size: 14px;
  line-height: 16px;
  cursor: pointer;
}
</style>
