import * as THREE from 'three';
import { state } from '../state.js';
import { SceneFeature } from './SceneFeature.js';
import sceneFeatureManager from './SceneFeatureManager.js';

export class RoseWindowLight extends SceneFeature {
    constructor() {
        super();
        this.spotlight = null;
        this.helper = null;
        sceneFeatureManager.register(this);
    }

    init() {
        // --- Dimensions for positioning ---
        const length = 40;
        const naveHeight = 15;
        const stageDepth = 5;

        // --- Create the spotlight ---
        this.spotlight = new THREE.SpotLight(0xffffff, 100.0); // White light, high intensity
        this.spotlight.position.set(0, naveHeight, -length / 2 + 10); // Position it at the rose window
        this.spotlight.angle = Math.PI / 9; // A reasonably focused beam
        this.spotlight.penumbra = 0.3; // Soft edges
        this.spotlight.decay = 0.7;
        this.spotlight.distance = 30;

        this.spotlight.castShadow = false;
        this.spotlight.shadow.mapSize.width = 1024;
        this.spotlight.shadow.mapSize.height = 1024;
        this.spotlight.shadow.camera.near = 1;
        this.spotlight.shadow.camera.far = 30;
        this.spotlight.shadow.focus = 1;

        // --- Create a target for the spotlight to aim at ---
        const targetObject = new THREE.Object3D();
        targetObject.position.set(0, 0, -length / 2 + stageDepth); // Aim at the center of the stage
        state.scene.add(targetObject);
        this.spotlight.target = targetObject;

        state.scene.add(this.spotlight);

        // --- Add a debug helper ---
        if (state.debugLight) {
            this.helper = new THREE.SpotLightHelper(this.spotlight);
            state.scene.add(this.helper);
        }
    }

    update(deltaTime) {
        if (!this.spotlight) return;

        // Make the light pulse with the music
        if (state.music) {
            const baseIntensity = 4.0;
            this.spotlight.intensity = baseIntensity + state.music.beatIntensity * 1.0;
        }

        // Update the helper if it exists
        if (this.helper) {
            this.helper.update();
        }
    }
}

new RoseWindowLight();