import { doAction } from "@wordpress/hooks";

const DV_REGISTRY_KEY = "__jetMenuDVRegistry";

/**
 * Registry instance (singleton)
 */
function createRegistry() {
    const conditions = {};

    return {
        register( condition ) {
            if ( ! condition || typeof condition !== "object" ) {
                return;
            }

            const name = String( condition.name || "" ).trim();

            if ( ! name ) {
                return;
            }

            conditions[ name ] = {
                name,
                label: condition.label || name,
                defaultAttrs:
                    condition.defaultAttrs && typeof condition.defaultAttrs === "object"
                        ? condition.defaultAttrs
                        : {},
                renderUI:
                    typeof condition.renderUI === "function"
                        ? condition.renderUI
                        : null,
            };
        },

        has( name ) {
            return !!conditions[ name ];
        },

        get( name ) {
            return conditions[ name ] || null;
        },

        all() {
            return conditions;
        },

        getOptions() {
            return Object.keys( conditions ).map( ( key ) => ( {
                label: conditions[ key ].label || key,
                value: key,
            } ) );
        },
    };
}

/**
 * Ensure global namespace.
 */
function ensureGlobalJetMenu() {
    window.JetMenu = window.JetMenu || {};
}

/**
 * Get registry singleton.
 */
export function getVisibilityConditionsRegistry() {
    ensureGlobalJetMenu();

    if ( window.JetMenu[ DV_REGISTRY_KEY ] ) {
        return window.JetMenu[ DV_REGISTRY_KEY ];
    }

    window.JetMenu[ DV_REGISTRY_KEY ] = createRegistry();

    return window.JetMenu[ DV_REGISTRY_KEY ];
}

/**
 * Global API:
 * JetMenu.registerVisibilityCondition( { name, label, defaultAttrs, renderUI } )
 */
export function ensureGlobalVisibilityRegistrationApi() {
    ensureGlobalJetMenu();

    if ( typeof window.JetMenu.registerVisibilityCondition === "function" ) {
        return;
    }

    window.JetMenu.registerVisibilityCondition = function( condition ) {
        const registry = getVisibilityConditionsRegistry();
        registry.register( condition );
    };
}

/**
 * Run centralized registration action:
 * - built-ins hook into "jetMenu.registerConditions"
 * - external code can also hook into it
 */
export function runVisibilityConditionsRegistration() {
    const registry = getVisibilityConditionsRegistry();

    // Fire action where all conditions should be registered.
    doAction( "jetMenu.registerConditions", registry );

    return registry;
}