import { RefinedMarketWebContextService, } from "../../../../services/pn-refined-marketweb-context/pn-refined-marketweb-context.service";
import { mapHeaderDataToViewModel } from "../mapper/pn-marketweb-header.mapper";
import { defaultHeaderI18n, resolveHeaderTranslations, } from "../utils/header-i18n";
/**
 * 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.
 */
export 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,
        };
    }
}
//# sourceMappingURL=pn-marketweb-header.service.js.map
