'use strict';

/**
 * Builds the list of language options that should actually be shown.
 *
 * What it does:
 * - Reads the backend-provided language selector model
 * - Checks page <link rel="alternate" hreflang="..."> tags
 * - If hreflang tags exist, only languages with matching tags are shown
 * - If no hreflang tags exist, all backend-provided languages are shown
 */
function getLanguageOptions(languageSelector) {
    if (!languageSelector?.languages?.length) {
        return [];
    }
    const hrefLangTags = Array.from(document.querySelectorAll('link[rel="alternate"][hreflang]'));
    const hrefLangs = hrefLangTags.map(tag => {
        let value = tag.getAttribute('hreflang') ?? '';
        if (value.indexOf('en-') !== -1 || value.indexOf('en_') !== -1) {
            value = value.substring(0, 2);
        }
        return value;
    });
    if (!hrefLangs.length) {
        return [...languageSelector.languages];
    }
    return languageSelector.languages.filter(option => hrefLangs.includes(option.twoLetterISOLanguageName));
}
/**
 * Resolves the URL for a given language option.
 *
 * What it does:
 * - Returns null in SPA mode so language switching can be handled by events only
 * - Uses an existing hreflang alternate URL if one exists in the document
 * - Otherwise falls back to generating a language URL from the site definition
 */
function getLanguageVersionUrl(item, siteDefinition, spaMode) {
    if (spaMode) {
        return null;
    }
    const alternativeTag = document.querySelector(`link[rel="alternate"][hreflang="${item.twoLetterISOLanguageName}"]`);
    if (alternativeTag) {
        return alternativeTag.getAttribute('href');
    }
    const siteUrl = siteDefinition?.url ?? '/';
    return siteUrl + (siteUrl.lastIndexOf('/') !== siteUrl.length - 1 ? '/' : '') + item.twoLetterISOLanguageName;
}

/**
 * Adds a Home item at the beginning of the main menu when needed.
 *
 * What it does:
 * - Returns the input untouched when hideHomeMenuItem is true
 * - Avoids adding a duplicate Home item if one already exists first in the list
 * - Otherwise prepends a synthetic Home item using the translated label
 */
function prependHomeMenuItem(items, i18n, homeUrl, hideHomeMenuItem) {
    if (hideHomeMenuItem) {
        return items;
    }
    if (items[0]?.name === i18n.menuHomeButton) {
        return items;
    }
    return [
        {
            href: homeUrl,
            name: i18n.menuHomeButton,
            id: 'homelink',
            open: false,
            selected: false,
            children: [],
        },
        ...items,
    ];
}
/**
 * Creates a stable-ish tracking id for promoted menu items.
 *
 * This mirrors the old wrapper behavior and is used when rendering promoted links.
 */
function promotedItemId(item) {
    return 'promo-' + item.linkText.replace(/[^A-Za-z0-9.\\\/]/gim, '');
}

function getLastMenuItem(menuItems) {
    return menuItems.length > 0
        ? menuItems[menuItems.length - 1]
        : null;
}
function getModeRoots(menuItems) {
    if (menuItems.length <= 1) {
        return [];
    }
    return menuItems.slice(0, -1);
}
/**
 * Header menu mode utilities.
 *
 * Purpose
 * -------
 * Interprets the backend top-level menu structure used for header menu
 * switching.
 *
 * Expected top-level order:
 * - all items except the last = switchable root menus
 * - last item = shared/common root
 *
 * Responsibilities
 * ----------------
 * - extract a structured representation of the switchable menu roots
 * - resolve the active root for a selected mode
 * - return grouped or flat visible items for rendering
 */
function extractToggleableMenuStructure(menuItems) {
    const sharedRoot = getLastMenuItem(menuItems);
    const modeRoots = getModeRoots(menuItems);
    const menuModeOptions = modeRoots.map((root, index) => ({
        index,
        label: root.name,
        href: root.href || undefined,
        root,
    }));
    return {
        hasMenuSwitching: menuModeOptions.length > 0,
        modeRoots,
        menuModeOptions,
        sharedRoot,
        sharedItems: sharedRoot?.children ?? [],
    };
}
/**
 * Returns the active root item for the selected mode.
 *
 * Falls back to the first available mode root when the requested mode
 * is out of bounds.
 */
function getToggleRootForMode(structure, mode) {
    return structure.modeRoots[mode] ?? structure.modeRoots[0] ?? null;
}
/**
 * Returns the active root item for the selected mode directly from raw menu items.
 */
function getToggleRootForMenuItems(menuItems, mode) {
    const structure = extractToggleableMenuStructure(menuItems);
    return getToggleRootForMode(structure, mode);
}
/**
 * Returns grouped visible items for rendering.
 *
 * - primaryItems = children of the active root
 * - sharedItems = children of the shared/common root
 */
function getMenuGroupsForMode(structure, mode) {
    const activeRoot = getToggleRootForMode(structure, mode);
    if (!activeRoot) {
        return {
            primaryItems: structure.sharedItems,
            sharedItems: [],
        };
    }
    return {
        primaryItems: activeRoot?.children ?? [],
        sharedItems: structure.sharedItems,
    };
}
/**
 * Returns grouped visible items directly from raw menu items.
 */
function getVisibleMenuGroupsForMode(menuItems, mode) {
    const structure = extractToggleableMenuStructure(menuItems);
    return getMenuGroupsForMode(structure, mode);
}
/**
 * Builds a flat list of visible menu items for the selected mode.
 *
 * Useful for render paths that do not need grouped rendering.
 */
function buildMenuItemsForMode(structure, mode) {
    const groups = getMenuGroupsForMode(structure, mode);
    return [
        ...groups.primaryItems,
        ...groups.sharedItems,
    ];
}

function normalizeHeaderTheme(theme) {
    switch (theme?.toLowerCase()) {
        case 'business':
            return 'business';
        case 'private':
            return 'private';
        default:
            return 'private';
    }
}
function getAppearanceForTheme(theme) {
    switch (normalizeHeaderTheme(theme)) {
        case 'private':
            return 'light';
        case 'business':
            return 'dark';
        default:
            return 'light';
    }
}
function resolveHeaderMenuThemes(menuThemes, menuModeOptions) {
    //1. Prop override
    if (menuThemes) {
        try {
            const parsed = JSON.parse(menuThemes);
            if (Array.isArray(parsed)) {
                const filtered = parsed
                    .filter((item) => typeof item === 'string')
                    .map(item => normalizeHeaderTheme(item));
                if (filtered.length > 0) {
                    return filtered;
                }
            }
        }
        catch (error) {
            console.warn('[pn-marketweb-header] Invalid menu-themes value', error);
        }
    }
    // 2. Fallback → VM
    if (!Array.isArray(menuModeOptions)) {
        return [];
    }
    return menuModeOptions
        .map(option => option?.root?.toggleTheme)
        .filter((theme) => typeof theme === 'string')
        .map(theme => normalizeHeaderTheme(theme));
}

exports.buildMenuItemsForMode = buildMenuItemsForMode;
exports.extractToggleableMenuStructure = extractToggleableMenuStructure;
exports.getAppearanceForTheme = getAppearanceForTheme;
exports.getLanguageOptions = getLanguageOptions;
exports.getLanguageVersionUrl = getLanguageVersionUrl;
exports.getToggleRootForMenuItems = getToggleRootForMenuItems;
exports.getVisibleMenuGroupsForMode = getVisibleMenuGroupsForMode;
exports.prependHomeMenuItem = prependHomeMenuItem;
exports.promotedItemId = promotedItemId;
exports.resolveHeaderMenuThemes = resolveHeaderMenuThemes;

//# sourceMappingURL=header-theme-a250bf67.js.map