<script setup lang="ts">
import LearningPathCircleColumn from "@/pages/learningPath/learningPathPage/LearningPathCircleColumn.vue";
import LearningPathScrollButton from "@/pages/learningPath/learningPathPage/LearningPathScrollButton.vue";
import type { Circle } from "@/services/circle";
import type { LearningPath } from "@/services/learningPath";
import { useScroll } from "@vueuse/core";
import { ref } from "vue";

const props = defineProps<{
  learningPath: LearningPath | undefined;
  useMobileLayout: boolean;
  hideButtons?: boolean;
}>();

const scrollIncrement = 600;

const learnPathDiagram = ref<HTMLElement | null>(null);
const { x, arrivedState } = useScroll(learnPathDiagram, { behavior: "smooth" });

const isFirstCircle = (topicIndex: number, circleIndex: number) =>
  topicIndex === 0 && circleIndex === 0;

const isLastCircle = (topicIndex: number, circleIndex: number, numCircles: number) =>
  topicIndex === (props.learningPath?.topics ?? []).length - 1 &&
  circleIndex === numCircles - 1;

const isCurrentCircle = (circle: Circle) =>
  props.learningPath?.nextLearningContent?.parentCircle === circle;

const scrollRight = () => scrollLearnPathDiagram(scrollIncrement);

const scrollLeft = () => scrollLearnPathDiagram(-scrollIncrement);

const scrollLearnPathDiagram = (offset: number) => {
  x.value += offset;
};
</script>

<template>
  <div class="relative flex flex-row items-center">
    <LearningPathScrollButton
      v-show="!arrivedState.left"
      direction="left"
      :hidden="props.useMobileLayout"
      @click="scrollLeft"
    ></LearningPathScrollButton>
    <div
      ref="learnPathDiagram"
      class="no-scrollbar flex h-96 snap-x flex-row overflow-auto py-5 sm:py-10"
    >
      <div
        v-for="(topic, topicIndex) in props.learningPath?.topics ?? []"
        :key="topic.title"
        class="border-l border-gray-500"
        :class="topicIndex == 0 ? 'ml-6 sm:ml-12' : ''"
      >
        <p
          :id="`topic-${topic.slug}`"
          class="inline-block h-12 self-start px-4 font-bold text-gray-800"
        >
          {{ topic.title }}
        </p>
        <div class="flex flex-row pt-6">
          <LearningPathCircleColumn
            v-for="(circle, circleIndex) in topic.circles"
            :key="circle.id"
            :learning-path="learningPath"
            :circle="circle"
            :topic="topic"
            :is-first-circle="isFirstCircle(topicIndex, circleIndex)"
            :is-last-circle="
              isLastCircle(topicIndex, circleIndex, topic.circles.length)
            "
            :is-current-circle="isCurrentCircle(circle) && !props.hideButtons"
          ></LearningPathCircleColumn>
        </div>
      </div>
    </div>
    <LearningPathScrollButton
      v-show="!arrivedState.right"
      direction="right"
      :hidden="props.useMobileLayout"
      @click="scrollRight"
    ></LearningPathScrollButton>
  </div>
</template>
