<script setup lang="ts">
import type { TimelineMarkerData } from '@/lib/Timeline'
import { computed, shallowRef, useTemplateRef } from 'vue'
import { markerToAbsoluteTime } from '@/lib/Timeline'
import { usePx } from '@/lib/usePx'
import { useTimelineStore } from '@/store/TimelineStore'
import MarkerBoxSvg from './marker-box.svg'

const {
  marker,
} = defineProps<{
  marker: TimelineMarkerData
}>()

const timeline = useTimelineStore()

const left = usePx(() => {
  const seconds = markerToAbsoluteTime(timeline.audioTrack!, marker)
  const px = timeline.secondsToPixels(seconds)
  return px
})

// const referenceClass = computed(() => marker.reference === 'absolute' ? 'marker-box-top' : 'marker-box-bottom');
const positionClass = computed(() => marker.position === 'top' ? 'marker-box-top' : 'marker-box-bottom')

// TODO: selection manager
const selected = shallowRef(false)

function toggle(_event: MouseEvent) {
  selected.value = !selected.value
}

const element = useTemplateRef('element')

function onPointerDown(event: PointerEvent) {
  element.value?.setPointerCapture(event.pointerId)
}
</script>

<template>
  <div
    ref="element" class="tw:absolute marker-box" :class="[positionClass, { selected }]" :style="{
      left: left.string,
      color: marker.color,
    }" :title="marker.name" @click.prevent.stop="toggle" @pointerdown.prevent.stop="onPointerDown"
  >
    <MarkerBoxSvg />
  </div>
</template>

<style scoped>
.marker-box {
  position: absolute;
  width: 11px;
  height: 16px;
  transform: translateX(-5px) translateY(1px);
  --marker-stroke-color: #00000080;
}

.marker-box-bottom {
  bottom: 0;
}

.marker-box-top {
  top: 0;

  &:deep(svg) {
    transform: rotate(180deg);
  }
}

.selected {
  --marker-stroke-color: #ffffff;
}
</style>
