import * as THREE from 'three';

export const FEAR_SETTINGS = {
    HALLWAY_LENGTH: 40,
    HALLWAY_WIDTH: 6,
    HALLWAY_HEIGHT: 5,
    PLAYER_HEIGHT: 3,
    PLAYER_SPEED: 4,
    FLASHLIGHT_INTENSITY_BASE: 8,
    WALL_BUFFER: 0.6,
    CREATURE_SPEED: 8,

    EVENT_NARROW_LOOP_COUNT: 2,
    EVENT_RUST_LOOP_COUNT: 4,
    EVENT_FINALE_LOOP_COUNT: 5
};

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

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

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

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

    update(delta: number) {
        const targetWidth = this.loopCount >= FEAR_SETTINGS.EVENT_NARROW_LOOP_COUNT ? 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;

        this.isRustActive = this.loopCount >= FEAR_SETTINGS.EVENT_RUST_LOOP_COUNT;
        this.finaleTriggered = this.loopCount >= FEAR_SETTINGS.EVENT_FINALE_LOOP_COUNT;

        this.emit();
    },

    registerCaught() {
        this.wasCaught = true;
        this.emit();
    }
};