import { LocationEntityModel } from "../models/LocationEntityModel.js";
import { CampaignEntityDisclosureManager } from "../services/CampaignEntityDisclosureManager.js";
import { CampaignEntityVisibilityManager } from "../services/CampaignEntityVisibilityManager.js";
import { LocationEntityStore } from "../services/LocationEntityStore.js";

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

export class LocationLimitedPreview extends HandlebarsApplicationMixin(ApplicationV2) {
    #locationId = "";
    #entityChangedHook = null;
    #disclosureChangedHook = null;
    #reconciling = false;
    #lastName = "Location";

    static DEFAULT_OPTIONS = {
        id: "augur-nexus-location-limited-preview",
        classes: ["augur-nexus", "location-limited-preview-window"],
        tag: "div",
        window: { title: "Location", resizable: false, minimizable: true },
        position: { width: 390, height: "auto" }
    };

    static PARTS = {
        content: {
            template: "modules/augur-nexus/templates/campaign-entities/location-limited-preview.hbs"
        }
    };

    static show({ locationId = "" } = {}) {
        if (!locationId) return null;
        const app = new this({ locationId });
        app.render(true, { focus: true });
        return app;
    }

    constructor({ locationId = "" } = {}, options = {}) {
        super(options);
        this.#locationId = locationId;
        this.#entityChangedHook = ({ entity, entityType } = {}) => {
            if ((!entity && (!entityType || entityType === "location")) || entity?.id === this.#locationId) void this.#reconcile();
        };
        this.#disclosureChangedHook = ({ entity, entityType } = {}) => {
            if ((!entity && (!entityType || entityType === "location")) || entity?.id === this.#locationId) void this.#reconcile();
        };
        Hooks.on("augurNexusCampaignEntitiesChanged", this.#entityChangedHook);
        Hooks.on("augurNexusCampaignEntityDisclosureChanged", this.#disclosureChangedHook);
    }

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

    _prepareContext() {
        const entity = LocationEntityStore.getLocation(this.#locationId);
        if (!entity) return { missing: true, name: "Missing Location", imageSrc: "", accent: "#d18a42" };
        this.#lastName = LocationEntityModel.getName(entity);
        return {
            missing: false,
            name: this.#lastName,
            imageSrc: LocationEntityModel.getThumbnail(entity) || LocationEntityModel.getImage(entity),
            accent: LocationEntityModel.getAccent(entity)
        };
    }

    _onRender(context, options) {
        super._onRender(context, options);
        if (this.window?.title) this.window.title.textContent = this.title;
    }

    async close(options) {
        if (this.#entityChangedHook) Hooks.off("augurNexusCampaignEntitiesChanged", this.#entityChangedHook);
        if (this.#disclosureChangedHook) Hooks.off("augurNexusCampaignEntityDisclosureChanged", this.#disclosureChangedHook);
        return super.close(options);
    }

    async #reconcile() {
        if (this.#reconciling) return;
        this.#reconciling = true;
        try {
            const entity = LocationEntityStore.getLocation(this.#locationId);
            if (!entity || !CampaignEntityVisibilityManager.canUserSee(entity, game.user)) {
                await this.close();
                return;
            }
            if (CampaignEntityDisclosureManager.canUserViewDetails(entity, game.user)) {
                await this.close();
                const { openLocation } = await import("../../../api/locations.js");
                await openLocation(entity);
                return;
            }
            if (this.rendered !== false) this.render({ parts: ["content"] });
        } finally {
            this.#reconciling = false;
        }
    }
}
