import { Container } from 'pixi.js';
import { Button } from './Button';
import { ListCursor } from './listCursor';

/**
 * Вертикальное меню: список кнопок с клавиатурным фокусом и навигацией.
 * Игра сама читает ввод и вызывает moveCursor/activate — движок не привязан к раскладке.
 */
export interface MenuListOptions {
    width: number;
    height: number;
    /** Отступ между кнопками (виртуальные пиксели). */
    gap?: number;
    size?: number;
}

export class MenuList extends Container {
    private buttons: Button[] = [];
    private listCursor: ListCursor;

    constructor(private options: MenuListOptions) {
        super();
        this.listCursor = new ListCursor(0);
    }

    /** Пересобрать список пунктов (старые кнопки уничтожаются). */
    setItems(
        items: { label: string; onSelect?: () => void }[]
    ): void {
        for (const b of this.buttons) b.destroy({ children: true });
        this.buttons = [];
        let y = 0;
        for (const item of items) {
            const btn = new Button({
                label: item.label,
                width: this.options.width,
                height: this.options.height,
                size: this.options.size,
                onSelect: item.onSelect
            });
            btn.position.set(0, y);
            this.addChild(btn);
            this.buttons.push(btn);
            y += this.options.height + (this.options.gap ?? 2);
        }
        this.listCursor.setCount(items.length);
        this.applyFocus();
    }

    /** Сдвинуть фокус (↑ = -1, ↓ = +1). */
    moveCursor(delta: number): void {
        this.listCursor.move(delta);
        this.applyFocus();
    }

    /** Выбранный индекс. */
    get index(): number {
        return this.listCursor.index;
    }

    /** Активировать кнопку под фокусом (Enter). */
    activate(): void {
        this.buttons[this.listCursor.index]?.activate();
    }

    private applyFocus(): void {
        this.buttons.forEach((b, i) => (b.focused = i === this.listCursor.index));
    }
}