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

export class MusicVisualizer extends SceneFeature {
    constructor() {
        super();
        this.lastStateChangeTime = 0;
        this.lastBlackoutMode = false;
        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;

        // --- Auto-Blackout Logic ---
        // If blackout is active, monitor for loud events (The Drop) to disable it.
        if (state.config.blackout) {
            if (state.blackoutMode !== this.lastBlackoutMode) {
                this.lastStateChangeTime = time;
                this.lastBlackoutMode = state.blackoutMode;
            }

            const timeInState = time - this.lastStateChangeTime;

            // Dynamic Thresholds
            // Exit blackout: Start high 0.8 and decrease over time
            let loudThreshold = Math.max(0.4, 0.8 - (timeInState * 0.05));
            
            // Enter blackout: Start low and increase over time
            let quietThreshold = Math.min(0.2, 0.05 + (timeInState * 0.01));

            const beatThreshold = 0.8;

            if (state.blackoutMode) {
                if (state.music.loudness > loudThreshold && state.music.beatIntensity > beatThreshold) {
                    state.blackoutMode = false;
                }
            } else {
                if (state.music.loudness < quietThreshold) {
                    state.blackoutMode = true;
                }
            }
        } else {
            state.blackoutMode = false;
            this.lastBlackoutMode = false;
        }
    }
}

new MusicVisualizer();