let mouse;
let raycaster;

function initControls(scene, camera, renderer){
    // --- Add OrbitControls ---
    controls = new THREE.OrbitControls(camera, renderer.domElement);
    controls.enableDamping = true; // Smooth movement
    controls.dampingFactor = 0.05;
    controls.enableRotate = false;
    controls.enablePan = true;
    controls.enableZoom = false;
    controls.mouseButtons = {
        LEFT: THREE.MOUSE.PAN
    }
    controls.target.set(0, 0, 0); // Focus on scene center
    controls.update();

    const transformControls = new THREE.TransformControls(camera, renderer.domElement);
    transformControls.setMode('translate'); // Move mode
    transformControls.showX = true;
    transformControls.showY = false;
    transformControls.showZ = true;
    transformControls.enabled = false;
    transformControls.addEventListener('dragging-changed', function (event) {
        controls.enabled = !event.value; // Disable OrbitControls while dragging
    });
    scene.add(transformControls);

    window.addEventListener('keydown', function(event) {
        if (event.key === 'm') {
            transformControls.enabled = !transformControls.enabled;
        }
    });

    // Add event listener for selecting Building To Move
    renderer.domElement.addEventListener('pointerdown', function(event) {
        // Calculate mouse position in normalized device coordinates
        const rect = renderer.domElement.getBoundingClientRect();
        mouse.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
        mouse.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
        
        raycaster.setFromCamera(mouse, camera);
        const intersects = raycaster.intersectObjects(interactableObjects);

        if (transformControls.enabled) {
            raycaster.setFromCamera(mouse, camera);
            const intersects = raycaster.intersectObjects(interactableObjects);
            if (intersects.length > 0) {
                const selected = intersects[0].object.userData.parentGroup || intersects[0].object;
                transformControls.attach(selected);
            } else {
                transformControls.detach();
            }
        }
    });
    
    mouse = new THREE.Vector2();
    raycaster = new THREE.Raycaster();
}