import { state } from '../state.js';
import { SceneFeature } from './SceneFeature.js';
import sceneFeatureManager from './SceneFeatureManager.js';

export class MusicVisualizer extends SceneFeature {
    constructor() {
        super();
        sceneFeatureManager.register(this);
    }

    init() {
        // Initialize music state
        state.music = {
            bpm: 120,
            beatDuration: 60 / 120,
            measureDuration: (60 / 120) * 4,
            beatIntensity: 0,
            measurePulse: 0,
            isLoudEnough: false,
        };
    }

    update(deltaTime) {
        if (!state.music || !state.partyStarted) return;

        const time = state.clock.getElapsedTime();

        // --- Calculate Beat Intensity (pulses every beat) ---
        // This creates a sharp attack and slower decay (0 -> 1 -> 0)
        const beatProgress = (time % state.music.beatDuration) / state.music.beatDuration;
        state.music.beatIntensity = Math.pow(1.0 - beatProgress, 2);

        // --- Calculate Measure Pulse (spikes every 4 beats) ---
        // This creates a very sharp spike for the torch flame effect
        const measureProgress = (time % state.music.measureDuration) / state.music.measureDuration;
        state.music.measurePulse = measureProgress < 0.2 ? Math.sin(measureProgress * Math.PI * 5) : 0;
    }
}

new MusicVisualizer();