// assets/js/core/TabConfigRegistry.js

class TabConfigRegistry {
    constructor() {
        this._registry = new Map();
    }

    /**
     * Register a tab config
     */
    register(key, config) {
        if (!key) {
            throw new Error("TabConfigRegistry: key is required");
        }

        if (this._registry.has(key)) {
            console.warn(`TabConfigRegistry: "${key}" already registered`);
            return;
        }

        const normalized = {
            key,
            title: config.title || key,
            icon: config.icon || null,
            fixed: !!config.fixed,
            order: config.order ?? 100,
            permission: config.permission || null,
            ...config
        };

        this._registry.set(key, normalized);
    }

    /**
     * Get config by key
     */
    get(key) {
        return this._registry.get(key) || null;
    }

    /**
     * Check if exists
     */
    has(key) {
        return this._registry.has(key);
    }

    /**
     * Return all configs sorted
     */
    getAll() {
        return [...this._registry.values()]
            .sort((a, b) => a.order - b.order);
    }

    /**
     * Filter configs by permission
     */
    getAvailable(userContext) {
        return this.getAll().filter(cfg => {
            if (!cfg.permission) return true;
            if (!userContext) return false;
            return userContext.permissions?.includes(cfg.permission);
        });
    }
}

const tabConfigRegistry = new TabConfigRegistry();

export default tabConfigRegistry;
