import { shop } from "pn-design-assets/pn-assets/icons";
const ORIGINAL_FETCH = window.fetch.bind(window);
/**
 * Create promoted menuitems for testing purposes
 */
function createPromotedMenuItem(linkText, href, pageLink = href, openInNewWindow = false) {
    return {
        linkText,
        pageLink,
        href,
        openInNewWindow,
    };
}
/**
 * Reusable menu item factory to keep stories compact.
 */
function createMenuItem(name, href, id, children = [], level = 0, overrides = {}) {
    return {
        name,
        href,
        id,
        selected: false,
        open: false,
        children,
        navigationHeading: '',
        promotedMenuItemsHeader: '',
        promotedMenuItems: [],
        hasChildren: children.length > 0,
        linkTarget: '',
        trackingId: `${name.toLowerCase().replace(/\s+/g, '-')}${id}`,
        level,
        isMegaMenuParent: level === 0,
        ...overrides,
    };
}
function createLeaf(name, href, id, level = 1) {
    return createMenuItem(name, href, id, [], level, {
        isMegaMenuParent: false,
    });
}
/**
 * Creates a mocked backend envelope with the supplied top-level menu structure.
 *
 * Structure semantics used by the header:
 * - all items except the last = switchable root menus
 * - last item = shared/common root
 *
 * This mock is intentionally kept trimmed to match the current frontend
 * interfaces, while still preserving the real backend envelope shape.
 */
function createMockedResponse(menuItems) {
    return {
        value: {
            sitedefinition: {
                name: 'Postnord Sweden',
                url: 'https://localhost:51547/',
            },
            search: {
                formActionUrl: 'https://localhost:51547/sok/',
                AutocompleteEndpoint: 'https://localhost:51547/api/search/autocomplete',
            },
            languageSelectorViewModel: {
                currentLanguageNativeName: 'Svenska',
                languages: [
                    {
                        twoLetterISOLanguageName: 'en',
                        nativeName: 'English',
                        isCurrent: false,
                    },
                    {
                        twoLetterISOLanguageName: 'sv',
                        nativeName: 'Svenska',
                        isCurrent: true,
                    },
                    {
                        twoLetterISOLanguageName: 'da',
                        nativeName: 'Dansk',
                        isCurrent: false,
                    },
                ],
            },
            siteSelectorViewModel: {
                siteSelectorButtonText: 'postnord.se',
                siteSelectorTitle: 'PostNord',
                currentSiteTitle: 'postnord.se',
                currentSiteDescription: 'Tjänster och verktyg för att skicka och ta emot din post',
                siteSelections: [
                    {
                        linkText: 'Portal',
                        linkDescription: 'Hantera dina försändelser',
                        href: 'https://portal.postnord.com/',
                        pageLink: '/portal/',
                        openInNewWindow: false,
                    },
                    {
                        linkText: 'postnord.com',
                        linkDescription: 'Information om PostNord Koncernen',
                        href: 'https://com-inte.postnord.com/sv/',
                        pageLink: 'https://com-inte.postnord.com/sv/',
                        openInNewWindow: true,
                    },
                ],
            },
            loginViewModel: {
                loginMenuLinks: [
                    {
                        linkText: 'Logga in',
                        href: 'https://portal.postnord.com/login?language=sv',
                        pageLink: '/login/',
                        openInNewWindow: false,
                        primaryLinkApperance: true,
                        isLogoutLink: false,
                        linkType: 'unified',
                    },
                ],
                legacyLoginLinks: [
                    {
                        linkText: 'Logga in',
                        href: 'https://portal.postnord.com/login?language=sv',
                        pageLink: '/login/',
                        openInNewWindow: false,
                        primaryLinkApperance: true,
                        isLogoutLink: false,
                    },
                ],
                loggedInLinks: [
                    {
                        linkText: 'Logga ut',
                        href: 'http://window.location.href/?logout',
                        pageLink: '/logout',
                        openInNewWindow: false,
                        primaryLinkApperance: false,
                        isLogoutLink: true,
                    },
                ],
                overrideLoginMenu: false,
                loginMenuLinkText: 'Logga in',
                countryCode: 'SE',
                locale: 'sv',
                loginUrl: 'https://portal.postnord.com/login?language=sv',
                registerUrl: 'https://portal.postnord.com/createaccount?market=SE',
                loggedInButtonText: 'My PostNord',
                loginTitle: 'Logga in direkt på:',
                loginLinkText: 'Logga in',
                createLoginLinkText: 'Skapa nytt konto',
                loginInfo: '<p>Testing the login <a href="/link/0e1d8517b7344986b68152a9a0544460.aspx">recommendation</a></p>',
            },
            mainMenu: {
                menuItems,
            },
        },
        formatters: [],
        contentTypes: [],
        declaredType: null,
        statusCode: 200,
    };
}
/**
 * Default structure:
 * - 2 switchable roots
 * - 1 shared/common root
 */
const DEFAULT_MOCKED_RESPONSE = createMockedResponse([
    createMenuItem('Private', '/private/', 'root-private', [
        createLeaf('Skicka', '/private/skicka/', 'private-send', 1),
        createLeaf('Ta emot', '/private/ta-emot/', 'private-receive', 1),
    ]),
    createMenuItem('Business', '/business/', 'root-business', [
        createLeaf('Boka frakt', '/business/boka-frakt/', 'business-book', 1),
        createLeaf('Spåra', '/business/spåra/', 'business-track', 1),
    ]),
    createMenuItem('Shared', '/', 'root-shared', [
        createLeaf('Kundservice', '/kundservice/', 'shared-support', 1),
        createLeaf('Handla online', '/handla-online/', 'shared-shop', 1),
    ], 0, {
        isMegaMenuParent: false,
    }),
]);
/**
 * 3 switchable roots + shared.
 */
const THREE_MODES_MOCKED_RESPONSE = createMockedResponse([
    createMenuItem('Private', '/private/', 'root-private', [
        createLeaf('Skicka', '/private/skicka/', 'private-send', 1),
        createLeaf('Ta emot', '/private/ta-emot/', 'private-receive', 1),
    ]),
    createMenuItem('Business', '/business/', 'root-business', [
        createLeaf('Boka frakt', '/business/boka-frakt/', 'business-book', 1),
        createLeaf('Portal', '/business/portal/', 'business-portal', 1),
    ]),
    createMenuItem('Partners', '/partners/', 'root-partners', [
        createLeaf('Integrationer', '/partners/integrationer/', 'partners-integrations', 1),
        createLeaf('API-dokumentation', '/partners/api/', 'partners-api', 1),
    ]),
    createMenuItem('Shared', '/', 'root-shared', [
        createLeaf('Kundservice', '/kundservice/', 'shared-support', 1),
        createLeaf('Om oss', '/om-oss/', 'shared-about', 1),
    ], 0, {
        isMegaMenuParent: false,
    }),
]);
/**
 * One switchable root + shared.
 * Should not render a switcher because there is only one mode root.
 */
const ONE_MODE_MOCKED_RESPONSE = createMockedResponse([
    createMenuItem('Private', '/private/', 'root-private', [
        createLeaf('Skicka', '/private/skicka/', 'private-send', 1),
        createLeaf('Ta emot', '/private/ta-emot/', 'private-receive', 1),
    ]),
    createMenuItem('Shared', '/', 'root-shared', [
        createLeaf('Kundservice', '/kundservice/', 'shared-support', 1),
        createLeaf('Handla online', '/handla-online/', 'shared-shop', 1),
    ], 0, {
        isMegaMenuParent: false,
    }),
]);
/**
 * Shared-only structure.
 * No switching should be available.
 */
const SHARED_ONLY_MOCKED_RESPONSE = createMockedResponse([
    createMenuItem('Shared', '/', 'root-shared', [
        createLeaf('Kundservice', '/kundservice/', 'shared-support', 1),
        createLeaf('Handla online', '/handla-online/', 'shared-shop', 1),
        createLeaf('Om oss', '/om-oss/', 'shared-about', 1),
    ], 0, {
        isMegaMenuParent: false,
    }),
]);
/**
 * Switchable roots + shared, where visible menu items also contain sub-menu items.
 */
const NESTED_SUBMENU_MOCKED_RESPONSE = createMockedResponse([
    createMenuItem('Private', '/private/', 'root-private', [
        createMenuItem('Skicka', '/private/skicka/', 'private-send', [
            createLeaf('Inrikes', '/private/skicka/inrikes/', 'private-send-domestic', 2),
            createLeaf('Utrikes', '/private/skicka/utrikes/', 'private-send-international', 2),
        ], 1, {
            isMegaMenuParent: false,
            hasChildren: true,
            promotedMenuItemsHeader: 'Populärt',
            promotedMenuItems: [
                createPromotedMenuItem('Skicka paket och brev', 'https://se-inte.postnord.com/kop-frakt/', '/link/ed3ac8e1d91241e98ca0c9cce544018e.aspx'),
                createPromotedMenuItem('Sök brevlåda eller serviceställe', 'https://se-inte.postnord.com/vara-verktyg/sok-brevlada-eller-servicestalle/', '/link/1ecca245984d4ea99a4bd28390577d52.aspx'),
            ],
        }),
        createMenuItem('Ta emot', '/private/ta-emot/', 'private-receive', [
            createLeaf('Paket', '/private/ta-emot/paket/', 'private-receive-packages', 2),
            createLeaf('Brev', '/private/ta-emot/brev/', 'private-receive-letters', 2),
        ], 1, {
            isMegaMenuParent: false,
            hasChildren: true,
        }),
    ]),
    createMenuItem('Business', '/business/', 'root-business', [
        createMenuItem('Boka frakt', '/business/boka-frakt/', 'business-book', [
            createLeaf('Inrikes företag', '/business/boka-frakt/inrikes/', 'business-book-domestic', 2),
            createLeaf('Utrikes företag', '/business/boka-frakt/utrikes/', 'business-book-international', 2),
        ], 1, {
            isMegaMenuParent: false,
            hasChildren: true,
        }),
        createMenuItem('Spåra', '/business/spåra/', 'business-track', [
            createLeaf('Spåra paket', '/business/spåra/paket/', 'business-track-packages', 2),
            createLeaf('Spåra pall', '/business/spåra/pall/', 'business-track-pallets', 2),
        ], 1, {
            isMegaMenuParent: false,
            hasChildren: true,
            promotedMenuItemsHeader: 'Populärt',
            promotedMenuItems: [
                createPromotedMenuItem('Skicka paket och brev', 'https://se-inte.postnord.com/kop-frakt/', '/link/ed3ac8e1d91241e98ca0c9cce544018e.aspx'),
                createPromotedMenuItem('Sök brevlåda eller serviceställe', 'https://se-inte.postnord.com/vara-verktyg/sok-brevlada-eller-servicestalle/', '/link/1ecca245984d4ea99a4bd28390577d52.aspx'),
            ],
        }),
    ]),
    createMenuItem('Shared', '/', 'root-shared', [
        createMenuItem('Kundservice', '/kundservice/', 'shared-support', [
            createLeaf('Vanliga frågor', '/kundservice/fragor/', 'shared-support-faq', 2),
            createLeaf('Kontakta oss', '/kundservice/kontakta-oss/', 'shared-support-contact', 2),
        ], 1, {
            isMegaMenuParent: false,
            hasChildren: true,
        }),
        createMenuItem('Handla online', '/handla-online/', 'shared-shop', [
            createLeaf('Frimärken', '/handla-online/frimarken/', 'shared-shop-stamps', 2),
            createLeaf('Emballage', '/handla-online/emballage/', 'shared-shop-packaging', 2),
        ], 1, {
            isMegaMenuParent: false,
            hasChildren: true,
        }),
    ], 0, {
        isMegaMenuParent: false,
    }),
]);
const meta = {
    title: 'Marketweb/Header/pn-marketweb-header',
    parameters: {
        layout: 'fullscreen',
    },
    argTypes: {
        market: { control: 'text' },
        language: { control: 'text' },
        initialActiveMenuMode: { control: 'number' },
        environment: {
            control: 'select',
            options: ['production', 'preproduction', 'integration', 'localhost'],
        },
        endpoint: { control: 'text' },
        pageId: { control: 'text' },
        siteid: { control: 'text' },
        userToken: { control: 'text' },
        userFullname: { control: 'text' },
        userLoggedin: { control: 'boolean' },
        hideSiteSelector: { control: 'boolean' },
        hideHomeMenuItem: { control: 'boolean' },
        hideLanguageSelector: { control: 'boolean' },
        hideSearch: { control: 'boolean' },
        hideLogin: { control: 'boolean' },
        showProfileSelection: { control: 'boolean' },
        showUnifiedLogin: { control: 'boolean' },
        siteDomainInUrls: { control: 'boolean' },
        autocompleteEndpoint: { control: 'text' },
        sessionForward: { control: 'boolean' },
        cache: { control: 'boolean' },
        searchPlaceholder: { control: 'text' },
        spaMode: { control: 'boolean' },
        checkUserLoggedInStateInterval: { control: 'number' },
        useMarketwebLogin: { control: 'boolean' },
        navigateOnMenuToggle: { control: 'boolean' },
        useMockedResponse: { control: 'boolean' },
        mockedResponse: {
            control: 'object',
            description: 'Mocked backend response envelope.',
        },
    },
};
export default meta;
/**
 * Creates a deep clone of JSON-like mocked data.
 * This avoids accidental mutation across renders.
 */
function cloneJson(value) {
    return JSON.parse(JSON.stringify(value));
}
/**
 * Creates a deep clone of the mocked backend response envelope.
 *
 * The mocked response should match the real backend response shape.
 */
function extractPayload(mockedResponse) {
    return cloneJson(mockedResponse);
}
/**
 * Creates a fetch Response containing mocked JSON.
 */
function createJsonResponse(body) {
    return new Response(JSON.stringify(body), {
        status: 200,
        headers: {
            'Content-Type': 'application/json',
        },
    });
}
function restoreOriginalFetch() {
    window.fetch = ORIGINAL_FETCH;
}
/**
 * Installs a fetch mock that intercepts header requests and returns the mocked
 * backend envelope.
 *
 * The component still performs a normal fetch from its point of view.
 */
function installHeaderFetchMock(mockedResponse, endpoint) {
    window.fetch = async (input, init) => {
        const requestUrl = typeof input === 'string'
            ? input
            : input instanceof URL
                ? input.toString()
                : input.url;
        const normalizedEndpoint = endpoint.replace(/\/$/, '');
        const isHeaderRequest = requestUrl.includes(`${normalizedEndpoint}/api/navigation/toggle-header`) ||
            requestUrl.includes('/api/navigation/toggle-header');
        if (isHeaderRequest) {
            const payload = extractPayload(mockedResponse);
            return createJsonResponse(payload);
        }
        return ORIGINAL_FETCH(input, init);
    };
}
function createTopRightEndButton() {
    const button = document.createElement('a');
    button.setAttribute('slot', 'toprightend');
    button.setAttribute('style', 'align-self:center;justfit-content:center;position:relative;text-decoration:none;color:#005d92;');
    button.innerHTML = `<span>Varukorg</span><pn-icon icon='${shop}' color="blue700" class="pn-icon"></pn-icon>`;
    button.style.cursor = 'pointer';
    button.style.fontSize = '16px';
    return button;
}
function createMenuFooterCta() {
    const link = document.createElement('a');
    link.setAttribute('slot', 'menu-footer-cta');
    link.setAttribute('href', '#');
    link.textContent = 'Footer CTA';
    link.style.display = 'inline-block';
    link.style.padding = '8px 12px';
    link.style.borderRadius = '6px';
    link.style.border = '1px solid #ccc';
    link.style.textDecoration = 'none';
    link.style.color = 'inherit';
    return link;
}
/**
 * Creates the actual header element and assigns props directly.
 *
 * This is important for boolean props like navigateOnMenuToggle.
 */
function createHeaderElement(args) {
    const header = document.createElement('pn-marketweb-header');
    header.market = args.market;
    header.initialActiveMenuMode = args.initialActiveMenuMode;
    header.menuThemes = args.menuThemes;
    header.language = args.language;
    header.environment = args.environment;
    header.endpoint = args.endpoint;
    header.pageId = args.pageId;
    header.siteid = args.siteid;
    header.userToken = args.userToken;
    header.userFullname = args.userFullname;
    header.userLoggedin = args.userLoggedin;
    header.hideSiteSelector = args.hideSiteSelector;
    header.hideHomeMenuItem = args.hideHomeMenuItem;
    header.hideLanguageSelector = args.hideLanguageSelector;
    header.hideSearch = args.hideSearch;
    header.hideLogin = args.hideLogin;
    header.showProfileSelection = args.showProfileSelection;
    header.showUnifiedLogin = args.showUnifiedLogin;
    header.siteDomainInUrls = args.siteDomainInUrls;
    header.autocompleteEndpoint = args.autocompleteEndpoint;
    header.sessionForward = args.sessionForward;
    header.cache = args.cache;
    header.searchPlaceholder = args.searchPlaceholder;
    header.spaMode = args.spaMode;
    header.checkUserLoggedInStateInterval = args.checkUserLoggedInStateInterval;
    header.useMarketwebLogin = args.useMarketwebLogin;
    header.navigateOnMenuToggle = args.navigateOnMenuToggle;
    header.appendChild(createTopRightEndButton());
    header.appendChild(createMenuFooterCta());
    return header;
}
/**
 * Renders the Storybook shell and the header.
 *
 * This story intentionally does not include a fake menu switcher.
 * The real pn-marketweb-header should render its own switcher when the menu
 * structure supports multiple switchable root menus.
 */
function renderHeaderStory(args) {
    restoreOriginalFetch();
    if (args.useMockedResponse) {
        installHeaderFetchMock(args.mockedResponse, args.endpoint);
    }
    const root = document.createElement('div');
    root.style.minHeight = '100vh';
    root.style.background = '#f5f5f5';
    const header = createHeaderElement(args);
    root.appendChild(header);
    const main = document.createElement('main');
    main.style.padding = '32px';
    const title = document.createElement('h1');
    title.textContent = 'Storybook preview';
    title.style.marginTop = '0';
    const paragraph1 = document.createElement('p');
    paragraph1.textContent = args.useMockedResponse
        ? 'This story uses a mocked backend response.'
        : 'This story uses the real backend response from the configured endpoint.';
    const paragraph2 = document.createElement('p');
    paragraph2.innerHTML =
        'In Storybook, <code>navigateOnMenuToggle</code> is disabled by default so you can inspect menu switching without leaving the preview.';
    main.appendChild(title);
    main.appendChild(paragraph1);
    main.appendChild(paragraph2);
    root.appendChild(main);
    return root;
}
const DEFAULT_ARGS = {
    market: 'se',
    language: 'sv',
    environment: 'localhost',
    initialActiveMenuMode: 0,
    endpoint: 'https://storybook.local',
    pageId: '9',
    siteid: '',
    userToken: '',
    userFullname: '',
    userLoggedin: false,
    hideSiteSelector: false,
    hideHomeMenuItem: false,
    hideLanguageSelector: false,
    hideSearch: false,
    hideLogin: false,
    showProfileSelection: true,
    showUnifiedLogin: true,
    siteDomainInUrls: false,
    autocompleteEndpoint: '',
    sessionForward: false,
    cache: false,
    searchPlaceholder: 'Sök',
    spaMode: false,
    checkUserLoggedInStateInterval: 0,
    useMarketwebLogin: false,
    navigateOnMenuToggle: false,
    useMockedResponse: true,
};
/**
 * Baseline story:
 * - 2 switchable roots
 * - 1 shared root
 */
export const TwoModesWithShared = {
    render: args => renderHeaderStory(args),
    args: {
        ...DEFAULT_ARGS,
        mockedResponse: DEFAULT_MOCKED_RESPONSE,
    },
};
/**
 * Verifies that more than 2 switchable roots are supported.
 */
export const ThreeModesWithShared = {
    render: args => renderHeaderStory(args),
    args: {
        ...DEFAULT_ARGS,
        mockedResponse: THREE_MODES_MOCKED_RESPONSE,
    },
};
/**
 * Only one mode root + shared.
 * The header should not render the menu switcher.
 */
export const OneModeWithShared = {
    render: args => renderHeaderStory(args),
    args: {
        ...DEFAULT_ARGS,
        mockedResponse: ONE_MODE_MOCKED_RESPONSE,
    },
};
/**
 * Shared-only structure.
 * Useful for verifying fallback rendering when no switchable roots exist.
 */
export const SharedOnly = {
    render: args => renderHeaderStory(args),
    args: {
        ...DEFAULT_ARGS,
        mockedResponse: SHARED_ONLY_MOCKED_RESPONSE,
    },
};
/**
 * Same baseline structure, but start on the second mode.
 */
export const StartOnSecondMode = {
    render: args => renderHeaderStory(args),
    args: {
        ...DEFAULT_ARGS,
        initialActiveMenuMode: 1,
        mockedResponse: DEFAULT_MOCKED_RESPONSE,
    },
};
/**
 * Same baseline structure, but allow real navigation hrefs on mode change.
 * Mostly useful for checking rendered links rather than interacting in Storybook.
 */
export const NavigationEnabled = {
    render: args => renderHeaderStory(args),
    args: {
        ...DEFAULT_ARGS,
        navigateOnMenuToggle: true,
        mockedResponse: DEFAULT_MOCKED_RESPONSE,
    },
};
/**
 * Smaller layout story while still using mocked data.
 */
export const Minimal = {
    render: args => renderHeaderStory(args),
    args: {
        ...DEFAULT_ARGS,
        hideSiteSelector: true,
        hideLanguageSelector: true,
        hideLogin: true,
        showProfileSelection: false,
        showUnifiedLogin: false,
        mockedResponse: DEFAULT_MOCKED_RESPONSE,
    },
};
/**
 * Menu items contain nested sub-menu items.
 */
export const NestedSubmenuItems = {
    render: args => renderHeaderStory(args),
    args: {
        ...DEFAULT_ARGS,
        mockedResponse: NESTED_SUBMENU_MOCKED_RESPONSE,
    },
};
/**
 * Uses the real local CMS instead of Storybook fetch mocking.
 */
export const LocalCms = {
    render: args => renderHeaderStory(args),
    args: {
        ...DEFAULT_ARGS,
        useMockedResponse: false,
        endpoint: 'https://localhost:51547',
        environment: 'localhost',
        pageId: '9',
        siteid: '',
        mockedResponse: DEFAULT_MOCKED_RESPONSE,
    },
};
/**
 * Uses the real integration CMS instead of Storybook fetch mocking. //FIXME: getting cors-safe data at the moment
 */
export const IntegrationCms = {
    render: args => renderHeaderStory(args),
    args: {
        ...DEFAULT_ARGS,
        useMockedResponse: false,
        endpoint: 'https://se-inte.postnord.com',
        environment: 'integration',
        market: 'se',
        language: 'sv',
        pageId: '9',
        //  userToken: '6ae6bde345eb68fc0102f4ba256f31e9151db31dc2ea4c23a51917c'
    },
};
//# sourceMappingURL=pn-marketweb-header.stories.js.map
