/**
 * Global config from PHP
 */
export function getCfg() {
    const cfg = window?.JetMenuMetaModalConfig || {};

    return {
        ...cfg,
        rolesOptions: Array.isArray(cfg.rolesOptions) ? cfg.rolesOptions : [],
        hasElementor: !!cfg.hasElementor,
    };
}

/**
 * jQuery-based AJAX helper
 */
export function ajaxPostJetMenu({ action, nonce, data }) {
    const config = getCfg();
    const ajaxUrl = config.ajaxUrl || window.ajaxurl;

    return window.jQuery.ajax({
        type: "POST",
        url: ajaxUrl,
        dataType: "json",
        data: {
            action,
            nonce: nonce || config.ajaxNonce || "",
            data: data || {},
        },
    });
}

export function getContentTypeOptions() {
    const cfg = getCfg();
    const hasElementor = !!cfg.hasElementor;

    return hasElementor
        ? [
            { label: "Elementor", value: "elementor" },
            { label: "Default (Block Editor)", value: "default" },
        ]
        : [
            { label: "Default (Block Editor)", value: "default" },
        ];
}

export function normalizeContentTypeValue( rawValue ) {
    const cfg = getCfg();
    const hasElementor = !!cfg.hasElementor;

    let value = rawValue ?? "default";

    if ( ! hasElementor && value === "elementor" ) {
        value = "default";
    }

    return value;
}

/**
 * Default object for dynamic visibility
 */
export const defaultVisibilityObject = {
    enabled: false,
    type: "show",
    relation: "AND",
    rules: [],
};

export function normalizeCustomMegaMenuWidthValue( rawValue ) {
    if ( rawValue === "" || rawValue === null || rawValue === undefined ) {
        return "";
    }

    const value = typeof rawValue === "string" ? rawValue.trim() : rawValue;

    if ( value === "" ) {
        return "";
    }

    const numberValue = Number( value );

    if ( ! Number.isFinite( numberValue ) || numberValue <= 0 ) {
        return "";
    }

    return Math.round( numberValue );
}

export function prepareNavItemSettingsForSave( controlData = {} ) {
    return Object.fromEntries(
        Object.keys( controlData ).map( ( key ) => {
            let value = controlData[ key ].value;

            if ( key === "custom_mega_menu_width" ) {
                value = normalizeCustomMegaMenuWidthValue( value );
            }

            return [ key, value ];
        } )
    );
}

/**
 * Build controlData structure from jet_menu_settings
 */
export function buildControlData( settings = {} ) {
    return {
        enabled: { value: settings.enabled ?? "false" },

        content_type: {
            value: normalizeContentTypeValue(settings.content_type),
            options: getContentTypeOptions(),
        },

        custom_mega_menu_position: {
            value: settings.custom_mega_menu_position ?? "default",
            options: [
                { label: "Default", value: "default" },
                { label: "Relative Item", value: "relative-item" },
            ],
        },

        custom_mega_menu_width: { value: settings.custom_mega_menu_width ?? "" },

        menu_svg: { value: settings.menu_svg ?? "" },
        icon_color: { value: settings.icon_color ?? "" },
        icon_size: { value: settings.icon_size ?? "" },

        menu_badge_type: {
            value: settings.menu_badge_type ?? "text",
            options: [
                { label: "Text", value: "text" },
                { label: "SVG", value: "svg" },
            ],
        },

        menu_badge: { value: settings.menu_badge ?? "" },
        badge_color: { value: settings.badge_color ?? "" },
        badge_bg_color: { value: settings.badge_bg_color ?? "" },
        badge_offset_x: { value: settings.badge_offset_x ?? "" },
        badge_offset_y: { value: settings.badge_offset_y ?? "" },
        badge_svg: { value: settings.badge_svg ?? "" },
        badge_svg_size: { value: settings.badge_svg_size ?? "" },

        hide_item_text: { value: settings.hide_item_text ?? "false" },
        item_padding: { value: settings.item_padding ?? "" },

        dynamic_visibility: {
            value: {
                ...defaultVisibilityObject,
                ...( settings.dynamic_visibility &&
                typeof settings.dynamic_visibility === "object" &&
                ! Array.isArray( settings.dynamic_visibility )
                    ? settings.dynamic_visibility
                    : {} ),
            }
        }
    };
}
