import { proxyCustomElement, HTMLElement, createEvent, h, Host } from '@stencil/core/internal/client';
import { M as MarketWebContextService } from './MarketWebContextService.js';
import { F as FetchHelper } from './FetchHelper.js';
import { d as debounce } from './index2.js';
import { a as alert_exclamation_circle } from './alert_exclamation_circle.js';

const translations = {
    'sv': {
        errorEmpty: 'Får inte vara tom',
        errorPostalCode: 'Kan inte hitta postkoden',
        required: 'obligatoriskt',
        addressNotFound: 'Adressen hittades inte'
    },
    'en': {
        errorEmpty: 'Cannot be empty',
        errorPostalCode: 'Could not find postalcode',
        required: 'required',
        addressNotFound: 'Address not found'
    },
    'da': {
        errorEmpty: 'Kan ikke være tom',
        errorPostalCode: 'Kunne ikke finde postnummeret',
        required: 'påkrævet',
        addressNotFound: 'Adressen blev ikke fundet'
    },
    'no': {
        errorEmpty: 'Cannot be empty',
        errorPostalCode: 'Could not find postalcode',
    },
    'fi': {
        errorEmpty: 'Cannot be empty',
        errorPostalCode: 'Could not find postalcode',
        required: 'pakollinen'
    },
    'de': {
        errorEmpty: 'Cannot be empty',
        errorPostalCode: 'Could not find postalcode',
    },
    'zh': {
        errorEmpty: 'Cannot be empty',
        errorPostalCode: 'Could not find postalcode',
    },
    'fr': {
        errorEmpty: 'Cannot be empty',
        errorPostalCode: 'Could not find postalcode',
    },
    'es': {
        errorEmpty: 'Cannot be empty',
        errorPostalCode: 'Could not find postalcode',
    },
    'nl': {
        errorEmpty: 'Cannot be empty',
        errorPostalCode: 'Could not find postalcode',
    },
    'it': {
        errorEmpty: 'Cannot be empty',
        errorPostalCode: 'Could not find postalcode',
    },
    'tr': {
        errorEmpty: 'Cannot be empty',
        errorPostalCode: 'Could not find postalcode',
    },
    'pl': {
        errorEmpty: 'Cannot be empty',
        errorPostalCode: 'Could not find postalcode',
    },
    'pt': {
        errorEmpty: 'Cannot be empty',
        errorPostalCode: 'Could not find postalcode',
    },
    'pt-BR': {
        errorEmpty: 'Cannot be empty',
        errorPostalCode: 'Could not find postalcode',
    },
};

const pnAddressAutofillCss = "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-address-autofill{display:flex;flex-direction:column;width:50rem}pn-address-autofill pn-input{width:50%}pn-address-autofill .input-container-row{display:flex;gap:1rem;margin-bottom:1rem}pn-address-autofill .label-container{color:#5e554a;font-size:0.875em;display:flex;justify-content:space-between;align-items:flex-end}pn-address-autofill .autocomplete-items{position:absolute;border-radius:0.8rem;border:0.1rem solid #5e554a;width:100%;max-height:30rem;overflow-y:auto}pn-address-autofill .autocomplete-items:hover,pn-address-autofill .autocomplete-items :focus{border:0.1rem solid #00a0d6}pn-address-autofill .autocomplete-items div{padding:1.6rem;cursor:pointer;background-color:#fff;border:0.1rem solid transparent}pn-address-autofill .autocomplete-items div:first-child{border-radius:0.8rem 0.8rem 0 0}pn-address-autofill .autocomplete-items div:last-child{border-radius:0 0 0.8rem 0.8rem}pn-address-autofill .autocomplete-items div:hover{background-color:#e0f8ff}pn-address-autofill .autocomplete-items .autocomplete-active{background-color:#e0f8ff}pn-address-autofill .autocomplete-items:empty{display:none}pn-address-autofill pn-input{max-width:25rem;width:100%}";
const PnAddressAutofillStyle0 = pnAddressAutofillCss;

const PnAddressAutofill$1 = /*@__PURE__*/ proxyCustomElement(class PnAddressAutofill extends HTMLElement {
    constructor() {
        super();
        this.__registerHost();
        this.addresscomplete = createEvent(this, "addresscomplete", 7);
        this.market = null;
        this.environment = null;
        this.endpoint = null;
        this.cache = true;
        this.countryCode = null;
        this.language = null;
        this.postalCodeProps = null;
        this.cityProps = null;
        this.streetAddressProps = null;
        this.streetNumberProps = null;
        this.addressNotFoundError = null;
        this.postalCode = null;
        this.city = null;
        this.streetAddress = null;
        this.streetNumber = null;
        this.validAddress = true;
        this.translation = undefined;
        this.postalCodeRequiredLabel = null;
        this.streetRequiredLabel = null;
        this.fullAddress = null;
        this.isLoading = true;
    }
    get hostElement() { return this; }
    pnInputPostalCode = null;
    pnInputCity = null;
    pnInputStreetAddress = null;
    pnInputStreetNumber = null;
    postalCodeInputField = null;
    streetAddressInputField = null;
    streetNumberInputField = null;
    pnInputHiddenValue = null;
    endpointPath = '/api/location/get-by-postalcode';
    _postalCodeProps = null;
    _cityProps = null;
    _streetAddressProps = null;
    _streetNumberProps = null;
    addresscomplete;
    fetchHelper = new FetchHelper('PostalCodeCityAutofill');
    componentWillLoad() {
        this.setInitialValues();
        this._postalCodeProps = this.setProps(this.postalCodeProps);
        this._cityProps = this.setProps(this.cityProps);
        this._streetAddressProps = this.setProps(this.streetAddressProps);
        this._streetNumberProps = this.setProps(this.streetNumberProps);
    }
    setProps(props) {
        if (typeof props === 'string') {
            return JSON.parse(props);
        }
        else {
            return props;
        }
    }
    componentDidLoad() {
        this.postalCodeInputField = this.pnInputPostalCode.querySelector('input');
        this.streetAddressInputField = this.pnInputStreetAddress.querySelector('input');
        this.streetNumberInputField = this.pnInputStreetNumber.querySelector('input');
        this.addEventHandlers();
    }
    async setInitialValues(href = window.location.href) {
        const marketWebContextService = new MarketWebContextService(href);
        if (!this.environment) {
            this.environment = await marketWebContextService.getEnvironmentName();
        }
        if (!this.endpoint && this.environment?.indexOf('local') === -1) {
            this.endpoint = await marketWebContextService.getEndpoint(this.environment, this.market);
        }
        if (!this.endpoint) {
            this.endpoint = '';
        }
        if (!this.language) {
            this.language = await marketWebContextService.getLanguage();
        }
        this.setTranslations();
        this.postalCodeRequiredLabel = "";
        this.streetRequiredLabel = "";
        if (this._postalCodeProps.postalCodeInputRequired === true) {
            this.postalCodeRequiredLabel = " (" + this.translation.required + ")";
        }
        if (this._streetAddressProps.streetAddressInputRequired === true) {
            this.streetRequiredLabel = " (" + this.translation.required + ")";
        }
    }
    setTranslations() {
        if (this.language === 'nb') {
            this.language = 'no';
        }
        if (this.language && translations[this.language]) {
            this.translation = translations[this.language];
        }
    }
    addEventHandlers() {
        let debounceTimeout;
        this.postalCodeInputField.addEventListener('input', (e) => {
            this.isLoading = true;
            clearTimeout(debounceTimeout);
            debounceTimeout = window.setTimeout(() => {
                this.fetchPostalCodeData(e);
            }, 300);
        });
        this.streetNumberInputField.addEventListener('input', debounce(this.fetchAddress.bind(this), 300));
        this.streetAddressInputField.addEventListener('keydown', () => { this.streetNumberInputField.value = ''; });
        this.addFormFieldEvent();
    }
    addFormFieldEvent() {
        const allInputs = this.hostElement.querySelectorAll('input');
        allInputs.forEach(element => {
            ['keyup', 'change', 'blur'].forEach(eventName => {
                const debounceUpdate = debounce(this.updateHiddenValue.bind(this), 1000);
                element.addEventListener(eventName, debounceUpdate);
            });
        });
    }
    updateHiddenValue(e) {
        if (e.target === this.streetNumberInputField) {
            this.streetNumber = this.streetNumberInputField.value;
        }
        if (this.validAddress && this.postalCode && this.city && this.streetAddress && this.streetNumber) {
            this.fullAddress = `${this.streetAddress} ${this.streetNumber}, ${this.city} ${this.postalCode}`;
        }
        else {
            this.fullAddress = '';
        }
        this.addresscomplete.emit(this.fullAddress);
    }
    async fetchPostalCodeData(e) {
        if (!e) {
            return;
        }
        const postalCode = this.postalCodeInputField.value;
        var postalCodeLength = 4;
        if (postalCode.length < postalCodeLength) {
            this.resetFields();
            return;
        }
        if (this.postalCode === postalCode) {
            return;
        }
        this.resetFields();
        this.postalCode = postalCode;
        var data = (await this.fetchPostalCode(postalCode));
        if (!data || !data.addresses) {
            this.city = null;
            this.isLoading = true;
            return;
        }
        const cityInfo = data.addresses?.find(addr => addr.postalCode === postalCode);
        this.city = cityInfo?.city || null;
        this.isLoading = false;
    }
    async fetchPostalCode(postalCode) {
        const endpointBase = this.endpoint.endsWith('/')
            ? this.endpoint.slice(0, -1)
            : this.endpoint;
        const fetchUrl = `${endpointBase}${this.endpointPath}?countryCode=${this.countryCode}&postalCode=${postalCode}`;
        try {
            const data = await this.fetchHelper.fetchJson(fetchUrl, { mode: 'cors' }, this.cache);
            if (!data?.addresses?.length) {
                this.pnInputPostalCode.setAttribute('error', this._postalCodeProps.postalCodeInputError);
                return;
            }
            return data;
        }
        catch (error) {
            console.error("Error fetching address data:", error);
            this.isLoading = true;
            return null;
        }
    }
    resetFields() {
        this.streetAddressInputField.value = '';
        this.streetNumberInputField.value = '';
        this.city = null;
        this.streetAddress = null;
        this.streetNumber = null;
        this.validAddress = false;
        let inputs = document.getElementsByTagName('pn-input');
        Array.from(inputs).forEach(element => {
            element.removeAttribute('error');
        });
    }
    async fetchAddress() {
        const streetAddress = this.streetAddressInputField.value.trim();
        const streetNumber = this.streetNumberInputField.value.trim();
        if (!streetAddress || !streetNumber) {
            this.validAddress = false;
            return;
        }
        const endpointBase = this.endpoint.endsWith('/')
            ? this.endpoint.slice(0, -1)
            : this.endpoint;
        const fetchUrl = `${endpointBase}${this.endpointPath}?countryCode=${this.countryCode}&postalCode=${this.postalCodeInputField.value}&address=${streetAddress + " " + streetNumber}`;
        try {
            const data = await this.fetchHelper.fetchJson(fetchUrl, { mode: 'cors' }, this.cache);
            if (!data?.addresses?.length) {
                this.validAddress = false;
            }
            else {
                const inputStreetAddress = this.normalizeChar(streetAddress);
                const inputStreetNumber = this.normalizeChar(streetNumber);
                const addressFound = data.addresses.some(addr => this.normalizeChar(addr.street) === inputStreetAddress &&
                    this.normalizeChar(addr.houseNumber) === inputStreetNumber &&
                    addr.postalCode === this.postalCodeInputField.value);
                this.validAddress = addressFound;
            }
        }
        catch (error) {
            console.error("Error fetching address data:", error);
            this.isLoading = true;
            this.validAddress = false;
        }
        if (this.streetAddress === streetAddress && this.streetNumber === streetNumber) {
            return;
        }
        if (streetAddress) {
            this.streetAddress = streetAddress;
        }
        if (streetNumber) {
            this.streetNumber = streetNumber;
        }
    }
    //this function is added to compare the street input values if entered without special characters like é, ø ect
    normalizeChar(str) {
        const specialCharMap = {
            'ø': 'o',
            'Ø': 'o',
            'æ': 'ae',
            'Æ': 'ae',
            // Add more as needed
        };
        var str1 = str.normalize("NFD").replace(/[\u0300-\u036f]/g, "")
            .split('').map(char => specialCharMap[char] || char)
            .join('').toLowerCase();
        return str1;
    }
    render() {
        return (h(Host, { key: '43ca8acceb3c02a3a12a6c4da9ae4e4b12853709', class: "pn-address-autofill" }, this._postalCodeProps?.postalCodeCityLabel ? (h("div", { class: "label-container" }, h("label", null, `${this._postalCodeProps.postalCodeCityLabel + ' ' + this.postalCodeRequiredLabel}`))) : null, h("div", { key: '4c61dd29dc1b53a71ab04f79a405bda5323764ab', class: "input-container-row" }, h("pn-input", { key: 'fd0baf1681bc21da522310f1233e693aa3f490cf', type: "number", name: this._postalCodeProps?.postalCodeInputName, required: this._postalCodeProps?.postalCodeInputRequired, placeholder: this._postalCodeProps?.postalCodeInputPlaceholder, ref: el => (this.pnInputPostalCode = el), autocomplete: "off", helpertext: this._postalCodeProps?.postalCodeInputHelpertext }), h("pn-input", { key: 'daa23faa30b9b48969b3f58e09ef6fe29a1f666d', type: "text", name: this._cityProps?.cityInputName, disabled: true, value: this.city, placeholder: this._cityProps?.cityInputPlaceholder, autocomplete: "off", helpertext: this._cityProps?.cityInputHelpertext })), this._streetAddressProps?.streetAddressNumberLabel ? (h("div", { class: "label-container" }, h("label", null, `${this._streetAddressProps.streetAddressNumberLabel + ' ' + this.streetRequiredLabel}`))) : null, h("div", { key: 'da8ef7b1eeca53ccbb926260acd2df79b395ee64', class: "input-container-row" }, h("pn-input", { key: 'cfd025d69b0901885da50d5dd7a763171ff96318', type: "text", name: this._streetAddressProps?.streetAddressInputName, required: this._streetAddressProps?.streetAddressInputRequired, value: this.streetAddress, placeholder: this._streetAddressProps?.streetAddressInputPlaceholder, ref: el => (this.pnInputStreetAddress = el), autocomplete: "off", helpertext: this._streetAddressProps?.streetAddressInputHelpertext, disabled: this.isLoading }), h("pn-input", { key: 'f9da42b0af3c7726686393ce1f161ac30d93a8b3', type: "text", name: this._streetNumberProps?.streetNumberInputName, required: this._streetNumberProps?.streetNumberInputRequired, value: this.streetNumber, placeholder: this._streetNumberProps?.streetNumberInputPlaceholder, ref: el => (this.pnInputStreetNumber = el), autocomplete: "off", helpertext: this._streetNumberProps?.streetNumberInputHelpertext, disabled: this.isLoading })), (!this.validAddress && this.streetAddressInputField.value && this.streetNumberInputField.value) ? (h("div", { class: "toast-container" }, h("pn-toast", { text: this.addressNotFoundError ?? this.translation.addressNotFound, appearance: "warning", icon: alert_exclamation_circle }))) : null));
    }
    static get style() { return PnAddressAutofillStyle0; }
}, [0, "pn-address-autofill", {
        "market": [1537],
        "environment": [1537],
        "endpoint": [1],
        "cache": [4],
        "countryCode": [1, "country-code"],
        "language": [1],
        "postalCodeProps": [1, "postal-code-props"],
        "cityProps": [1, "city-props"],
        "streetAddressProps": [1, "street-address-props"],
        "streetNumberProps": [1, "street-number-props"],
        "addressNotFoundError": [1, "address-not-found-error"],
        "postalCode": [32],
        "city": [32],
        "streetAddress": [32],
        "streetNumber": [32],
        "validAddress": [32],
        "translation": [32],
        "postalCodeRequiredLabel": [32],
        "streetRequiredLabel": [32],
        "fullAddress": [32],
        "isLoading": [32]
    }]);
function defineCustomElement$1() {
    if (typeof customElements === "undefined") {
        return;
    }
    const components = ["pn-address-autofill"];
    components.forEach(tagName => { switch (tagName) {
        case "pn-address-autofill":
            if (!customElements.get(tagName)) {
                customElements.define(tagName, PnAddressAutofill$1);
            }
            break;
    } });
}

const PnAddressAutofill = PnAddressAutofill$1;
const defineCustomElement = defineCustomElement$1;

export { PnAddressAutofill, defineCustomElement };

//# sourceMappingURL=pn-address-autofill.js.map