let scene, camera, renderer, model, light;
let isDragging = false;
let previousMousePosition = {
    x: 0,
    y: 0
};
let shouldRotate = false;


function init3DScene() {
    scene = new THREE.Scene();
    camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
    renderer = new THREE.WebGLRenderer({ antialias: true });
    renderer.setClearColor(0xFFFFFF); // Background color
    renderer.setSize(window.innerWidth * 0.8, window.innerHeight * 0.8);

    const canvasContainer = document.getElementById('canvasContainer');
    if (canvasContainer) {
        canvasContainer.appendChild(renderer.domElement);
        renderer.domElement.style.width = '100%';
        renderer.domElement.style.height = '100%';
    } else {
        console.error('Canvas container not found');
    }

    light = new THREE.DirectionalLight(0xfffff1, 0.8);
    scene.add(light);
    const ambientLight = new THREE.AmbientLight(0xffffff, 0.3);
    scene.add(ambientLight);

    const loader = new THREE.GLTFLoader();
    loader.load('3d/svr.glb', function (gltf) {
        model = gltf.scene;
        scene.add(model);
        adjustCameraPosition();
        animate();
        console.log("Model loaded", model);
    }, undefined, function (error) {
        console.error('An error happened during loading model:', error);
    });

    setupControls();
    setupInteractionHandlers();
}

function adjustCameraPosition() {
    const box = new THREE.Box3().setFromObject(model);
    const center = box.getCenter(new THREE.Vector3());
    const size = box.getSize(new THREE.Vector3());
    camera.position.set(center.x, center.y, size.length());
    camera.lookAt(center);
}

function animate() {
    requestAnimationFrame(animate);

    if (shouldRotate) {
        model.rotation.y += 0.01;
    }

    renderer.render(scene, camera);
}

function setupControls() {
    document.getElementById('moveLeft').addEventListener('click', () => model.position.x -= 8);
    document.getElementById('moveRight').addEventListener('click', () => model.position.x += 8);
    document.getElementById('zoomIn').addEventListener('click', () => camera.position.z -= 20);
    document.getElementById('zoomOut').addEventListener('click', () => camera.position.z += 20);
    document.getElementById('lightUp').addEventListener('click', () => light.intensity += 1);
    document.getElementById('lightDown').addEventListener('click', () => light.intensity -= 1);
    document.getElementById('rotate').addEventListener('click', () => shouldRotate = !shouldRotate);
}

function setupInteractionHandlers() {
    renderer.domElement.addEventListener('mousedown', onMouseDown);
    renderer.domElement.addEventListener('mousemove', onMouseMove);
    renderer.domElement.addEventListener('mouseup', onMouseUp);
}

function onMouseDown(event) {
    isDragging = true;
    previousMousePosition.x = event.clientX;
    previousMousePosition.y = event.clientY;
}

function onMouseMove(event) {
    if (isDragging) {
        var deltaMove = {
            x: event.clientX - previousMousePosition.x,
            y: event.clientY - previousMousePosition.y
        };

        model.rotation.y += deltaMove.x * 0.005;
        model.rotation.x += deltaMove.y * 0.005;

        previousMousePosition = {
            x: event.clientX,
            y: event.clientY
        };
    }
}

function onMouseUp(event) {
    isDragging = false;
}


function toggleModal(show) {
    const modal = document.getElementById('modelViewerModal');
    if (modal) {
        modal.style.display = show ? 'block' : 'none';
    }
}

document.addEventListener('DOMContentLoaded', function() {
    const button = document.querySelector('.button3D');
    if (button) {
        button.addEventListener('click', function() {
            if (!scene) {
                init3DScene();
            } else {
                console.log("3D scene is already initialized.");
            }
            toggleModal(true);
        });
    } else {
        console.error("The 3D button was not found on the page.");
    }
});
