<script setup lang="ts">
import type { HTMLAttributes } from "vue"
import { cn } from "@/lib/utils"
import { ref, onMounted, onUnmounted, nextTick } from "vue"

const props = defineProps<{
  class?: HTMLAttributes["class"]
}>()

const scrollRef = ref<HTMLElement | null>(null)
const scrollPositionKey = 'sidebar-scroll-position'
let saveTimeout: ReturnType<typeof setTimeout> | null = null

function saveScrollPosition() {
  if (scrollRef.value) {
    sessionStorage.setItem(scrollPositionKey, scrollRef.value.scrollTop.toString())
  }
}

function handleScroll() {
  if (saveTimeout) {
    clearTimeout(saveTimeout)
  }
  saveTimeout = setTimeout(saveScrollPosition, 50)
}

onMounted(() => {
  const saved = sessionStorage.getItem(scrollPositionKey)
  if (saved) {
    nextTick(() => {
      if (scrollRef.value) {
        scrollRef.value.scrollTop = parseFloat(saved)
      }
    })
  }
  
  if (scrollRef.value) {
    scrollRef.value.addEventListener('scroll', handleScroll, { passive: true })
  }
})

onUnmounted(() => {
  if (scrollRef.value) {
    scrollRef.value.removeEventListener('scroll', handleScroll)
  }
  if (saveTimeout) {
    clearTimeout(saveTimeout)
  }
})
</script>

<template>
  <div
    ref="scrollRef"
    data-slot="sidebar-content"
    data-sidebar="content"
    :class="cn('flex min-h-0 flex-1 flex-col gap-2 overflow-auto group-data-[collapsible=icon]:overflow-hidden', props.class)"
  >
    <slot />
  </div>
</template>
