// DSS Team Portal - Three.js Scene
import * as THREE from 'three';

let scene, camera, renderer, crystal;

function init() {
    // Scene
    scene = new THREE.Scene();

    // Camera
    camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
    camera.position.z = 5;

    // Renderer
    const canvas = document.getElementById('webgl-canvas');
    renderer = new THREE.WebGLRenderer({ canvas, antialias: true, alpha: true });
    renderer.setSize(window.innerWidth, window.innerHeight);

    // "Fake Crystal" - using a simple material for POC
    const geometry = new THREE.IcosahedronGeometry(1.5, 0);
    const material = new THREE.MeshBasicMaterial({ color: 0xff0000, wireframe: true });
    
    // Add a uniform for color control
    material.onBeforeCompile = (shader) => {
        shader.uniforms.uColor = { value: new THREE.Color(0xff0000) };
        shader.fragmentShader = `
            uniform vec3 uColor;
            ${shader.fragmentShader}
        `.replace(
            `vec4 diffuseColor = vec4( diffuse, opacity );`,
            `vec4 diffuseColor = vec4( uColor, opacity );`
        );
        crystal.userData.shader = shader;
    };
    
    crystal = new THREE.Mesh(geometry, material);
    scene.add(crystal);

    // Animation Loop
    function animate() {
        requestAnimationFrame(animate);
        crystal.rotation.x += 0.001;
        crystal.rotation.y += 0.001;
        renderer.render(scene, camera);
    }
    animate();

    // Handle window resize
    window.addEventListener('resize', () => {
        camera.aspect = window.innerWidth / window.innerHeight;
        camera.updateProjectionMatrix();
        renderer.setSize(window.innerWidth, window.innerHeight);
    });
}

function updateCrystalColor(color) {
    if (crystal && crystal.userData.shader) {
        crystal.userData.shader.uniforms.uColor.value.set(color);
    }
}

export { init as initScene, updateCrystalColor, camera, crystal };
