import { Vector3 } from "three";
import { useFrame, useThree } from "@react-three/fiber";
import { CameraControls } from "@react-three/drei";
import { useSceneContext } from "../sceneContext";
import { useIsComparing } from "../../../store/builder/store";
import { useSceneStore } from "../../../store/scene/useSceneStore";
import { useSimulationState } from "../../../store/simulation/useSimulationStore";
import useModuleStore from "../../../store/ui/useModuleStore";

import * as CONSTANTS from "../../../types/world/worldConstants";

function SyncCam() {
    const { layout } = useSceneContext();
    const { controls } = useThree();
    const { isComparing } = useIsComparing();
    const { activeModule } = useModuleStore();
    const { comparisonScene } = useSimulationState();
    const { setCamera, camState } = useSceneStore();

    useFrame(() => {
        if (layout === "Comparison Layout" && controls && camState) {
            (controls as any).mouseButtons.left = CONSTANTS.controlsTransition.leftMouse;
            (controls as any).mouseButtons.right = CONSTANTS.controlsTransition.rightMouse;
            (controls as any).mouseButtons.wheel = CONSTANTS.controlsTransition.wheelMouse;
            (controls as any).mouseButtons.middle = CONSTANTS.controlsTransition.middleMouse;
            (controls as CameraControls).setLookAt(camState.position.x, camState.position.y, camState.position.z, camState.target.x, camState.target.y, camState.target.z, true);
        }
        if (layout === "Main Layout" && controls && isComparing && activeModule === "simulation" && comparisonScene) {
            const position = (controls as CameraControls).getPosition(new Vector3());
            const target = (controls as CameraControls).getTarget(new Vector3());
            setCamera(position, target);
        }
    });

    return <></>;
}

export default SyncCam;
