export class LocationViewRegistry {
    static #views = new Map();

    static register(definition = {}) {
        const id = String(definition.id || "").trim();
        if (!id || typeof definition.open !== "function") throw new Error("Location views require an id and open function.");
        const view = {
            id,
            moduleId: String(definition.moduleId || "").trim(),
            label: String(definition.label || id).trim(),
            description: String(definition.description || "").trim(),
            icon: String(definition.icon || "fas fa-map").trim(),
            priority: Number(definition.priority || 0),
            isPrimary: typeof definition.isPrimary === "function"
                ? definition.isPrimary
                : () => definition.primary === true,
            isAvailable: typeof definition.isAvailable === "function" ? definition.isAvailable : () => true,
            open: definition.open
        };
        this.#views.set(id, view);
        Hooks.callAll("augurNexusLocationViewsChanged", { view: this.#public(view) });
        return this.#public(view);
    }

    static listFor(entity = {}) {
        return [...this.#views.values()]
            .filter(view => this.#isAvailable(view, entity))
            .sort((left, right) => (right.priority - left.priority) || left.label.localeCompare(right.label))
            .map(view => this.#public(view, entity));
    }

    static getPrimaryFor(entity = {}) {
        const view = [...this.#views.values()]
            .filter(candidate => this.#isAvailable(candidate, entity) && this.#isPrimary(candidate, entity))
            .sort((left, right) => (right.priority - left.priority) || left.label.localeCompare(right.label))[0];
        return view ? this.#public(view, entity) : null;
    }

    static async open(id, entity = {}) {
        const view = this.#views.get(String(id || "").trim());
        if (!view || !this.#isAvailable(view, entity)) return null;
        return view.open(entity);
    }

    static #isAvailable(view, entity) {
        try { return view.isAvailable(entity) !== false; }
        catch (error) {
            console.warn(`Augur: Nexus | Location view ${view.id} availability check failed.`, error);
            return false;
        }
    }

    static #isPrimary(view, entity) {
        try { return view.isPrimary(entity) === true; }
        catch (error) {
            console.warn(`Augur: Nexus | Location view ${view.id} primary check failed.`, error);
            return false;
        }
    }

    static #public(view, entity = null) {
        return {
            id: view.id,
            moduleId: view.moduleId,
            label: view.label,
            description: view.description,
            icon: view.icon,
            priority: view.priority,
            primary: entity ? this.#isPrimary(view, entity) : false
        };
    }
}
