import { Container, Graphics, PixelText, ensurePixelFont, type Scene } from '@rpg/engine';
import { Game } from '../Game';
import { AREAS } from '../data/locations';
import { MenuScene } from './MenuScene';

/**
 * Загрузочная сцена: грузит ассеты с прогресс-баром, затем меню.
 */
export class BootScene implements Scene {
    private view = new Container();
    private bar: Graphics;
    private started = false;
    private progress = -1;

    constructor(private game: Game) {
        const label = new PixelText({
            text: 'пепел оседает...',
            size: 11,
            color: 0x8a8a9a
        });
        label.anchor.set(0.5);
        label.position.set(240, 120);
        this.bar = new Graphics();
        this.view.addChild(label, this.bar);
        this.game.renderer.uiRoot.addChild(this.view);
    }

    enter(): void {}

    exit(): void {
        this.view.destroy({ children: true });
    }

    update(_dt: number): void {
        if (!this.started) {
            this.started = true;
            void this.game.assets
                .load(Game.ASSET_KEYS, (p) => {
                    this.progress = p;
                })
                .then(async () => await this.game.assets.loadAtlas('chars/hero_sheet.json'))
                .then(async () => await this.game.assets.loadAtlas('chars/clumps_sheet.json'))
                .then(async () => await this.game.assets.loadAtlas('chars/fauna_sheet.json'))
                .then(async () => {
                    // Карты областей: файлы .map (rpg-map, RLE) -> parseMap.
                    for (const id of Object.keys(AREAS)) {
                        await this.game.loadMap(id);
                    }
                })
                .then(() => ensurePixelFont(Game.FONT_URL))
                // Звуки: декодируем заранее, чтобы первый play не тормозил.
                .then(async () => {
                    for (const key of Game.AUDIO_KEYS) {
                        await this.game.audio.load(key);
                        await this.game.audio.preload(key);
                    }
                })
                .then(() => {
                    this.progress = 1;
                    console.log('[boot] ассеты загружены, меню...'); // маяк для смоук-тестов
                    void this.game.scenes.replace(new MenuScene(this.game), { duration: 0.3 });
                })
                .catch((err) => {
                    console.error('[boot] ошибка загрузки:', err);
                });
        }
        if (this.progress >= 0) {
            this.drawBar(this.progress);
            this.progress = -1; // перерисовать один раз на изменение
        }
    }

    private drawBar(p: number): void {
        this.bar.clear();
        this.bar.rect(180, 136, 120, 6).fill(0x23232b);
        this.bar.rect(180, 136, Math.round(120 * p), 6).fill(0xd99a32);
    }

    render(): void {}
}