import { Container, Graphics, Text } from 'pixi.js';
import type { Scene } from '@rpg/engine';
import { Game } from '../Game';
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 Text({
            text: 'пепел оседает...',
            style: { fontFamily: 'monospace', fontSize: 8, fill: 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(() => {
                    this.progress = 1;
                    void this.game.scenes.replace(new MenuScene(this.game));
                })
                .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 {}
}