<script setup lang="ts">
import type { TimelineClipData, TimelineTrackData } from '@/lib/Timeline'
import { storeToRefs } from 'pinia'
import { computed } from 'vue'
import { useTimelineStore } from '@/store/TimelineStore'
import Default from './Default.vue'

const {
  clip,
  width,
} = defineProps<{
  track: TimelineTrackData
  clip: TimelineClipData
  width: number
}>()

const { audioTrack } = storeToRefs(useTimelineStore())
const ColorTransitionOut = computed(() => `${(audioTrack.value?.ColorTransitionOut ?? 0) * 100}%`)
const ColorTransitionIn = computed(() => `${100 - (audioTrack.value?.ColorTransitionIn ?? 0) * 100}%`)

// TODO: shift by BeatsOffset, use new method for computing index into pallete

const colorsPrevNext = computed(() => {
  const palette = audioTrack.value?.Palette
  if (palette !== undefined && palette.length > 0) {
    const nextColorIndex = (clip.clipIn + 1) % palette.length
    const prevColorIndex = (clip.clipIn - 1) % palette.length
    const nextColor = palette[nextColorIndex]
    const prevColor = palette[prevColorIndex]
    return { prevColor, nextColor }
  }
  return { prevColor: clip.color, nextColor: clip.color }
})
</script>

<template>
  <div
    class="tw:absolute tw:w-full palette-gradient" :style="{
      // TODO: this is inaccurate w.r.t. In & Out duration. Also wasteful.
      'left': `-50%`,
      'width': `200%`,
      '--color-prev': colorsPrevNext.prevColor,
      '--color-curr': clip.color,
      '--color-next': colorsPrevNext.nextColor,
      '--color-transition-out': ColorTransitionOut,
      '--color-transition-in': ColorTransitionIn,
    }"
  />

  <div
    class="tw:absolute tw:top-0 tw:bottom-5.5 tw:border-l tw:border-(--timeline-clip-baseline-color)"
    :style="{ left: ColorTransitionOut }"
  />
  <div
    class="tw:absolute tw:top-0 tw:bottom-5.5 tw:border-l tw:border-(--timeline-clip-baseline-color)"
    :style="{ left: ColorTransitionIn }"
  />

  <Default :track :clip :width />
</template>

<style scoped>
.fade-out {
  border-style: solid;
  border-color: transparent;
  border-top-color: black;
  border-right-color: black;
}

.palette-gradient {
  left: 0;
  top: 0;
  /* TODO: hardcoded bottom line offset */
  height: 100%;
  height: calc(100% - calc(var(--tw-spacing) * 5.5) - 0px);
  background-image:
    linear-gradient(to right,
      var(--color-prev) 0%,
      var(--color-curr) var(--color-transition-out),
      var(--color-curr) var(--color-transition-in),
      var(--color-next) 100%);
}
</style>
