const { HandlebarsApplicationMixin } = foundry.applications.api;

export default class MGT2ActorSheet extends HandlebarsApplicationMixin(foundry.applications.sheets.ActorSheetV2) {

    static SHEET_MODES = { EDIT: 0, PLAY: 1 }

    constructor(options = {}) {
        super(options);
        this._sheetMode = this.constructor.SHEET_MODES.PLAY;
    }

    /** @override */
    static DEFAULT_OPTIONS = {
        classes: ["mgt2", "sheet", "actor"],
        position: {
            width: 780,
        },
        form: {
            submitOnChange: true,
            closeOnSubmit: false,
        },
        window: {
            resizable: true,
        },
        dragDrop: [{ dragSelector: ".drag-item-list", dropSelector: ".drop-item-list" }],
        actions: {
            toggleSheet: MGT2ActorSheet.#onToggleSheet,
        },
    }

    get isPlayMode() {
        if (this._sheetMode === undefined) this._sheetMode = this.constructor.SHEET_MODES.PLAY;
        return this._sheetMode === this.constructor.SHEET_MODES.PLAY;
    }

    get isEditMode() {
        if (this._sheetMode === undefined) this._sheetMode = this.constructor.SHEET_MODES.PLAY;
        return this._sheetMode === this.constructor.SHEET_MODES.EDIT;
    }

    tabGroups = { sidebar: "health" }

    /** @override */
    async _prepareContext() {
        const base = await super._prepareContext();
        const actor = this.document;
        return {
            ...base,
            actor: actor,
            // Flat shorthands for template backward-compat (AppV1 style)
            name: actor.name,
            img: actor.img,
            cssClass: this.isEditable ? "editable" : "locked",
            system: actor.system,
            source: actor.toObject(),
            fields: actor.schema.fields,
            systemFields: actor.system.schema.fields,
            isEditable: this.isEditable,
            isEditMode: this.isEditMode,
            isPlayMode: this.isPlayMode,
            isGM: game.user.isGM,
            config: CONFIG.MGT2,
        };
    }

    /** @override */
    _onRender(context, options) {
        super._onRender(context, options);
        // Inject theme class dynamically (can't use game.settings in static DEFAULT_OPTIONS)
        const theme = game.settings.get("mgt2", "theme");
        if (theme) this.element.classList.add(theme);
        this._activateTabGroups();
    }

    _activateTabGroups() {
        for (const [group, activeTab] of Object.entries(this.tabGroups)) {
            const nav = this.element.querySelector(`nav[data-group="${group}"]`);
            if (!nav) continue;

            nav.querySelectorAll('[data-tab]').forEach(link => {
                link.classList.toggle('active', link.dataset.tab === activeTab);
                link.addEventListener('click', event => {
                    event.preventDefault();
                    this.tabGroups[group] = link.dataset.tab;
                    this.render();
                });
            });

            this.element.querySelectorAll(`[data-group="${group}"][data-tab]`).forEach(content => {
                content.classList.toggle('active', content.dataset.tab === activeTab);
            });
        }
    }

    /** @override */
    _canDragDrop(selector) {
        return this.isEditable;
    }

    static async #onToggleSheet(event) {
        event.preventDefault();
        this._sheetMode = this.isPlayMode
            ? this.constructor.SHEET_MODES.EDIT
            : this.constructor.SHEET_MODES.PLAY;
        this.render();
    }
}
