/*!
 * Built with Stencil
 * By PostNord.
 */
'use strict';

var index = require('./index-CfUQZtlH.js');
var index$1 = require('./index.cjs.js');

const translations = {
    CLOSEST_DELIVERY_DATE: {
        en: 'Closest delivery date:',
        sv: 'Nästa utdelningsdag:',
    },
    NEXT_DELIVERY_DATE: {
        en: 'Next delivery date:',
        sv: 'Kommande utdelningsdag:',
    },
    ZIP_CODE: {
        en: 'Zip code:',
        sv: 'Postnummer:',
    },
    VALIDATION_ERROR_MESSAGE: {
        en: 'Zip code not valid',
        sv: 'Postnumret är inte giltigt',
    },
    SERVER_ERROR_MESSAGE: {
        en: 'Could not find zip code',
        sv: 'Kan inte hitta postnumret',
    },
    PLACEHOLDER_TEXT: {
        en: 'Search for a zip code',
        sv: 'Sök på ett postnummer',
    },
    SEARCH: {
        en: 'Search',
        sv: 'Sök',
    },
};

const pnZipcodeSearchCss = () => `${index.transformTag("pn-zipcode-search")}{display:block;color:#5e554a}${index.transformTag("pn-zipcode-search")} .pn-search-results{display:flex;flex-direction:column;gap:1em;padding:0 0.75em}${index.transformTag("pn-zipcode-search")} .pn-search-results span{color:#5e554a}${index.transformTag("pn-zipcode-search")} .pn-search-results h3{color:#2d2013}${index.transformTag("pn-zipcode-search")} .pn-error-text{color:#a70707;padding:0 0.75em}${index.transformTag("pn-zipcode-search")}>${index.transformTag("pn-search-field")}{width:100%;margin-bottom:1em}`;

const PnZipcodeSearch = class {
    constructor(hostRef) {
        index.registerInstance(this, hostRef);
        this.searchsuccessful = index.createEvent(this, "searchsuccessful");
    }
    /** This language property will update when pnTopbar loads */
    searchId = `pn-zipcode-${index$1.uuidv4()}`;
    get hostElement() { return index.getElement(this); }
    validZipCode;
    loading = false;
    showResult = false;
    zipCodeSearchResult = {
        delivery: '',
        upcoming: '',
        city: '',
        postalCode: '',
    };
    error = false;
    errorMessage;
    /** The `language` property will be prioritized before the pnTopbar language. */
    language = null;
    /** Set a pre initialized value. */
    value;
    /** Event fired when search has result */
    searchsuccessful;
    async componentWillLoad() {
        if (this.language === null)
            await index$1.awaitTopbar(this.hostElement);
        if (!!this.value)
            this.handleSearch(this.value);
    }
    translation(key) {
        return translations[key][this.language || index$1.sv];
    }
    handleSearch(value) {
        this.value = value;
        this.validateZipCode();
        if (this.error) {
            this.errorMessage = 'VALIDATION_ERROR_MESSAGE';
            return;
        }
        this.zipCodeSearch();
    }
    async zipCodeSearch() {
        this.loading = true;
        await fetch(`https://portal.postnord.com/api/sendoutarrival/closest?postalCode=${this.validZipCode}`)
            .then(response => response.json())
            .then(data => {
            this.showResult = true;
            this.zipCodeSearchResult = data;
            this.searchsuccessful.emit(true);
        })
            .catch(() => {
            this.error = true;
            this.errorMessage = 'SERVER_ERROR_MESSAGE';
            this.searchsuccessful.emit(false);
        })
            .finally(() => {
            this.loading = false;
        });
    }
    validateZipCode() {
        // Removes spaces and dashes
        const formatValue = this.value ? this.value.replace(/[ -]/gi, '') : '';
        const validRegex = /^\d{5}$/;
        const valid = validRegex.test(formatValue);
        this.error = !valid;
        if (valid) {
            this.validZipCode = formatValue;
        }
    }
    renderSearchResult() {
        if (!this.loading && !this.error && this.showResult) {
            return (index.h("output", { class: "pn-search-results", htmlFor: this.searchId }, index.h("p", { class: "text-row" }, index.h("span", null, this.translation('CLOSEST_DELIVERY_DATE')), index.h("h3", { class: "delivery-date" }, this.zipCodeSearchResult.delivery)), index.h("p", { class: "text-row" }, index.h("span", null, this.translation('NEXT_DELIVERY_DATE')), index.h("h3", { class: "delivery-date" }, this.zipCodeSearchResult.upcoming)), index.h("p", { class: "text-row" }, index.h("span", null, this.translation('ZIP_CODE')), index.h("h3", null, this.zipCodeSearchResult.postalCode, ", ", this.zipCodeSearchResult.city || 'N/A'))));
        }
    }
    renderErrorMessage() {
        if (this.error && !this.loading) {
            return (index.h("p", { class: "pn-error-text", role: "alert" }, index.h("small", null, this.translation(this.errorMessage))));
        }
    }
    render() {
        return (index.h(index.Host, { key: 'b9314bbca808c725bc074d1dc9e58223bb551468' }, index.h("pn-search-field", { key: '4c7eaf8c96aa36e17c546371345c7aac6a0c5ee7', label: this.translation('PLACEHOLDER_TEXT'), value: this.value, searchid: this.searchId, loading: this.loading, button: "icon", buttonLabel: this.translation('SEARCH'), placeholder: this.translation('PLACEHOLDER_TEXT'), onSearch: e => this.handleSearch(e.detail) }), this.renderSearchResult(), this.renderErrorMessage()));
    }
};
PnZipcodeSearch.style = pnZipcodeSearchCss();

exports.pn_zipcode_search = PnZipcodeSearch;
