/**
 * ALGA ARENA — Cinematic Scene Manager
 * Binds all sub-systems into a unified, high-performance lifecycle
 */

'use strict';

window.CinematicManager = (() => {
    let container, canvas, renderer, scene, camera;
    let clock, frameId, isInitialized = false;
    let isReducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches;

    const init = (containerId) => {
        container = document.getElementById(containerId);
        if (!container || isInitialized) return;

        clock = new THREE.Clock();

        // 1. Create WebGL Canvas
        canvas = document.createElement('canvas');
        canvas.id = 'arena-3d-canvas';
        canvas.style.position = 'absolute';
        canvas.style.top = '0';
        canvas.style.left = '0';
        canvas.style.width = '100%';
        canvas.style.height = '100%';
        canvas.style.zIndex = '0';
        canvas.style.pointerEvents = 'none';
        container.appendChild(canvas);

        // 2. Setup Renderer
        renderer = new THREE.WebGLRenderer({
            canvas: canvas,
            antialias: !isReducedMotion && window.innerWidth > 768,
            alpha: true,
            powerPreference: "high-performance"
        });
        renderer.setSize(container.clientWidth, container.clientHeight);
        renderer.setPixelRatio(Math.min(window.devicePixelRatio, 1.5));
        renderer.toneMapping = THREE.ACESFilmicToneMapping;
        renderer.toneMappingExposure = 1.0;

        // 3. Setup Scene & Camera
        scene = new THREE.Scene();
        scene.fog = new THREE.FogExp2(0x05070c, 0.04);

        camera = new THREE.PerspectiveCamera(45, container.clientWidth / container.clientHeight, 0.1, 100);
        camera.position.set(0, 0, 10);

        // 4. Load Cinematic Modules
        window.CinematicLighting?.init(scene);
        window.CinematicCore?.init(scene);
        window.CinematicFragments?.init(scene);
        window.CinematicParticles?.init(scene);
        window.CinematicReflection?.init(scene);

        // 5. Connect ScrollTrigger timeline
        window.CinematicTimelines?.init(camera, scene);

        // Event listeners
        window.addEventListener('resize', handleResize);
        if (!isReducedMotion) {
            window.addEventListener('mousemove', handleMouseMove);
        }

        isInitialized = true;
        animate();
    };

    const animate = () => {
        frameId = requestAnimationFrame(animate);

        const delta = clock.getDelta();
        const time = clock.getElapsedTime();

        // Update active modules
        window.CinematicCore?.update(delta, time);
        window.CinematicFragments?.update(delta, time);
        window.CinematicParticles?.update(delta, time);
        window.CinematicParallax?.update(scene, delta);

        renderer.render(scene, camera);
    };

    const handleMouseMove = (e) => {
        window.CinematicParallax?.onMouseMove(e);
    };

    const handleResize = () => {
        if (!container || !camera || !renderer) return;
        const w = container.clientWidth;
        const h = container.clientHeight;
        camera.aspect = w / h;
        camera.updateProjectionMatrix();
        renderer.setSize(w, h);
    };

    const destroy = () => {
        cancelAnimationFrame(frameId);
        window.removeEventListener('resize', handleResize);
        window.removeEventListener('mousemove', handleMouseMove);
        
        window.CinematicDispose?.clear(scene);
        renderer?.dispose();
        canvas?.remove();
        isInitialized = false;
    };

    return { init, destroy };
})();
