/**
 * WebAudio с четырьмя шинами (master/music/sfx/ambience): громкости по шинам,
 * кроссфейд лупов (музыка и амбиент — независимые слоты), опции sfx
 * (громкость/скорость/панорама), кэш сэмплов. Игры подключают Settings.onChange
 * и вызывают setBusVolume.
 */

export interface AudioBuses {
    master: GainNode;
    music: GainNode;
    sfx: GainNode;
    ambience: GainNode;
}

export type BusName = 'master' | 'music' | 'sfx' | 'ambience';

export interface MusicHandle {
    stop(fadeSeconds?: number): void;
    /** Задать громкость сразу (для медленных тик-фейдов поверх — локальные слои). */
    setVolume(volume: number): void;
}

/** Опции разового sfx. */
export interface PlayOptions {
    /** Относительная громкость в шине sfx (0..1+). */
    volume?: number;
    /** Скорость воспроизведения 0.5..2 (джиттер шагов, вариации тона). */
    rate?: number;
    /** Панорама -1..1; |pan| < 0.01 — узел StereoPanner не создаётся. */
    pan?: number;
}

interface LoopOptions {
    loop?: boolean;
    fade?: number;
    volume?: number;
    bus?: BusName;
}

/** Запущенный луп: источник + его огибающая громкости. */
interface Slot {
    source: AudioBufferSourceNode;
    gain: GainNode;
}

const DEFAULT_FADE = 1;
const MIN_FADE_VOLUME = 0.0001;

const clamp = (v: number, lo: number, hi: number) => Math.max(lo, Math.min(hi, v));

export class AudioManager {
    private ctx: AudioContext | null = null;
    private buffers = new Map<string, AudioBuffer>();
    private urls = new Map<string, string>();
    private buses: AudioBuses | null = null;
    private currentMusic: Slot | null = null;
    private currentAmbience: Slot | null = null;

    /** Шпионский хук: вызывается при каждом фактическом запуске sfx (тесты, DEV-мост игры). */
    onPlayed?: (key: string, opts: PlayOptions) => void;

    constructor(
        private resolveUrl: (key: string) => string,
        private ctxFactory: () => AudioContext = () => new AudioContext()
    ) {}

    /** Расблокировать аудио — вызвать из обработчика пользовательского ввода. */
    async unlock(): Promise<void> {
        if (!this.ctx) {
            this.ctx = this.ctxFactory();
            const master = this.ctx.createGain();
            const music = this.ctx.createGain();
            const sfx = this.ctx.createGain();
            const ambience = this.ctx.createGain();
            music.connect(master);
            sfx.connect(master);
            ambience.connect(master);
            master.connect(this.ctx.destination);
            this.buses = { master, music, sfx, ambience };
        }
        if (this.ctx.state === 'suspended') {
            await this.ctx.resume();
        }
    }

    /** Громкость шины 0..1 (до unlock шин ещё нет — вызов игнорируется). */
    setBusVolume(bus: BusName, volume: number): void {
        if (this.buses) {
            this.buses[bus].gain.value = Math.max(0, Math.min(1, volume));
        }
    }

    async load(key: string): Promise<void> {
        this.urls.set(key, this.resolveUrl(key));
    }

    /**
     * Декодировать заранее (после unlock, например в сцене загрузки),
     * чтобы первый play не тратил время на fetch+decode.
     */
    async preload(key: string): Promise<void> {
        const ctx = await this.ensureContext();
        if (!ctx) return;
        await this.decode(key);
    }

    /**
     * Проиграть sfx (если звук не загружен — тихо ничего не делает).
     * opts — число (громкость, обратная совместимость) или PlayOptions.
     */
    async play(key: string, opts?: number | PlayOptions): Promise<void> {
        const o: PlayOptions = typeof opts === 'number' ? { volume: opts } : (opts ?? {});
        const ctx = await this.ensureContext();
        if (!ctx) return;
        const buf = await this.decode(key);
        if (!buf) return;

        const volume = o.volume ?? 1;
        const rate = clamp(o.rate ?? 1, 0.5, 2);
        const pan = clamp(o.pan ?? 0, -1, 1);

        const source = ctx.createBufferSource();
        source.buffer = buf;
        source.playbackRate.value = rate;
        const gain = ctx.createGain();
        gain.gain.value = volume;
        source.connect(gain);
        if (Math.abs(pan) >= 0.01 && typeof ctx.createStereoPanner === 'function') {
            const panner = ctx.createStereoPanner();
            panner.pan.value = pan;
            gain.connect(panner).connect(this.buses!.sfx);
        } else {
            gain.connect(this.buses!.sfx);
        }
        source.start();
        this.onPlayed?.(key, { volume, rate, pan });
    }

    /**
     * Играть луп в заданной шине; НЕ занимает ни слот музыки, ни слот амбиента —
     * база для локальных амбиент-слоёв (несколько параллельных лупов).
     */
    async playLoop(key: string, { loop = true, fade = DEFAULT_FADE, volume = 1, bus = 'music' }: LoopOptions = {}): Promise<MusicHandle | null> {
        const slot = await this.startLoop(key, { loop, fade, volume, bus });
        if (!slot) return null;
        return this.makeHandle(slot, fade);
    }

    /** Handle над слотом: затухание + мгновенная громкость (без борьбы с ramp). */
    private makeHandle(slot: Slot, fade: number): MusicHandle {
        return {
            stop: (fadeSeconds = fade) => this.fadeOut(slot, fadeSeconds),
            setVolume: (volume: number) => {
                if (!this.ctx) return;
                const t = this.ctx.currentTime;
                slot.gain.gain.cancelScheduledValues(t);
                slot.gain.gain.setValueAtTime(Math.max(0, volume), t);
            }
        };
    }

    /**
     * Играть музыку с кроссфейдом: текущий трек затухает, новый нарастает
     * за fadeSeconds. Слот один — повторный вызов вытесняет прежний трек.
     */
    async playMusic(key: string, { loop = true, fade = DEFAULT_FADE, volume = 1 }: Omit<LoopOptions, 'bus'> = {}): Promise<MusicHandle | null> {
        const ctx = await this.ensureContext();
        if (!ctx) return null;
        // Сначала проверяем ключ: негодный не должен заглушить текущий трек.
        if (!(await this.decode(key))) return null;
        this.stopMusic(fade);
        const slot = await this.startLoop(key, { loop, fade, volume, bus: 'music' });
        if (!slot) return null;
        this.currentMusic = slot;
        return this.makeHandle(slot, fade);
    }

    /** Остановить музыку (с затуханием). */
    stopMusic(fadeSeconds = 0.5): void {
        const current = this.currentMusic;
        if (!current) return;
        this.currentMusic = null;
        this.fadeOut(current, fadeSeconds);
    }

    /**
     * Играть амбиент с кроссфейдом — слот отдельный от музыки:
     * playAmbience и playMusic не вытесняют друг друга.
     */
    async playAmbience(key: string, { fade = DEFAULT_FADE, volume = 1 }: { fade?: number; volume?: number } = {}): Promise<MusicHandle | null> {
        const ctx = await this.ensureContext();
        if (!ctx) return null;
        if (!(await this.decode(key))) return null;
        this.stopAmbience(fade);
        const slot = await this.startLoop(key, { loop: true, fade, volume, bus: 'ambience' });
        if (!slot) return null;
        this.currentAmbience = slot;
        return this.makeHandle(slot, fade);
    }

    /** Остановить амбиент (с затуханием). */
    stopAmbience(fadeSeconds = 0.5): void {
        const current = this.currentAmbience;
        if (!current) return;
        this.currentAmbience = null;
        this.fadeOut(current, fadeSeconds);
    }

    /** Общий запуск лупа (источник + линейное нарастание громкости). */
    private async startLoop(key: string, { loop, fade, volume, bus }: Required<LoopOptions>): Promise<Slot | null> {
        const ctx = await this.ensureContext();
        if (!ctx) return null;
        const buf = await this.decode(key);
        if (!buf) return null;

        const source = ctx.createBufferSource();
        source.buffer = buf;
        source.loop = loop;
        const gain = ctx.createGain();
        gain.gain.setValueAtTime(MIN_FADE_VOLUME, ctx.currentTime);
        gain.gain.linearRampToValueAtTime(volume, ctx.currentTime + fade);
        source.connect(gain).connect(this.buses![bus]);
        source.start();
        return { source, gain };
    }

    /** Затухание слота и остановка источника после fadeSeconds. */
    private fadeOut(slot: Slot, fadeSeconds: number): void {
        if (!this.ctx) return;
        const t = this.ctx.currentTime;
        slot.gain.gain.cancelScheduledValues(t);
        slot.gain.gain.setValueAtTime(slot.gain.gain.value, t);
        slot.gain.gain.linearRampToValueAtTime(MIN_FADE_VOLUME, t + fadeSeconds);
        setTimeout(() => {
            try {
                slot.source.stop();
            } catch {
                // уже остановлен
            }
        }, fadeSeconds * 1000 + 50);
    }

    private async ensureContext(): Promise<AudioContext | null> {
        await this.unlock();
        return this.ctx;
    }

    private async decode(key: string): Promise<AudioBuffer | null> {
        if (!this.ctx) return null;
        let buf = this.buffers.get(key);
        const url = this.urls.get(key);
        if (!buf && url) {
            try {
                const res = await fetch(url);
                buf = await this.ctx.decodeAudioData(await res.arrayBuffer());
                this.buffers.set(key, buf);
            } catch (err) {
                console.warn(`[audio] не удалось декодировать ${key}:`, err);
                return null;
            }
        }
        return buf ?? null;
    }
}