const { ApplicationV2, HandlebarsApplicationMixin } = foundry.applications.api;

export class TradeGoodsPickerApplication extends HandlebarsApplicationMixin(ApplicationV2) {
    #title = "Select Trade Goods";
    #goods = [];
    #selectedIds = new Set();
    #onApply = null;

    static DEFAULT_OPTIONS = {
        id: "augur-nexus-trade-goods-picker",
        classes: ["augur-nexus", "augur-theme-fantasy", "trade-goods-picker"],
        tag: "div",
        window: { title: "Select Trade Goods", resizable: true, minimizable: true },
        position: { width: 470, height: 620 },
        actions: {
            applyTradeGoods: TradeGoodsPickerApplication._onApply,
            closeTradeGoodsPicker: TradeGoodsPickerApplication._onClose
        }
    };

    static PARTS = { content: { template: "modules/augur-nexus/templates/trade/trade-goods-picker.hbs" } };

    static show({ title = "Select Trade Goods", goods = [], selectedIds = [], onApply = null } = {}) {
        const app = new this({ title, goods, selectedIds, onApply });
        app.render(true, { focus: true });
        return app;
    }

    constructor({ title = "Select Trade Goods", goods = [], selectedIds = [], onApply = null } = {}, options = {}) {
        super(options);
        this.#title = String(title || "Select Trade Goods");
        this.#goods = foundry.utils.deepClone(goods || []);
        this.#selectedIds = new Set((selectedIds || []).map(String));
        this.#onApply = typeof onApply === "function" ? onApply : null;
    }

    get title() { return this.#title; }

    _prepareContext() {
        return {
            title: this.#title,
            goods: this.#goods.map(good => ({ ...good, selected: this.#selectedIds.has(String(good.id)) })),
            selectedCount: this.#selectedIds.size
        };
    }

    _onRender(context, options) {
        super._onRender(context, options);
        if (this.window?.title) this.window.title.textContent = this.#title;
        const search = this.element.querySelector("[data-trade-picker-search]");
        search?.addEventListener("input", () => this.#filter(search.value));
        this.element.querySelectorAll("[name='tradeGoodId']").forEach(input => {
            input.addEventListener("change", () => this.#updateCount());
        });
    }

    static _onApply() {
        const selectedIds = [...this.element.querySelectorAll("[name='tradeGoodId']:checked")].map(input => String(input.value));
        this.#onApply?.(selectedIds);
        return this.close();
    }

    static _onClose() { return this.close(); }

    #filter(value) {
        const query = String(value || "").trim().toLocaleLowerCase();
        this.element.querySelectorAll("[data-trade-picker-good]").forEach(row => {
            row.hidden = !!query && !String(row.dataset.searchText || "").toLocaleLowerCase().includes(query);
        });
    }

    #updateCount() {
        const count = this.element.querySelectorAll("[name='tradeGoodId']:checked").length;
        const output = this.element.querySelector("[data-trade-picker-count]");
        if (output) output.textContent = String(count);
    }
}
