import { ShopEditorRegistry } from "./ShopEditorRegistry.js";

const MODULES_URL = "https://www.patreon.com/TheAugur";

export class ShopCreationGateway {
    static #capabilities = new Map();

    static registerCapability(definition = {}) {
        const id = String(definition.id || "").trim();
        const moduleId = String(definition.moduleId || "").trim();
        if (!id || !moduleId) throw new Error("Shop creation capabilities require an id and moduleId.");
        const capability = { id, moduleId };
        this.#capabilities.set(id, capability);
        Hooks.callAll("augurNexusShopCreationCapabilitiesChanged", { reason: "register", capability: { ...capability } });
        return { ...capability };
    }

    static canCreate() {
        return this.#capabilities.size > 0;
    }

    static async authorize() {
        if (this.canCreate()) return true;
        await this.#showModuleRequiredDialog();
        return false;
    }

    static async open(options = {}) {
        if (!await this.authorize()) return null;
        return ShopEditorRegistry.open(options);
    }

    static async #showModuleRequiredDialog() {
        const safeModulesUrl = foundry.utils.escapeHTML(MODULES_URL);

        return foundry.applications.api.DialogV2.wait({
            window: {
                title: "Module Required",
                icon: "fa-solid fa-circle-info"
            },
            position: {
                width: 440
            },
            content: `
                <p>Creating <strong>shops and marketplaces</strong> in Nexus is powered by Augur content modules.</p>
                <p>Augur content modules unlock stores, regional markets, and the content used to stock them.</p>
                <p class="notes">You can explore the available modules and follow development on <a href="${safeModulesUrl}" target="_blank" rel="noopener noreferrer">Patreon</a>.</p>
            `,
            buttons: [
                {
                    action: "close",
                    label: "Close",
                    icon: "fa-solid fa-xmark"
                },
                {
                    action: "viewModules",
                    label: "View Modules",
                    icon: "fa-solid fa-up-right-from-square",
                    default: true,
                    callback: () => {
                        window.open(MODULES_URL, "_blank", "noopener,noreferrer");
                    }
                }
            ]
        });
    }
}
