import * as THREE from 'three';
import { state, initState } from '../state.js';
import { EffectsManager } from '../effects/EffectsManager.js';
import { createSceneObjects } from '../scene/root.js';
import { animate, onWindowResize } from './animate.js';
import { loadVideoFile, playNextVideo } from './video-player.js';

// --- Initialization ---
export function init() {
    initState();

    // 1. Scene Setup (Dark, Ambient)
    state.scene = new THREE.Scene();
    state.scene.background = new THREE.Color(0x000000); 

    // 2. Camera Setup
    const FOV = 65;
    state.camera = new THREE.PerspectiveCamera(FOV, window.innerWidth / window.innerHeight, 0.1, 1000);
    state.camera.position.set(0, 1.5, 4);
    
    // 3. Renderer Setup
    state.renderer = new THREE.WebGLRenderer({ antialias: true });
    state.renderer.setSize(window.innerWidth, window.innerHeight);
    state.renderer.setPixelRatio(window.devicePixelRatio);
    // Enable shadows on the renderer
    state.renderer.shadowMap.enabled = true;
    state.renderer.shadowMap.type = THREE.PCFSoftShadowMap; // Softer shadows
    
    state.container.appendChild(state.renderer.domElement);

    // 5. Build the entire scene with TV and surrounding objects
    createSceneObjects();

    // 6. Initialize all visual effects via the manager
    state.effectsManager = new EffectsManager(state.scene);

    // --- 8. Debug Visualization Helpers ---
    // Visual aids for the light source positions
    if (state.debugLight && THREE.PointLightHelper) {
        const screenHelper = new THREE.PointLightHelper(state.screenLight, 0.1, 0xff0000); // Red for screen
        state.scene.add(screenHelper);

        // Lamp Helper will now work since lampLight is added to the scene
        const lampHelperPoint = new THREE.PointLightHelper(state.lampLightPoint, 0.1, 0x00ff00); // Green for lamp
        state.scene.add(lampHelperPoint);
    }
    
    // 9. Event Listeners
    window.addEventListener('resize', onWindowResize, false);
    state.fileInput.addEventListener('change', loadVideoFile); 
    
    // Button logic
    state.loadTapeButton.addEventListener('click', () => {
        state.fileInput.click(); 
    });
    
    // Auto-advance to the next video when the current one finishes.
    state.videoElement.addEventListener('ended', playNextVideo);
    
    // Start the animation loop
    animate();
}
