import * as THREE from 'three';

export const FEAR_SETTINGS = {
    HALLWAY_LENGTH: 40,
    HALLWAY_WIDTH: 6,
    HALLWAY_HEIGHT: 5,
    PLAYER_HEIGHT: 3,
    WALL_BUFFER: 0.6,
};

const listeners = new Set<() => void>();

export const fearState = {
    loopCount: 0,
    currentWidth: FEAR_SETTINGS.HALLWAY_WIDTH,
    isRustActive: false,

    subscribe(listener: () => void) {
        listeners.add(listener);
        return () => { listeners.delete(listener); };
    },

    emit() {
        listeners.forEach((listener) => listener());
    },

    update(delta: number) {
        this.isRustActive = this.loopCount >= 3;

        const targetWidth = this.loopCount >= 2 ? 2.5 : FEAR_SETTINGS.HALLWAY_WIDTH;
        const newWidth = THREE.MathUtils.lerp(this.currentWidth, targetWidth, 2 * delta);

        if (Math.abs(this.currentWidth - newWidth) > 0.001) {
            this.currentWidth = newWidth;
            this.emit();
        }
    },

    registerLoop(direction: 'forward' | 'backward') {
        this.loopCount += 1;
        console.log(`Hallway looped ${direction}. Total loops: ${this.loopCount}`);
        this.emit();
    }
};