/*!
 * Built by ShiftSoftware
 * Copyright (c)
 */
import { Host, h } from "@stencil/core";
import cn from "../../global/lib/cn";
import { getInputLocalization } from "../../features/form-hook/index";
import { FormInputLabel } from "./components/form-input-label";
import { FormErrorMessage } from "./components/form-error-message";
import { FormInputPrefix } from "./components/form-input-prefix";
import { string } from "yup";
import { AsYouType } from "libphonenumber-js";
import { getCountryForTimezone } from "countries-and-timezones";
import { y } from "../forms/defaults/validation";
const partKeyPrefix = 'form-input-';
export class FormPhoneNumber {
    constructor() {
        this.type = 'text';
        this.prefixWidth = 0;
        this.localization = {};
        this.countryCode = 'IQ';
        this.isOpen = false;
        this.externalRequired = false;
        this.onInputChange = (event) => {
            const target = event.target;
            this.validator.reset();
            target.value = this.validator.input(this.getValue()).replace(this.inputPrefix, '').trim();
            this.form.onInput(event);
        };
        this.validate = () => {
            // @ts-ignore
            let v = string().meta(y.meta(this.name));
            v = v.test(y.require(this.name), y.require(this.name), value => {
                if (!this.externalRequired && !this.required)
                    return true;
                return !!value.replace(this.inputPrefix, '').trim();
            });
            v = v.test(y.format(this.name), y.format(this.name), value => {
                if (!value.replace(this.inputPrefix, '').trim())
                    return true; // let required handle empty cases
                const checker = new AsYouType(this.selectedValue);
                checker.input(this.getValue());
                return checker.isValid();
            });
            return v;
        };
        this.getValue = () => {
            var _a, _b;
            const raw = ((_a = this === null || this === void 0 ? void 0 : this.inputRef) === null || _a === void 0 ? void 0 : _a.value.trim().replace(/^\+/, '')) || '';
            const prefix = ((_b = this.inputPrefix) === null || _b === void 0 ? void 0 : _b.trim().replace(/^\+/, '')) || '';
            const stripped = raw.startsWith(prefix) ? raw.slice(prefix.length).trim() : raw;
            const hasPrefix = raw.startsWith(prefix);
            return hasPrefix ? '+' + prefix + ' ' + stripped : this.inputPrefix + ' ' + raw;
        };
        this.updateShiftSelectContext = (newValues) => {
            Object.entries(newValues).forEach(([key, value]) => {
                // @ts-ignore
                this[key] = value;
            });
        };
        this.handleSelection = (option) => {
            this.selectedValue = option.value;
            this.isOpen = false;
        };
        this.renderCountryOption = (renderOption) => {
            var _a, _b, _c;
            const v = new AsYouType((_a = renderOption.meta) === null || _a === void 0 ? void 0 : _a.code);
            const countryNumber = ((_c = (_b = v.metadata) === null || _b === void 0 ? void 0 : _b.numberingPlan) === null || _c === void 0 ? void 0 : _c.metadata[0]) || '';
            const divIdentifier = cn('custom-shift-select-option custom-shift-select-country-option', {
                'custom-shift-select-option-selected shift-select-option-selected': this.selectedValue === renderOption.value,
            });
            const labelIdentifier = 'shift-select-country-code-label';
            const numberIdentifier = 'shift-select-country-number';
            return (h("div", { part: divIdentifier, class: divIdentifier }, h("span", { part: labelIdentifier, class: labelIdentifier }, renderOption === null || renderOption === void 0 ? void 0 : renderOption.label), !!countryNumber && (h("span", { part: numberIdentifier, class: numberIdentifier }, '+' + countryNumber))));
        };
    }
    async componentWillLoad() {
        this.onDefaultValueChange();
        this.form.subscribe(this.name, this);
        this.onStaticValueChange(this.staticValue, false);
        if (typeof this.countryCode === 'string') {
            this.selectedValue = this.countryCode;
        }
        else if (Array.isArray(this.countryCode)) {
            const codes = this.countryCode.map(c => (typeof c === 'string' ? c : c.code).toUpperCase());
            const detectedCountry = this.detectCountryFromBrowser(codes);
            const match = detectedCountry;
            this.selectedValue = (match || codes[0]);
        }
    }
    detectCountryFromBrowser(availableCodes) {
        var _a;
        // 1. Try timezone → country mapping
        try {
            const tz = Intl.DateTimeFormat().resolvedOptions().timeZone;
            const country = getCountryForTimezone(tz);
            if (country && availableCodes.includes(country.id))
                return country.id;
        }
        catch (_b) { }
        // 2. Fallback to browser locale
        const languages = ((_a = navigator.languages) === null || _a === void 0 ? void 0 : _a.length) ? navigator.languages : [navigator.language];
        for (const lang of languages) {
            const parts = lang === null || lang === void 0 ? void 0 : lang.split('-');
            if ((parts === null || parts === void 0 ? void 0 : parts.length) >= 2) {
                const country = parts[parts.length - 1].toUpperCase();
                if (country.length === 2 && availableCodes.includes(country))
                    return country;
            }
        }
        return null;
    }
    async onCountryChange() {
        var _a, _b, _c;
        this.validator = new AsYouType(this.selectedValue);
        this.inputPrefix = this.validator ? '+' + ((_c = (_b = (_a = this.validator) === null || _a === void 0 ? void 0 : _a.metadata) === null || _b === void 0 ? void 0 : _b.numberingPlan) === null || _c === void 0 ? void 0 : _c.metadata[0]) : undefined;
        this.form.validateInput(this.name);
    }
    async onDefaultValueChange() {
        if (this.defaultValue && this.validator) {
            this.validator.reset();
            this.defaultValue = this.validator.input(this.defaultValue || '');
        }
    }
    async onStaticValueChange(newStaticValue, notInitialLoad = true) {
        if (!!newStaticValue) {
            this.defaultValue = newStaticValue;
            this.inputRef.value = newStaticValue;
        }
        else if (notInitialLoad) {
            this.defaultValue = '';
            this.inputRef.value = '';
        }
    }
    async onValidatorChange() {
        await this.componentDidLoad();
    }
    async componentDidLoad() {
        const prefix = this.el.getElementsByClassName(this.name + '-prefix')[0];
        this.prefixWidth = prefix ? prefix.getBoundingClientRect().width : 0;
        this.inputRef = this.el.getElementsByClassName(partKeyPrefix + this.name)[0];
    }
    async disconnectedCallback() {
        this.form.unsubscribe(this.name);
    }
    reset(newValue) {
        const value = newValue || this.defaultValue || '';
        this.inputRef.value = value;
        this.validator.reset();
        if (value)
            this.validator.input(value);
    }
    render() {
        const { disabled, isRequired, meta, isError, errorMessage } = this.form.getInputState(this.name);
        const part = partKeyPrefix + this.name;
        const { label, placeholder, errorTextMessage } = getInputLocalization(this, meta, errorMessage);
        const isDisabled = disabled || this.isLoading || !!this.staticValue || this.isDisabled || !this.selectedValue;
        this.externalRequired = isRequired;
        const hasMultipleCountries = Array.isArray(this.countryCode) && this.countryCode.length > 1;
        const options = Array.isArray(this.countryCode) &&
            this.countryCode.map(country => {
                if (typeof country === 'string') {
                    return { value: country, label: country, meta: { code: country } };
                }
                else {
                    return { value: country.code, label: country === null || country === void 0 ? void 0 : country.code, meta: { code: country.code } };
                }
            });
        return (h(Host, { translate: "no" }, h("label", { part: this.name, id: this.wrapperId, class: cn('form-input-label-container', this.wrapperClass, { disabled: isDisabled }) }, h(FormInputLabel, { name: this.name, isRequired: isRequired, label: label }), h("div", { dir: "ltr", part: cn(`${this.name}-container form-input-container form-phone-container`, { 'form-input-container-country': hasMultipleCountries }), class: cn('form-input-container form-phone-container', { 'form-input-container-country': hasMultipleCountries }) }, hasMultipleCountries && (h("div", { part: `${this.name}-input-country-selection form-input form-input-country-selection`, class: cn('form-input-country-selection shrink-0') }, h("shift-select", { hasTick: false, options: options, isOpen: this.isOpen, disableInput: isDisabled, selectedValue: this.selectedValue, handleSelection: this.handleSelection, renderOption: this.renderCountryOption, name: this.name + '-country-selection', updateContext: this.updateShiftSelectContext }))), h("div", { part: "form-input-container-wrapper", class: cn('form-input-container-wrapper', { 'flex-1 relative': hasMultipleCountries }) }, h(FormInputPrefix, { name: this.name, direction: "ltr", prefix: this.inputPrefix }), h("input", { type: this.type, name: this.name, disabled: isDisabled, onInput: this.onInputChange, defaultValue: this.defaultValue, part: cn(`${this.name}-input form-input`, { [`${this.name}-input-with-country form-input-with-country`]: hasMultipleCountries }), placeholder: placeholder || (meta === null || meta === void 0 ? void 0 : meta.placeholder), style: Object.assign({}, (this.prefixWidth ? { ['paddingLeft']: `${this.prefixWidth}px` } : {})), class: cn('form-input-style', part, {
                'form-input-error-style': isError,
            }) }))), h(FormErrorMessage, { name: this.name, isError: isError, errorMessage: errorTextMessage }))));
    }
    static get is() { return "form-phone-number"; }
    static get originalStyleUrls() {
        return {
            "$": ["form-inputs.css"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["form-inputs.css"]
        };
    }
    static get properties() {
        return {
            "name": {
                "type": "string",
                "attribute": "name",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false
            },
            "wrapperId": {
                "type": "string",
                "attribute": "wrapper-id",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false
            },
            "required": {
                "type": "boolean",
                "attribute": "required",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false
            },
            "isLoading": {
                "type": "boolean",
                "attribute": "is-loading",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false
            },
            "form": {
                "type": "unknown",
                "attribute": "form",
                "mutable": false,
                "complexType": {
                    "original": "FormHook<any>",
                    "resolved": "FormHook<any>",
                    "references": {
                        "FormHook": {
                            "location": "import",
                            "path": "~features/form-hook/form-hook",
                            "id": "src/features/form-hook/form-hook.ts::FormHook"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false
            },
            "inputPrefix": {
                "type": "string",
                "attribute": "input-prefix",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false
            },
            "wrapperClass": {
                "type": "string",
                "attribute": "wrapper-class",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false
            },
            "defaultValue": {
                "type": "string",
                "attribute": "default-value",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false
            },
            "type": {
                "type": "string",
                "attribute": "type",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "defaultValue": "'text'"
            },
            "isDisabled": {
                "type": "boolean",
                "attribute": "is-disabled",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false
            },
            "staticValue": {
                "type": "string",
                "attribute": "static-value",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false
            },
            "localization": {
                "type": "unknown",
                "attribute": "localization",
                "mutable": false,
                "complexType": {
                    "original": "FormInputLocalization",
                    "resolved": "{ [lang: string]: { label?: string; placeholder?: string; require?: string; format?: string; minMessage: string; maxMessage: string; betweenMessage: string; }; }",
                    "references": {
                        "FormInputLocalization": {
                            "location": "import",
                            "path": "~features/form-hook",
                            "id": "src/features/form-hook/index.ts::FormInputLocalization"
                        }
                    }
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "defaultValue": "{}"
            },
            "countryCode": {
                "type": "string",
                "attribute": "country-code",
                "mutable": false,
                "complexType": {
                    "original": "string | string[] | { code: string; icon?: string }[]",
                    "resolved": "string | string[] | { code: string; icon?: string; }[]",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "defaultValue": "'IQ'"
            }
        };
    }
    static get states() {
        return {
            "prefixWidth": {},
            "selectedValue": {},
            "isOpen": {},
            "validator": {},
            "externalRequired": {}
        };
    }
    static get elementRef() { return "el"; }
    static get watchers() {
        return [{
                "propName": "selectedValue",
                "methodName": "onCountryChange"
            }, {
                "propName": "defaultValue",
                "methodName": "onDefaultValueChange"
            }, {
                "propName": "staticValue",
                "methodName": "onStaticValueChange"
            }, {
                "propName": "inputPrefix",
                "methodName": "onValidatorChange"
            }];
    }
}
