import * as THREE from 'three';
import { ref, onUnmounted } from 'vue';

export function useThreeScene() {
    const canvasContainer = ref<HTMLElement | null>(null);
    let scene: THREE.Scene;
    let camera: THREE.PerspectiveCamera;
    let renderer: THREE.WebGLRenderer;

    const initScene = () => {
        if (!canvasContainer.value) return;

        // Scene
        scene = new THREE.Scene();
        scene.background = new THREE.Color(0x9ee3f9);

        // Camera
        const aspect = window.innerWidth / window.innerHeight;
        camera = new THREE.PerspectiveCamera(40, aspect, 1, 1000);
        camera.position.set(25, 45, 25);
        camera.lookAt(0, 0, 0);

        // Renderer
        renderer = new THREE.WebGLRenderer({ antialias: true });
        renderer.setSize(window.innerWidth, window.innerHeight);
        renderer.shadowMap.enabled = true;
        renderer.outputColorSpace = THREE.SRGBColorSpace;
        canvasContainer.value.appendChild(renderer.domElement);

        window.addEventListener('resize', onWindowResize);
    };

    const onWindowResize = () => {
        if (!renderer || !camera) return;
        camera.aspect = window.innerWidth / window.innerHeight;
        camera.updateProjectionMatrix();
        renderer.setSize(window.innerWidth, window.innerHeight);
    };

    onUnmounted(() => {
        window.removeEventListener('resize', onWindowResize);
        if (renderer) renderer.dispose();
    });

    return {
        canvasContainer,
        initScene,
        getScene: () => scene,
        getCamera: () => camera,
        getRenderer: () => renderer
    };
}
