import { BaseItemSheetL5r5e } from "./base-item-sheet.js";

/** Mode Invocation values per invocation type */
const INVOCATION_MODE = {
    general: 3,
    neutre: 0,
    precis: -3,
};

/**
 * Sheet for Mot d'Invocation items (Chiaroscuro).
 * @extends {BaseItemSheetL5r5e}
 */
export class MotInvocationSheetL5r5e extends BaseItemSheetL5r5e {
    /** @override */
    static get defaultOptions() {
        return foundry.utils.mergeObject(super.defaultOptions, {
            classes: ["l5r5e", "sheet", "mot-invocation"],
            template: CONFIG.l5r5e.paths.templates + "items/mot_invocation/mot-invocation-sheet.html",
            width: 500,
            height: 360,
        });
    }

    /** @override */
    async getData(options = {}) {
        const sheetData = await super.getData(options);

        // Build invocation types list from i18n
        const invTypes = game.l5r5e.HelpersL5r5e.getLocalizedRawObject("chiaroscuro.technique.invocation_types") ?? {};
        sheetData.data.invocationTypesList = [{ id: "", label: "—" }].concat(
            Object.entries(invTypes).map(([id, label]) => ({ id, label }))
        );

        sheetData.data.enrichedHtml = {
            description: await foundry.applications.ux.TextEditor.implementation.enrichHTML(
                sheetData.data.system.description ?? "",
                { async: true }
            ),
        };

        return sheetData;
    }

    /** @override */
    activateListeners(html) {
        super.activateListeners(html);

        if (!this.isEditable) return;

        html.find("#mot_invocation_type").on("change", async (event) => {
            const type = event.target.value;
            const mode = INVOCATION_MODE[type] ?? 0;
            // Update stored value and refresh display
            await this.object.update({ system: { invocation_type: type, mode_invocation: mode } });
            this.render(true);
        });
    }
}
