<script setup lang="ts">
import { useLoop } from '@tresjs/core';
import { Vector3 } from 'three';

const { controls, camera } = useTresContext();
const goto_camera = use_goto_camera();

const COUNT = 30
type smooth = {
    value: Vector3 | undefined,
    count: number
}
const smooth_target = reactive({}) as smooth
const smooth_move = reactive({}) as smooth

const set_moveto = (obj: smooth, value: smooth["value"]) => {
    obj.value = value
    obj.count = COUNT
}

watch(goto_camera, () => {
    smooth_target.value = goto_camera.value
    smooth_target.count = COUNT
})

const koef = (1 / COUNT) * 3
const { onBeforeLoop } = useRenderLoop()
onBeforeLoop(() => {
    if (smooth_target.value || smooth_move.value) {
        if (smooth_target.value) {
            (controls.value as any).target.lerp(smooth_target.value as Vector3, koef);
            (controls.value as any).update();
            smooth_target.count -= 1;
            if (smooth_target.count == 1) {
                set_moveto(smooth_target, undefined);
            }
        } else if (smooth_move.value) {
            camera.value?.position.lerp(smooth_move.value as Vector3, koef);
            camera.value?.updateMatrixWorld();
            (controls.value as any).update();

            smooth_move.count -= 1;
            if (smooth_move.count == 1) {
                set_moveto(smooth_move, undefined);
            }
        }
    }
})
</script>
<template></template>
