import { playSfx } from '../data/sfxSpecs';
import { MenuList, MenuSceneBase, Panel, PixelText } from '@rpg/engine';
import { Game } from '../Game';
import { questLog } from '../data/quests';
import { itemName, useItemLine } from '../data/items';

/**
 * Сумка и журнал квестов (панель поверх локации, push/pop).
 * Содержимое собирается из флагов/варов GameState при каждом открытии.
 * Список сумки с курсором: Enter — применить предмет (часы показывают время,
 * время в сумке заморожено — локация не тикается). Журнал — текст без фокуса.
 */
export class InventoryScene extends MenuSceneBase {
    constructor(
        private game: Game,
        private onBack: () => void
    ) {
        super(
            { input: game.engine.input, inputBlocked: () => game.scenes.transitioning },
            { up: 'up', down: 'down', confirm: 'advance', cancel: 'menu', extra: ['inventory'] }
        );
    }

    protected build(): 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);
        };

        // Сумка: список с курсором, Enter — применить выбранный предмет.
        addLine('Сумка', 0x999988, 16, 36);
        const slots = this.game.inventory.all;
        const result = new PixelText({ text: '', size: 10, color: 0xf2d49a });
        result.position.set(20, 150);
        panel.addChild(result);
        if (slots.length > 0) {
            this.menu = new MenuList({ width: 240, height: 14, gap: 1, size: 10 });
            this.menu.position.set(20, 48);
            this.menu.setItems(
                slots.map((slot) => ({
                    label: slot.count > 1 ? `${itemName(slot.id)} ×${slot.count}` : itemName(slot.id),
                    onSelect: () => this.useItem(slot.id, result)
                }))
            );
            panel.addChild(this.menu);
        } else {
            addLine('— пусто —', 0x777788, 24, 50);
        }

        // Журнал квестов — ниже сумки, без фокуса.
        const menuBottom = 48 + Math.max(slots.length, 1) * 15;
        addLine('Журнал', 0x999988, 16, menuBottom + 2);
        let y = menuBottom + 17;
        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: 'Enter — применить, 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);
    }

    /** Применить предмет: юза́бельные дают строку-результат, остальные молчат. */
    private useItem(id: string, result: PixelText): void {
        const line = useItemLine(id, { label: this.game.clock.label });
        if (line === null) return;
        playSfx(this.game.audio, 'sfx/ui_click');
        result.text = line;
    }

    /** Esc или клавиша инвентаря — назад в локацию. */
    protected onCancel(): void {
        this.close();
    }

    protected onAction(action: string): void {
        if (action === 'inventory') this.close();
    }

    private close(): void {
        playSfx(this.game.audio, 'sfx/ui_click');
        this.onBack();
    }
}