import { Container, Panel, PixelText, type Scene } from '@rpg/engine';
import { Game } from '../Game';
import { inventoryItems, questLog } from '../data/quests';

/**
 * Сумка и журнал квестов (панель поверх локации, push/pop).
 * Содержимое собирается из флагов/варов GameState при каждом открытии.
 */
export class InventoryScene implements Scene {
    private view = new Container();

    constructor(private game: Game, private onBack: () => void) {
        const panel = new Panel({ width: 280, height: 180 });
        panel.position.set((Game.VIRTUAL_W - 280) / 2, (Game.VIRTUAL_H - 180) / 2);

        const title = new PixelText({ text: 'ЗВОНАРЬ', size: 14, color: 0xd8c79a });
        title.anchor.set(0.5);
        title.position.set(140, 16);
        panel.addChild(title);

        const addLine = (text: string, color: number, x: number, y: number): void => {
            const t = new PixelText({ text, size: 10, color });
            t.position.set(x, y);
            panel.addChild(t);
        };

        // Инвентарь
        addLine('Сумка', 0x999988, 16, 36);
        let y = 50;
        for (const item of inventoryItems(this.game.inventory)) {
            addLine(item, 0xd8c79a, 24, y);
            y += 13;
        }

        // Журнал квестов
        addLine('Журнал', 0x999988, 16, y + 6);
        y += 21;
        for (const entry of questLog(this.game.state)) {
            const mark = entry.done ? 'x' : '·';
            addLine(`[${mark}] ${entry.text}`, entry.done ? 0xd8c79a : 0xaaaaaa, 24, y);
            y += 13;
        }

        const hint = new PixelText({ text: 'Esc — назад', size: 9, color: 0x777788 });
        hint.anchor.set(0.5);
        hint.position.set(140, 168);
        panel.addChild(hint);

        this.view.addChild(panel);
        this.game.renderer.uiRoot.addChild(this.view);
    }

    enter(): void {}

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

    render(): void {}

    update(_dt: number): void {
        if (this.game.scenes.transitioning) return;
        const input = this.game.engine.input;
        if (input.isActionJustPressed('menu') || input.isActionJustPressed('inventory')) {
            void this.game.audio.play('sfx/ui_click');
            this.onBack();
        }
    }
}