import { r as registerInstance, c as createEvent, g as getElement, h, F as Fragment, d as Host } from './index-c0a4d8bd.js';
import { F as FetchHelper } from './FetchHelper-4789695a.js';
import { s as state } from './pn-marketweb-siteheader-store-69bcd7eb.js';
import { e as extractToggleableMenuStructure, g as getLanguageOptions, b as buildMenuItemsForMode, p as prependHomeMenuItem, r as resolveHeaderMenuThemes, a as getToggleRootForMenuItems, c as getVisibleMenuGroupsForMode } from './header-theme-d09b64c7.js';
import { t as translations } from './translations-d2f5804e.js';
import './index-a0a6fb88.js';

const ALLOWED_LANGUAGES = [
    'sv',
    'da',
    'fi',
    'no',
    'en',
    'de',
    'zh',
    'fr',
    'es',
    'it',
    'nl',
];
const ALLOWED_MARKETS = [
    'se',
    'dk',
    'fi',
    'no',
    'com',
    'de',
    'tpl',
    'group',
];
const WWW_MARKETS = [
    'se',
    'dk',
    'fi',
    'no',
    'de',
    'com',
];
const DEVELOPMENT_DOMAINS = [
    'localhost',
    '.local',
    'local.',
    '.dev',
    'dev.',
];
const MARKETS = {
    se: {
        fallbackLanguage: 'sv',
        integration: 'se-inte.postnord.com',
        preproduction: 'se-prep.postnord.com',
        production: 'se-prod.postnord.com',
        live: 'www.postnord.se',
    },
    dk: {
        fallbackLanguage: 'da',
        integration: 'dk-inte.postnord.com',
        preproduction: 'dk-prep.postnord.com',
        production: 'dk-prod.postnord.com',
        live: 'www.postnord.dk',
    },
    fi: {
        fallbackLanguage: 'fi',
        integration: 'fi-inte.postnord.com',
        preproduction: 'fi-prep.postnord.com',
        production: 'fi-prod.postnord.com',
        live: 'www.postnord.fi',
    },
    no: {
        fallbackLanguage: 'no',
        integration: 'no-inte.postnord.com',
        preproduction: 'no-prep.postnord.com',
        production: 'no-prod.postnord.com',
        live: 'www.postnord.no',
    },
    com: {
        fallbackLanguage: 'en',
        integration: 'com-inte.postnord.com',
        preproduction: 'com-prep.postnord.com',
        production: 'com-prod.postnord.com',
        live: 'www.postnord.com',
    },
    de: {
        fallbackLanguage: 'en',
        integration: 'de-inte.postnord.com',
        preproduction: 'de-prep.postnord.com',
        production: 'de-prod.postnord.com',
        live: 'www.postnord.de',
    },
    tpl: {
        fallbackLanguage: 'sv',
        integration: 'tpl-inte.postnord.com',
        preproduction: 'tpl-prep.postnord.com',
        production: 'tpl-prod.postnord.com',
        live: 'www.tpl.postnord.com',
    },
    group: {
        fallbackLanguage: 'en',
        integration: 'group-inte.postnord.com',
        preproduction: 'group-prep.postnord.com',
        production: 'group-prod.postnord.com',
        live: 'group.postnord.com',
    },
};
const ENVIRONMENT_ALIASES = {
    integration: 'integration',
    inte: 'integration',
    preproduction: 'preproduction',
    prep: 'preproduction',
    production: 'production',
    prod: 'production',
};

class RefinedMarketWebContextService {
    href;
    doc;
    constructor(options) {
        this.href = options?.href ?? window.location.href;
        this.doc = options?.doc ?? document;
    }
    resolve() {
        const url = new URL(this.href);
        const market = this.resolveMarket(url);
        const environment = this.resolveEnvironment(url);
        const language = this.resolveLanguage(market);
        return {
            market,
            environment,
            language,
        };
    }
    getMarket() {
        return this.resolve().market;
    }
    getEnvironmentName() {
        return this.resolve().environment;
    }
    getLanguage() {
        return this.resolve().language;
    }
    isDevEnvironment() {
        const hostname = new URL(this.href).hostname.toLowerCase();
        return DEVELOPMENT_DOMAINS.some(fragment => hostname.includes(fragment));
    }
    getEndpoint(environment, market) {
        if (environment === 'localhost') {
            return '';
        }
        const currentHostname = new URL(this.href).hostname.toLowerCase();
        const config = MARKETS[market];
        if (environment === 'production' && currentHostname === config.live.toLowerCase()) {
            return `https://${config.live}`;
        }
        if (environment !== 'production' && currentHostname === config[environment].toLowerCase()) {
            return `https://${config[environment]}`;
        }
        if (environment === 'production') {
            if (WWW_MARKETS.includes(market)) {
                return `https://${config.live}`;
            }
            if (market === 'tpl') {
                return 'https://www.tpl.postnord.com';
            }
            return `https://${config.live}`;
        }
        return `https://${config[environment]}`;
    }
    resolveEnvironment(url) {
        const hostname = url.hostname.toLowerCase();
        const matchedAlias = Object.keys(ENVIRONMENT_ALIASES).find(alias => hostname.includes(`-${alias}`));
        if (matchedAlias) {
            return ENVIRONMENT_ALIASES[matchedAlias];
        }
        const isKnownLiveHost = Object.values(MARKETS).some(config => config.live.toLowerCase() === hostname);
        if (isKnownLiveHost || hostname.includes('www.')) {
            return 'production';
        }
        return 'integration';
    }
    resolveMarket(url) {
        const hostname = url.hostname.toLowerCase();
        const fromLiveDomain = this.resolveMarketFromLiveDomain(hostname);
        if (fromLiveDomain)
            return fromLiveDomain;
        const fromEnvironmentHost = this.resolveMarketFromEnvironmentHost(hostname);
        if (fromEnvironmentHost)
            return fromEnvironmentHost;
        const fromPostnordSubdomain = this.resolveMarketFromPostnordSubdomain(hostname);
        if (fromPostnordSubdomain)
            return fromPostnordSubdomain;
        if (this.isDevEnvironment()) {
            const fromDevUrl = this.resolveMarketFromDevelopmentUrl(url);
            if (fromDevUrl)
                return fromDevUrl;
        }
        return 'se';
    }
    resolveLanguage(market) {
        const candidates = [
            this.doc?.documentElement?.getAttribute('lang'),
            this.doc?.querySelector('meta[http-equiv="content-language"]')?.getAttribute('content'),
            this.doc?.querySelector('meta[property="og:locale"]')?.getAttribute('content'),
            this.doc?.querySelector('[lang]')?.getAttribute('lang'),
        ];
        for (const candidate of candidates) {
            const normalized = this.normalizeLanguage(candidate);
            if (normalized) {
                return normalized;
            }
        }
        return MARKETS[market].fallbackLanguage;
    }
    normalizeLanguage(value) {
        if (!value) {
            return undefined;
        }
        const normalized = value.trim().toLowerCase().split(/[-_]/)[0];
        return ALLOWED_LANGUAGES.includes(normalized)
            ? normalized
            : undefined;
    }
    resolveMarketFromLiveDomain(hostname) {
        const matched = Object.entries(MARKETS).find(([, config]) => config.live.toLowerCase() === hostname);
        return matched?.[0];
    }
    resolveMarketFromEnvironmentHost(hostname) {
        const matched = Object.entries(MARKETS).find(([, config]) => [config.integration, config.preproduction, config.production].some(envHost => envHost.toLowerCase() === hostname));
        return matched?.[0];
    }
    resolveMarketFromPostnordSubdomain(hostname) {
        if (hostname.includes('www')) {
            return undefined;
        }
        if (!hostname.includes('.postnord.')) {
            return undefined;
        }
        const postnordIndex = hostname.indexOf('.postnord.');
        const beforePostnord = hostname.substring(0, postnordIndex);
        const parts = beforePostnord.split('.').filter(Boolean);
        if (parts.length === 0) {
            return undefined;
        }
        const closestSubdomain = parts[parts.length - 1];
        return this.isMarketName(closestSubdomain) ? closestSubdomain : undefined;
    }
    resolveMarketFromDevelopmentUrl(url) {
        const target = `${url.hostname}${url.pathname}`.toLowerCase();
        const matchedMarket = ALLOWED_MARKETS.find(market => {
            const patterns = [
                `/${market}/`,
                `/${market}`,
                `.${market}.`,
                `.${market}/`,
                `${market}.`,
            ];
            return patterns.some(pattern => target.includes(pattern));
        });
        if (matchedMarket) {
            return matchedMarket;
        }
        const matchedByFallbackLanguage = Object.entries(MARKETS).find(([, config]) => {
            const language = config.fallbackLanguage.toLowerCase();
            const patterns = [
                `/${language}/`,
                `/${language}`,
                `.${language}.`,
                `.${language}/`,
                `${language}.`,
            ];
            return patterns.some(pattern => target.includes(pattern));
        });
        return matchedByFallbackLanguage?.[0];
    }
    isMarketName(value) {
        return ALLOWED_MARKETS.includes(value);
    }
}

/**
 * Removes duplicated language segments from generated URLs.
 *
 * Example:
 * /sv/sv/page -> /sv/page
 *
 * This protects against incorrectly concatenated site-domain-based URLs.
 */
function removeDoubleLanguage(url, language) {
    if (!language) {
        return url;
    }
    const languageSegment = language.toLowerCase() + '/';
    const doubleLanguageSegment = '/' + languageSegment + languageSegment;
    if (url.includes(doubleLanguageSegment)) {
        return url.replace(doubleLanguageSegment, '/' + languageSegment);
    }
    return url;
}
/**
 * Resolves a menu/login href to an absolute site-relative URL when needed.
 *
 * What it does:
 * - Leaves fully-qualified http/https URLs unchanged
 * - Prefixes relative URLs with the current site definition domain
 * - Cleans up accidental double language segments
 */
function adjustHref(href, siteDefinition, language) {
    if (!href) {
        return href;
    }
    if (href.indexOf('http') === 0) {
        return href;
    }
    const siteUrl = siteDefinition?.url ?? '';
    const domainUrl = siteUrl.lastIndexOf('/') === siteUrl.length - 1
        ? siteUrl.substring(0, siteUrl.length - 1)
        : siteUrl;
    return removeDoubleLanguage(domainUrl + href, language);
}
/**
 * Recursively adjusts a menu item and all child menu items so that
 * relative URLs become site-domain-aware absolute URLs.
 *
 * This returns a new object rather than mutating the original API item.
 */
function adjustMenuItemUrls(item, siteDefinition, language) {
    return {
        ...item,
        href: adjustHref(item.href, siteDefinition, language),
        children: (item.children ?? []).map(child => adjustMenuItemUrls(child, siteDefinition, language)),
    };
}
/**
 * Adjusts login dialog links so that relative URLs are resolved against
 * the active site domain.
 *
 * This is used when siteDomainInUrls is enabled.
 */
function adjustLoginDialogUrls(loginDialog, siteDefinition, language) {
    if (!loginDialog) {
        return null;
    }
    return {
        ...loginDialog,
        loggedInLinks: (loginDialog.loggedInLinks ?? []).map(item => ({
            ...item,
            href: adjustHref(item.href, siteDefinition, language),
        })),
        loginMenuLinks: (loginDialog.loginMenuLinks ?? []).map(item => ({
            ...item,
            href: adjustHref(item.href, siteDefinition, language),
        })),
    };
}
/**
 * Navigates to the provided href when available.
 */
function navigateToHref(href) {
    if (!href) {
        return;
    }
    window.location.href = href;
}
/**
 * Navigates to a menu item's href when available.
 */
function navigateToMenuItem(item) {
    navigateToHref(item?.href);
}

/**
 * Maps backend header data into the internal renderable view model.
 *
 * This mapper is the normalization boundary between the backend header payload
 * and the UI-facing header view model.
 *
 * Top-level menu interpretation:
 * - all items except the last = switchable root menus
 * - last item = shared/common root
 *
 * These semantics are inferred by position, not by stable backend identifiers.
 *
 * Responsibilities
 * ----------------
 * - normalize top-level backend payload sections
 * - optionally adjust relative URLs against the site domain
 * - detect whether the backend menu supports menu switching
 * - preserve the raw normalized menu structure for the wrapper component
 * - prepare a flat `menuItems` list for simpler rendering paths
 *
 * Important
 * ---------
 * - The switchable root items themselves are not intended to be rendered as
 *   visible main navigation entries
 * - Visible navigation is derived from:
 *   - active root children
 *   - plus shared/common root children
 * - If only a shared/common root exists, its children are rendered flat
 * - The wrapper component may choose either:
 *   - `menuItems` for flat rendering
 *   - or `rawMenuItems` + menu helpers for grouped rendering
 */
function mapHeaderDataToViewModel(data, options) {
    if (!data || typeof data !== 'object') {
        return {
            siteDefinition: null,
            menuItems: [],
            search: null,
            siteSelector: null,
            languageSelector: null,
            languageOptions: [],
            loginDialog: null,
            homePageLink: '/',
            hasMenuSwitching: false,
            menuModeOptions: [],
            defaultMenuMode: 0,
            rawMenuItems: [],
        };
    }
    const siteDefinition = data.sitedefinition ?? null;
    /**
     * Keep a normalized copy of the backend menu structure.
     *
     * This raw structure is preserved because the wrapper component may need the
     * original top-level roots in order to:
     * - switch active menu mode
     * - render grouped navigation
     * - resolve mode navigation targets
     *
     * Top-level semantics are positional:
     * - all items except the last = switchable root menus
     * - last item = shared/common root
     */
    const rawMenuItems = (data.mainMenu?.menuItems ?? []).map(item => options.siteDomainInUrls
        ? adjustMenuItemUrls(item, siteDefinition, options.language)
        : { ...item });
    const toggleStructure = extractToggleableMenuStructure(rawMenuItems);
    /**
     * `menuItems` is kept as a flat convenience list for render paths that do
     * not need to reason about root menus explicitly.
     *
     * This flat list contains:
     * - active-mode primary items when switchable roots exist
     * - plus shared/common items
     *
     * If only a shared/common root exists, its children are rendered flat.
     */
    let menuItems = buildMenuItemsForMode(toggleStructure, 0);
    menuItems = prependHomeMenuItem(menuItems, options.i18n, siteDefinition?.url ?? '/', options.hideHomeMenuItem);
    const search = {
        ...(data.search ?? {}),
        AutocompleteEndpoint: options.autocompleteEndpoint ?? '',
    };
    const siteSelector = data.siteSelectorViewModel ?? null;
    const languageSelector = data.languageSelectorViewModel ?? null;
    const languageOptions = getLanguageOptions(languageSelector);
    const loginDialog = options.siteDomainInUrls
        ? adjustLoginDialogUrls(data.loginViewModel ?? null, siteDefinition, options.language)
        : data.loginViewModel ?? null;
    return {
        siteDefinition,
        menuItems,
        search,
        siteSelector,
        languageSelector,
        languageOptions,
        loginDialog,
        homePageLink: siteDefinition?.url ?? document.location.hostname,
        hasMenuSwitching: toggleStructure.hasMenuSwitching,
        menuModeOptions: toggleStructure.menuModeOptions,
        defaultMenuMode: 0,
        rawMenuItems,
    };
}

/**
 * Safe fallback i18n object used before translations have been resolved,
 * or if a language is missing from the translation table.
 */
const defaultHeaderI18n = {
    searchlabel: '',
    searchplaceholder: '',
    searchbuttontext: '',
    menuHomeButton: '',
    menuGoBackButton: '',
    mainMenuButton: '',
    menuStartButton: '',
    profileSelectionFlyoutHeading: '',
    unifiedLoginButton: '',
    unifiedMyPagesButton: '',
    home: 'Home',
};
/**
 * Resolves the i18n object for the current language and applies overrides.
 *
 * What it does:
 * - Looks up translation values for the selected language
 * - Falls back to a safe default object if the language is missing
 * - Allows the search placeholder to be overridden by a prop
 * - Ensures "home" always has a non-empty fallback value
 */
function resolveHeaderTranslations(language, searchPlaceholder) {
    const resolved = (language && translations[language]) ? translations[language] : defaultHeaderI18n;
    return {
        ...defaultHeaderI18n,
        ...resolved,
        searchplaceholder: searchPlaceholder || resolved.searchplaceholder || '',
        home: resolved.home && resolved.home.trim() !== '' ? resolved.home : 'Home',
    };
}

/**
 * Service responsible for:
 * - resolving the effective header context
 * - building the fetch URL for the header endpoint
 * - loading header data from the backend
 * - mapping backend data into a renderable header state
 *
 * This service uses the refined context service as the source of truth
 * for market/language/environment resolution.
 */
class PnMarketwebHeaderService {
    fetchHelper;
    href;
    doc;
    /**
     * Fixed backend path for loading header data.
     * This is appended to the resolved endpoint domain.
     */
    endpointPath = '/api/navigation/toggle-header';
    constructor(fetchHelper, href = window.location.href, doc = document) {
        this.fetchHelper = fetchHelper;
        this.href = href;
        this.doc = doc;
    }
    /**
     * Resolves the effective header context.
     *
     * What it does:
     * - uses the RefinedMarketWebContextService to resolve context from the current URL/document
     * - lets explicit input values override resolved values when provided
     * - resolves endpoint from environment + market when endpoint is not explicitly passed in
     * - keeps pageId as part of the final header request context
     */
    async resolveContext(input) {
        const contextService = new RefinedMarketWebContextService({
            href: this.href,
            doc: this.doc,
        });
        const resolvedContext = contextService.resolve();
        const market = input.market ?? resolvedContext.market;
        const language = input.language ?? resolvedContext.language;
        const environment = input.environment ?? resolvedContext.environment;
        const endpoint = input.endpoint && input.endpoint.trim() !== ''
            ? input.endpoint
            : contextService.getEndpoint(environment, market);
        return {
            market,
            language,
            environment,
            endpoint,
            pageId: input.pageId ?? '',
        };
    }
    /**
     * Builds the final request URL used to fetch header JSON.
     *
     * What it does:
     * - removes a trailing slash from the endpoint base if needed
     * - appends the fixed header endpoint path
     * - adds query parameters for market, language and current page
     */
    buildFetchUrl(context) {
        const endpointBase = context.endpoint.lastIndexOf('/') === context.endpoint.length - 1
            ? context.endpoint.substring(0, context.endpoint.length - 1)
            : context.endpoint;
        return `${endpointBase}${this.endpointPath}?market=${context.market}&language=${context.language}&currentPage=${context.pageId ?? ''}`;
    }
    /**
     * Fetches header data from the backend.
     *
     * Returns null when required context is missing.
     */
    async fetchHeaderData(context, cache = false) {
        if (!context.market || !context.language || context.endpoint == null) {
            return null;
        }
        const fetchUrl = this.buildFetchUrl(context);
        const response = await this.fetchHelper.fetchJson(fetchUrl, { mode: 'cors' }, cache);
        if (!response) {
            return null;
        }
        return 'value' in response ? response.value : response;
    }
    /**
     * Builds i18n for the current language + presentation overrides.
     */
    resolveI18n(language, searchPlaceholder = '') {
        if (!language) {
            return defaultHeaderI18n;
        }
        return resolveHeaderTranslations(language, searchPlaceholder);
    }
    /**
     * Maps raw header data into the current UI view model.
     */
    mapViewModel(rawHeaderData, input) {
        return mapHeaderDataToViewModel(rawHeaderData, {
            language: input.language ?? undefined,
            hideHomeMenuItem: input.hideHomeMenuItem,
            siteDomainInUrls: input.siteDomainInUrls,
            autocompleteEndpoint: input.autocompleteEndpoint,
            i18n: input.i18n,
        });
    }
    /**
     * Resolves context, fetches backend data and builds the final header state.
     */
    async loadHeaderState(input) {
        const context = await this.resolveContext({
            market: input.market,
            language: input.language,
            environment: input.environment,
            endpoint: input.endpoint,
            pageId: input.pageId,
        });
        const i18n = this.resolveI18n(context.language, input.searchPlaceholder);
        const rawHeaderData = await this.fetchHeaderData(context, input.cache ?? false);
        if (!rawHeaderData) {
            return {
                context,
                rawHeaderData: null,
                vm: null,
                i18n,
                status: 'error',
                activeMenuMode: 0, /* default to first mode */
            };
        }
        const vm = this.mapViewModel(rawHeaderData, {
            language: context.language,
            hideHomeMenuItem: input.hideHomeMenuItem,
            siteDomainInUrls: input.siteDomainInUrls,
            autocompleteEndpoint: input.autocompleteEndpoint,
            i18n,
        });
        return {
            context,
            rawHeaderData,
            vm,
            i18n,
            status: 'ready',
            activeMenuMode: vm.defaultMenuMode
        };
    }
    /**
     * Rebuilds the UI state from already-fetched raw backend data.
     * Use this when presentation-only inputs change and a refetch is not needed.
     */
    remapHeaderState(input) {
        const i18n = this.resolveI18n(input.language ?? input.context.language, input.searchPlaceholder);
        if (!input.rawHeaderData) {
            return {
                context: input.context,
                rawHeaderData: null,
                vm: null,
                i18n,
                status: 'error',
                activeMenuMode: input.currentActiveMenuMode,
            };
        }
        const vm = this.mapViewModel(input.rawHeaderData, {
            language: input.language ?? input.context.language,
            hideHomeMenuItem: input.hideHomeMenuItem,
            siteDomainInUrls: input.siteDomainInUrls,
            autocompleteEndpoint: input.autocompleteEndpoint,
            i18n,
        });
        return {
            context: input.context,
            rawHeaderData: input.rawHeaderData,
            vm,
            i18n,
            status: 'ready',
            activeMenuMode: input.currentActiveMenuMode,
        };
    }
}

const STORAGE_KEY = 'pn-marketweb-header:menu-mode';
/**
 * Returns the previously selected menu mode from localStorage.
 *
 * Returns null if:
 * - nothing is stored
 * - value is invalid
 * - storage is unavailable
 */
function getStoredHeaderMenuMode() {
    if (typeof window === 'undefined') {
        return null;
    }
    try {
        const value = window.localStorage.getItem(STORAGE_KEY);
        if (value == null) {
            return null;
        }
        const parsed = Number(value);
        if (Number.isInteger(parsed) && parsed >= 0) {
            return parsed;
        }
    }
    catch {
        // intentionally ignored
    }
    return null;
}
/**
 * Persists the selected menu mode in localStorage.
 *
 * Storage failures are intentionally ignored.
 */
function storeHeaderMenuMode(mode) {
    if (typeof window === 'undefined') {
        return;
    }
    try {
        window.localStorage.setItem(STORAGE_KEY, String(mode));
    }
    catch {
        // intentionally ignored
    }
}
/**
 * Resolves the effective initial menu mode.
 *
 * Priority:
 * 1. Stored user preference
 * 2. Server-provided initial mode
 * 3. Fallback to first mode (index 0)
 */
function resolveInitialHeaderMenuMode(hasMenuSwitching, initialActiveMenuMode) {
    if (!hasMenuSwitching) {
        return 0;
    }
    const storedMode = getStoredHeaderMenuMode();
    if (typeof storedMode === 'number') {
        return storedMode;
    }
    return initialActiveMenuMode ?? 0;
}

const pnMarketwebHeaderCss = "pn-button-dropdown .pn-button-dropdown>pn-button>.pn-button{min-height:initial}.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0, 0, 0, 0);white-space:nowrap;border-width:0}@media screen and (max-width: 767px){.sr-only-mobile{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0, 0, 0, 0);white-space:nowrap;border-width:0}}pn-marketweb-header{display:block;background-color:var(--siteheader-bg, #ffffff);color:var(--siteheader-text-color, #000000);--siteheader-bg:#ffffff;--siteheader-text-color:#000000;--siteheader-shadow:0 0.06rem 0.18rem rgba(0, 0, 0, 0.1), 0 0.32rem 0.72rem rgba(0, 0, 0, 0.13);--siteheader-row-border-color:#f3f2f2;--siteheader-row-padding-inline:1.6rem;--siteheader-row-min-height:2em;--siteheader-row-main-min-height:5.6rem;--siteheader-top-row-bg:transparent;--siteheader-top-row-border-color:#f3f2f2;--siteheader-top-text-color:#000000;--siteheader-top-link-color:#000000;--siteheader-top-icon-fill:currentColor;--siteheader-main-row-bg-mobile:#ffffff;--siteheader-main-row-bg-tablet:#ffffff;--siteheader-logo-color:#00a0d6;--siteheader-mainnav-top-position-mobile:3.5em;--siteheader-mainnav-link-hover-effect-color:#e0f8ff;--siteheader-button-font-weight:400;--siteheader-button-padding:0.5rem;--siteheader-button-radius:0.8rem;--siteheader-button-hover-bg:#e0f8ff;--siteheader-button-hover-text-color:#000000;--siteheader-toggle-color:#005d92;--siteheader-toggle-hover-color:#000000;--siteheader-toggle-active-color:#000000;--siteheader-toggle-active-underline-color:#00a0d6;--siteheader-mainnav-divider-color:#d3cecb;--siteheader-search-max-width:30rem;--siteheader-search-min-width:23.3rem;--siteheader-search-input-bg:#ffffff;--siteheader-search-input-color:#000000;--siteheader-search-placeholder-color:#000000;--siteheader-search-button-bg:#ffffff;--siteheader-search-icon-fill:currentColor}body[data-siteheader-menuopen=true]{max-height:100vh;overflow:hidden}@media screen and (min-width: 1024px){body[data-siteheader-menuopen=true]{max-height:initial;overflow:initial}}pn-marketweb-header header{position:relative;z-index:1000;display:flex;flex-direction:column;background-color:var(--siteheader-bg, #ffffff);color:var(--siteheader-text-color, #000000);box-shadow:var(--siteheader-shadow, 0 0.06rem 0.18rem rgba(0, 0, 0, 0.1), 0 0.32rem 0.72rem rgba(0, 0, 0, 0.13))}pn-marketweb-header .siteheader-row{display:flex;flex-flow:row;align-items:center;width:100%;min-height:var(--siteheader-row-min-height, 2em);padding-inline:var(--siteheader-row-padding-inline, 1.6rem)}pn-marketweb-header .siteheader-row:not(:last-child){border-bottom:0.1rem solid var(--siteheader-row-border-color, #f3f2f2)}pn-marketweb-header .siteheader-row-top{display:none}pn-marketweb-header .siteheader-row-main{display:flex;flex-direction:row;align-items:center;justify-content:space-between;max-width:100%;min-height:var(--siteheader-row-main-min-height, 5.6rem);padding-inline:var(--siteheader-row-padding-inline, 1.6rem);overflow:visible}pn-marketweb-header .siteheader-logocontainer{display:flex;align-items:center;z-index:1}pn-marketweb-header .siteheader-logolink{display:flex;align-items:center;height:100%;max-height:6.4rem}pn-marketweb-header .siteheader-logolink:hover,pn-marketweb-header .siteheader-logolink:focus,pn-marketweb-header .siteheader-logolink:active{box-shadow:none;text-decoration:none}pn-marketweb-header .siteheader-logo{display:block;color:var(--siteheader-logo-color)}pn-marketweb-header .siteheader-row>pn-marketweb-siteheader-search{display:none}pn-marketweb-header pn-spinner{display:none}pn-marketweb-header pn-button-dropdown:not(.hydrated) .pn-button-dropdown-container{display:none}pn-marketweb-header .siteheader-row pn-button button:hover{color:var(--siteheader-button-hover-text-color, #000000)}pn-marketweb-header .siteheader-row pn-button button:hover .pn-button-bg,pn-marketweb-header .siteheader-row pn-button button:hover .pn-button-bg::after{background-color:var(--siteheader-button-hover-bg, #e0f8ff)}pn-marketweb-header pn-button button{font-weight:var(--siteheader-button-font-weight, 400) !important;padding:var(--siteheader-button-padding, 0.5rem) !important}pn-marketweb-header pn-button button .pn-button-bg::after{border-radius:var(--siteheader-button-radius, 0.8rem) !important}@media screen and (min-width: 769px){pn-marketweb-header{--siteheader-row-min-height:3.2em;--siteheader-row-main-min-height:3.2em}pn-marketweb-header .siteheader-row{justify-content:space-between}pn-marketweb-header .siteheader-row-top{display:flex}pn-marketweb-header .siteheader-row>pn-marketweb-siteheader-search{display:block;width:100%;min-width:var(--siteheader-search-min-width, 23.3rem);max-width:var(--siteheader-search-max-width, 30rem)}}@media screen and (min-width: 1024px){pn-marketweb-header .siteheader-row-main{margin-top:auto;overflow:visible}}pn-marketweb-header[data-theme=business]{--siteheader-bg:#0d234b;--siteheader-text-color:#ffffff;--siteheader-row-border-color:#0d234b;--siteheader-top-row-bg:#0d234b;--siteheader-top-row-border-color:#0d234b;--siteheader-top-text-color:#ffffff;--siteheader-top-link-color:#ffffff;--siteheader-top-icon-fill:#ffffff;--siteheader-main-row-bg-mobile:#0d234b;--siteheader-main-row-bg-tablet:#ffffff;--siteheader-button-hover-bg:#ffffff;--siteheader-button-hover-text-color:#000000;--siteheader-logo-color:#00a0d6;--siteheader-cart-countindicator-color:#000000;--siteheader-cart-icon-color:#ffffff;--siteheader-cart-countindicator-background:#ffffff;--siteheader-cart-link-color:#ffffff;--siteheader-toggle-color:#ffffff;--siteheader-toggle-hover-color:#ffffff;--siteheader-toggle-active-color:#ffffff;--siteheader-toggle-active-underline-color:#ffffff;--siteheader-search-input-bg:#ffffff;--siteheader-search-input-color:#0d234b;--siteheader-search-placeholder-color:#0d234b;--siteheader-search-button-bg:#ffffff;--siteheader-search-icon-fill:#0d234b;--siteheader-mainnav-list-heading-color:#000000;--siteheader-mainnav-link-hover-effect-color:#0d234b;--siteheader-mainnav-link-active-effect-color:#0d234b;--siteheader-mainnav-level-2-border-top-left-radius-desktop:0;--siteheader-mainnav-level-2-border-top-right-radius-desktop:0;--siteheader-mainnav-link-active-desktop-color:#0d234b;--siteheader-mainnav-link-level1-indicator-color:#0d234b;--siteheader-mainnav-link-level1-indicator-active-color:#0d234b;--siteheader-mainnav-link-level1-border-bottom:0.1rem solid #e9e6e5;--siteheader-mainnav-link-level2-border-bottom:0.1rem solid #e9e6e5;--siteheader-login-profileselection-heading-color:#000000;--siteheader-login-profileselection-user-name-color:#000000;--siteheader-login-profileselection-description-color:#5e554a;--siteheader-login-profileselection-divider-background:#005d92;--siteheader-login-profileselection-profileoption-link-background:#ffffff;--siteheader-login-linklist-heading-color:#000000}";
const PnMarketwebHeaderStyle0 = pnMarketwebHeaderCss;

const PnMarketwebHeader = class {
    constructor(hostRef) {
        registerInstance(this, hostRef);
        this.changeLanguage = createEvent(this, "changeLanguage", 7);
        this.changeMarket = createEvent(this, "changeMarket", 7);
        this.initialActiveMenuMode = 0;
        this.menuThemes = undefined;
        this.market = null;
        this.language = null;
        this.environment = null;
        this.endpoint = null;
        this.siteid = null;
        this.pageId = '';
        this.userToken = '';
        this.userFullname = '';
        this.userLoggedin = false;
        this.hideSiteSelector = false;
        this.hideHomeMenuItem = false;
        this.hideLanguageSelector = false;
        this.hideSearch = false;
        this.hideLogin = false;
        this.showProfileSelection = false;
        this.showUnifiedLogin = false;
        this.siteDomainInUrls = false;
        this.autocompleteEndpoint = '';
        this.sessionForward = false;
        this.cache = false;
        this.searchPlaceholder = '';
        this.spaMode = false;
        this.checkUserLoggedInStateInterval = 0;
        this.useMarketwebLogin = false;
        this.navigateOnMenuToggle = true;
        this.vm = null;
        this.i18n = defaultHeaderI18n;
        this.status = 'loading';
        this.minimizeSearch = false;
        this.loggedIn = false;
        this.activeMenuMode = 0;
    }
    get hostElement() { return getElement(this); }
    /** Guard used to prevent watchers from reloading during initial setup. */
    isInitializing = false;
    /** Cached raw backend payload so UI-only prop changes can remap without refetching. */
    rawHeaderData = null;
    /** Main nav element reference used for overflow calculation. */
    mainNavEl;
    /** Emitted when the language changes. */
    changeLanguage;
    /** Emitted when the market changes. */
    changeMarket;
    /** Shared helper for backend requests. */
    fetchHelper = new FetchHelper('marketweb-header');
    /** Service for context resolution and header-data fetching. */
    headerService = new PnMarketwebHeaderService(this.fetchHelper);
    hasResolvedInitialMenuMode = false;
    async componentWillLoad() {
        await this.loadHeader();
    }
    onLanguageSelectorChange(e) {
        this.language = e.detail;
        window.dispatchEvent(new CustomEvent('marketweb-languagechange', { detail: this.language }));
    }
    async onLanguageChange() {
        if (this.isInitializing || !this.language) {
            return;
        }
        this.changeLanguage.emit(this.language);
        await this.loadHeader();
    }
    async onMarketChange() {
        if (this.isInitializing || !this.market) {
            return;
        }
        this.changeMarket.emit(this.market);
        await this.loadHeader();
    }
    async onEnvironmentChange() {
        if (this.isInitializing || !this.environment) {
            return;
        }
        await this.loadHeader();
    }
    async onEndpointChange() {
        if (this.isInitializing) {
            return;
        }
        await this.loadHeader();
    }
    async onPageIdChange() {
        if (this.isInitializing) {
            return;
        }
        await this.loadHeader();
    }
    onPresentationInputChange() {
        if (this.isInitializing) {
            return;
        }
        this.remapViewModel();
    }
    onLoginStateChange(e) {
        if (typeof e.detail?.loggedIn === 'boolean') {
            this.loggedIn = e.detail.loggedIn;
        }
    }
    handleResize() {
        requestAnimationFrame(() => {
            this.checkMenuOverflow();
        });
    }
    get menuThemeList() {
        return resolveHeaderMenuThemes(this.menuThemes, this.vm?.menuModeOptions);
    }
    get logoUrl() {
        return this.vm?.menuModeOptions?.[this.activeMenuMode]?.href ?? '/';
    }
    async loadHeader() {
        this.status = 'loading';
        this.isInitializing = true;
        try {
            const result = await this.headerService.loadHeaderState({
                market: this.market,
                language: this.language,
                environment: this.environment,
                endpoint: this.endpoint,
                pageId: this.pageId,
                cache: this.cache,
                hideHomeMenuItem: this.hideHomeMenuItem,
                siteDomainInUrls: this.siteDomainInUrls,
                autocompleteEndpoint: this.autocompleteEndpoint,
                searchPlaceholder: this.searchPlaceholder,
            });
            this.applyHeaderState(result);
            requestAnimationFrame(() => {
                this.checkMenuOverflow();
            });
        }
        catch (error) {
            console.error('[pn-marketweb-header] Failed to load header', error);
            this.rawHeaderData = null;
            this.vm = null;
            this.status = 'error';
        }
        finally {
            this.isInitializing = false;
        }
    }
    remapViewModel() {
        const context = {
            market: this.market,
            language: this.language,
            environment: this.environment,
            endpoint: this.endpoint,
            pageId: this.pageId ?? '',
        };
        const result = this.headerService.remapHeaderState({
            context,
            rawHeaderData: this.rawHeaderData,
            language: this.language,
            hideHomeMenuItem: this.hideHomeMenuItem,
            siteDomainInUrls: this.siteDomainInUrls,
            autocompleteEndpoint: this.autocompleteEndpoint,
            searchPlaceholder: this.searchPlaceholder,
            currentActiveMenuMode: this.activeMenuMode,
        });
        this.applyHeaderState(result);
        requestAnimationFrame(() => {
            this.checkMenuOverflow();
        });
    }
    applyHeaderState(result) {
        this.market = result.context.market;
        this.language = result.context.language;
        this.environment = result.context.environment;
        this.endpoint = result.context.endpoint;
        this.rawHeaderData = result.rawHeaderData;
        this.vm = result.vm;
        this.i18n = result.i18n;
        this.status = result.status;
        if (!result.vm?.hasMenuSwitching) {
            this.activeMenuMode = 0;
            this.hasResolvedInitialMenuMode = false;
        }
        else if (!this.hasResolvedInitialMenuMode) {
            this.activeMenuMode = resolveInitialHeaderMenuMode(true, this.initialActiveMenuMode);
            this.hasResolvedInitialMenuMode = true;
        }
        if (state.loginManager && result.vm?.siteDefinition?.url) {
            state.loginManager.setSiteUrl(result.vm.siteDefinition.url);
        }
    }
    checkMenuOverflow() {
        const mainNavEl = this.mainNavEl;
        if (!mainNavEl) {
            return;
        }
        const firstMenuLevel = mainNavEl.querySelector('pn-mainnav-level');
        if (!firstMenuLevel) {
            return;
        }
        const navContainer = firstMenuLevel.parentElement;
        if (!navContainer) {
            return;
        }
        const availableWidth = navContainer.clientWidth;
        const requiredWidth = firstMenuLevel.scrollWidth;
        this.minimizeSearch = requiredWidth > availableWidth;
    }
    isUserLoggedIn() {
        return this.loggedIn || this.userLoggedin;
    }
    adjustSiteSelectorUrl(href) {
        if (!this.isUserLoggedIn()) {
            return href;
        }
        const loginDomains = ['portal.postnord.com'];
        const matchedHref = loginDomains.some(domain => href.includes(domain));
        if (!matchedHref) {
            return href;
        }
        if (state.loginManager) {
            return state.loginManager.getLoginUrl(href);
        }
        return href;
    }
    onMenuToggleChange = (e) => {
        const nextMode = e.detail;
        if (nextMode === this.activeMenuMode) {
            return;
        }
        this.activeMenuMode = nextMode;
        storeHeaderMenuMode(nextMode);
        if (!this.navigateOnMenuToggle || !this.vm?.rawMenuItems.length) {
            return;
        }
        const targetRoot = getToggleRootForMenuItems(this.vm.rawMenuItems, nextMode);
        navigateToMenuItem(targetRoot);
    };
    getVisibleMenuGroups(vm) {
        if (!vm.rawMenuItems.length) {
            return {
                primaryItems: vm.menuItems,
                sharedItems: [],
            };
        }
        const structure = extractToggleableMenuStructure(vm.rawMenuItems);
        if (structure.modeRoots.length === 0) {
            return {
                primaryItems: vm.menuItems,
                sharedItems: [],
            };
        }
        const groups = getVisibleMenuGroupsForMode(vm.rawMenuItems, this.activeMenuMode);
        return {
            primaryItems: prependHomeMenuItem(groups.primaryItems, this.i18n, vm.siteDefinition?.url ?? '/', this.hideHomeMenuItem),
            sharedItems: groups.sharedItems,
        };
    }
    render() {
        const vm = this.vm;
        const i18n = this.i18n;
        const activeTheme = this.menuThemeList[this.activeMenuMode] ?? 'private';
        const logoUrl = this.logoUrl;
        const menuGroups = vm
            ? this.getVisibleMenuGroups(vm)
            : { primaryItems: [], sharedItems: [] };
        return (h(Host, { key: '77b50a06702c9c8aee59392c7ebcf392d0e93ace', language: this.language ?? undefined, market: this.market ?? undefined, environment: this.environment ?? undefined, "data-status": this.status, "data-mode": this.activeMenuMode, "data-theme": activeTheme }, h("header", { key: 'f17a9126e62264bcbc596802394d8a0eb64809d7' }, vm && (h(Fragment, { key: 'e4d0c6cbb175bd545c37011e8a26040e293b5078' }, h("pn-marketweb-header-top-row", { key: 'f20e51e813cd52f09a223d860e04759f9d277183', vm: vm, i18n: i18n, language: this.language ?? undefined, siteid: this.siteid ?? undefined, endpoint: this.endpoint ?? undefined, environment: this.environment ?? undefined, userToken: this.userToken, userFullname: this.userFullname, userLoggedin: this.userLoggedin, hideSiteSelector: this.hideSiteSelector, hideLanguageSelector: this.hideLanguageSelector, hideSearch: this.hideSearch, hideLogin: this.hideLogin, showProfileSelection: this.showProfileSelection, showUnifiedLogin: this.showUnifiedLogin, spaMode: this.spaMode, checkUserLoggedInStateInterval: this.checkUserLoggedInStateInterval, useMarketwebLogin: this.useMarketwebLogin, activeMenuMode: this.activeMenuMode, theme: activeTheme, navigateOnMenuToggle: this.navigateOnMenuToggle, menuToggleChangeHandler: this.onMenuToggleChange, adjustSiteSelectorUrl: (href) => this.adjustSiteSelectorUrl(href), logoUrl: logoUrl }, h("slot", { key: 'c0025425b08f233bc8ef6c9db59c516b1c2c8d05', name: "header-top-left", slot: "header-top-left" }), h("slot", { key: '822354a2c86ca56f4a7e6926492a5202e82d0d2e', name: "header-top-right-start", slot: "header-top-right-start" }), h("slot", { key: '68364a475418c6bb6baba867f9b78bc2f7cd3c92', name: "toprightend", slot: "toprightend" })), h("slot", { key: 'e49bc7c21f51abb86b05e6a986163f6b8848c425', name: "siteheader-menu-top-button" }), h("pn-marketweb-header-main-row", { key: 'a56827628a3f649546881449479df0d7721da5b2', vm: vm, i18n: i18n, market: this.market ?? undefined, language: this.language ?? undefined, siteid: this.siteid ?? undefined, hideSearch: this.hideSearch, hideLogin: this.hideLogin, hideLanguageSelector: this.hideLanguageSelector, hideSiteSelector: this.hideSiteSelector, minimizeSearch: this.minimizeSearch, activeMenuMode: this.activeMenuMode, theme: activeTheme, navigateOnMenuToggle: this.navigateOnMenuToggle, primaryItems: menuGroups.primaryItems, sharedItems: menuGroups.sharedItems, showMenuDivider: menuGroups.primaryItems.length > 0 && menuGroups.sharedItems.length > 0, userToken: this.userToken, userFullname: this.userFullname, userLoggedin: this.userLoggedin, endpoint: this.endpoint ?? undefined, environment: this.environment ?? undefined, showProfileSelection: this.showProfileSelection, showUnifiedLogin: this.showUnifiedLogin, checkUserLoggedInStateInterval: this.checkUserLoggedInStateInterval, useMarketwebLogin: this.useMarketwebLogin, spaMode: this.spaMode, menuToggleChangeHandler: this.onMenuToggleChange, mainNavRefHandler: (el) => {
                this.mainNavEl = el;
            }, adjustSiteSelectorUrl: (href) => this.adjustSiteSelectorUrl(href), logoUrl: logoUrl }, h("slot", { key: '673017970d5f273a2810acc09d47744cfdda19e6', name: "mobile-toprightend", slot: "mobile-toprightend" }), h("slot", { key: '86493520b39dd5c0fbe4a371e3503cfdcc51e8bf', name: "header-bottom-button", slot: "header-bottom-button" }), h("slot", { key: '1fa6a9440a1f2b4bcb081fbc5c7ce3bb31a6bb63', name: "menu-footer-cta", slot: "menu-footer-cta" })))))));
    }
    static get watchers() { return {
        "language": ["onLanguageChange"],
        "market": ["onMarketChange"],
        "environment": ["onEnvironmentChange"],
        "endpoint": ["onEndpointChange"],
        "pageId": ["onPageIdChange"],
        "hideHomeMenuItem": ["onPresentationInputChange"],
        "siteDomainInUrls": ["onPresentationInputChange"],
        "autocompleteEndpoint": ["onPresentationInputChange"],
        "searchPlaceholder": ["onPresentationInputChange"]
    }; }
};
PnMarketwebHeader.style = PnMarketwebHeaderStyle0;

export { PnMarketwebHeader as pn_marketweb_header };

//# sourceMappingURL=pn-marketweb-header.entry.js.map