<template>
    <div v-if="showScrollBar" class="scroll-bar">
        <div class="inner" ref="inner">
            <div class="handle" ref="handle" />
        </div>
    </div>
</template>

<script setup>
import { ref, onBeforeUnmount, computed, watch } from 'vue'
import { useElementSize, useWindowScroll, useWindowSize } from '@vueuse/core'
import Tempus from 'tempus'
import { useDragControls } from '@/composables/useDragControls'

const inner = ref()
const handle = ref()

// Sizing
const { height: wHeight } = useWindowSize()
const { y: scrollY } = useWindowScroll()
const { height: documentHeight } = useElementSize(document.documentElement)
const { height: innerHeight } = useElementSize(inner)
const { height: handleHeight } = useElementSize(handle)

// Drag controls
// useDragControls({
//     target: handle,
//     onUpdate: ({ y }) => {
//         console.log(y.value)
//     },
// })

const updateScrollbar = () => {
    const scrollHeight = documentHeight.value
    const viewportHeight = wHeight.value
    const limit = scrollHeight - viewportHeight

    if (limit <= 0) return

    const progress = scrollY.value / limit

    if (handle.value) {
        handle.value.style.transform = `translate3d(0,${
            progress * (innerHeight.value - handleHeight.value)
        }px,0)`
    }
}

const showScrollBar = computed(() => {
    return documentHeight.value > wHeight.value
})

// RAF
const removeRaf = ref()
const addRaf = () => (removeRaf.value = Tempus.add(updateScrollbar))
onBeforeUnmount(() => {
    removeRaf.value?.()
})
watch(
    showScrollBar,
    (show) => {
        if (show) {
            addRaf()
        } else {
            removeRaf.value?.()
        }
    },
    { immediate: true },
)
</script>

<style lang="scss">
.scroll-bar {
    position: fixed;
    top: 0;
    right: 0;
    bottom: 0;
    width: 8px;
    will-change: transform;
    border-left: 1px solid var(--grey-100);

    .inner {
        height: 100%;
        position: relative;

        .handle {
            width: 100%;
            height: 388px;
            background: var(--grey-100);
            border-radius: 20px;
            position: absolute;
            right: 0;
            will-change: transform;
        }
    }
}
</style>
