import { InputDirective } from '@agorapulse/ui-components/input';
import { InputGroupComponent, InputPrefixComponent } from '@agorapulse/ui-components/input-group';
import { DropdownItemSingleOneLineComponent, DropdownSearchFormComponent, SelectBaseDirective } from '@agorapulse/ui-components/select';
import * as i1 from '@agorapulse/ui-symbol';
import { apCheck } from '@agorapulse/ui-symbol';
import { NgOptimizedImage } from '@angular/common';
import * as i0 from '@angular/core';
import { inject, DestroyRef, EventEmitter, forwardRef, Output, Input, ViewEncapsulation, Component } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import * as i2 from '@angular/forms';
import { FormGroup, FormControl, Validators, FormsModule, ReactiveFormsModule, NG_VALUE_ACCESSOR, NG_VALIDATORS } from '@angular/forms';
import * as i3 from '@ng-select/ng-select';
import { NgSelectModule } from '@ng-select/ng-select';

/* eslint-disable @typescript-eslint/no-empty-function */
const NUMBER_ONLY_PATTERN = /[0-9]/;
const DEFAULT_COUNTRY_CODE = 'US';
const DEFAULT_PHONE_NUMBER_CODE = '+1';
class PhoneNumberInputComponent {
    destroyRef = inject(DestroyRef);
    set errorsDisplayForced(errorsDisplayForced) {
        if (errorsDisplayForced) {
            this.formGroup.markAllAsTouched();
            Object.values(this.formGroup.controls).forEach(control => control.markAsDirty());
            this.formGroup.updateValueAndValidity();
        }
    }
    flagsBucketUrl;
    set phoneNumberInfos(phoneNumberInfos) {
        this.codeNumberInfos = phoneNumberInfos ?? [];
        this.countryCodeMappedPhoneNumberInfos = phoneNumberInfos.reduce((acc, phoneNumberInfo) => {
            acc[phoneNumberInfo.countryCode] = phoneNumberInfo;
            return acc;
        }, {});
    }
    codeNumberInfos = [];
    countryCodeMappedPhoneNumberInfos = {};
    name;
    placeholder;
    searchPlaceholder;
    set phoneNumber(phoneNumber) {
        this.formGroup.controls.phoneNumber.setValue(phoneNumber);
    }
    set phoneNumberCode(phoneNumberCode) {
        this.formGroup.controls.countryCode.setValue(phoneNumberCode);
    }
    set initialCountryCode(initialCountryCode) {
        const firstValue = this.findPhoneNumberInfoByCountryCode(initialCountryCode)?.countryCode;
        if (firstValue) {
            this.formGroup.patchValue({ countryCode: firstValue });
        }
    }
    changePhoneNumber = new EventEmitter();
    changePhoneNumberCode = new EventEmitter();
    formGroup = new FormGroup({
        countryCode: new FormControl(DEFAULT_COUNTRY_CODE, [Validators.required]),
        phoneNumber: new FormControl('', [Validators.required]),
    });
    onTouched = () => { };
    onChange = () => { };
    constructor(symbolRegistry) {
        symbolRegistry.registerSymbols([apCheck]);
    }
    ngOnInit() {
        // Subscribe to form changes to propagate them to the parent component
        this.formGroup.valueChanges.pipe(takeUntilDestroyed(this.destroyRef)).subscribe(value => {
            let phoneNumberCode = DEFAULT_PHONE_NUMBER_CODE;
            if (value.countryCode) {
                const phoneNumberInfo = this.findPhoneNumberInfoByCountryCode(value.countryCode);
                if (phoneNumberInfo) {
                    phoneNumberCode = phoneNumberInfo.phoneNumberCode;
                }
            }
            if (this.onChange && phoneNumberCode) {
                this.onChange({
                    phoneNumber: value.phoneNumber,
                    phoneNumberCode,
                });
            }
            if (value.phoneNumber !== this.phoneNumber) {
                this.changePhoneNumber.emit(value.phoneNumber ?? '');
            }
            if (phoneNumberCode !== this.phoneNumberCode) {
                this.changePhoneNumberCode.emit(phoneNumberCode ?? '');
            }
        });
    }
    registerOnChange(fn) {
        this.onChange = fn;
    }
    registerOnTouched(fn) {
        this.onTouched = fn;
    }
    validate() {
        return this.formGroup.valid ? null : { phoneNumber: 'invalid', ...this.formGroup.errors };
    }
    writeValue(phone) {
        // Avoid setting an empty value for the phone number code, it should always have a value
        if (phone === null || !phone.phoneNumberCode) {
            this.formGroup.patchValue({ phoneNumber: phone?.phoneNumberCode ?? '' });
        }
        else {
            this.formGroup.patchValue(phone);
        }
    }
    phoneNumberCodeSearchFn(term, item) {
        const termCased = term.toLocaleLowerCase();
        return item.countryName.toLocaleLowerCase().indexOf(termCased) > -1 || item.countryCode.toLocaleLowerCase().indexOf(termCased) > -1;
    }
    markAsTouched() {
        this.formGroup.markAllAsTouched();
    }
    /**
     * Filter the phone number input to only allow numbers
     */
    filterChars(event) {
        if (event.inputType !== 'insertText') {
            return;
        }
        const inputChar = event.data;
        if (inputChar && !NUMBER_ONLY_PATTERN.test(inputChar)) {
            event.preventDefault();
        }
    }
    findPhoneNumberInfoByCountryCode(countryCode) {
        return this.codeNumberInfos.find(codeInfo => codeInfo.countryCode === countryCode);
    }
    static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.16", ngImport: i0, type: PhoneNumberInputComponent, deps: [{ token: i1.SymbolRegistry }], target: i0.ɵɵFactoryTarget.Component });
    static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "21.2.16", type: PhoneNumberInputComponent, isStandalone: true, selector: "ap-phone-number-input", inputs: { errorsDisplayForced: "errorsDisplayForced", flagsBucketUrl: "flagsBucketUrl", phoneNumberInfos: "phoneNumberInfos", name: "name", placeholder: "placeholder", searchPlaceholder: "searchPlaceholder", phoneNumber: "phoneNumber", phoneNumberCode: "phoneNumberCode", initialCountryCode: "initialCountryCode" }, outputs: { changePhoneNumber: "changePhoneNumber", changePhoneNumberCode: "changePhoneNumberCode" }, providers: [
            {
                provide: NG_VALUE_ACCESSOR,
                useExisting: forwardRef(() => PhoneNumberInputComponent),
                multi: true,
            },
            {
                provide: NG_VALIDATORS,
                useExisting: forwardRef(() => PhoneNumberInputComponent),
                multi: true,
            },
        ], ngImport: i0, template: "<ng-container [formGroup]=\"formGroup\">\n    <ng-select\n            #select\n            apSelectSingle\n            data-test=\"subscription-billing-infos-phoneNumberCode\"\n            class=\"ap-phone-number-code-select ap-select\"\n            bindLabel=\"countryName\"\n            bindValue=\"countryCode\"\n            notFoundText=\"\"\n            formControlName=\"countryCode\"\n            appendTo=\"body\"\n            [clearable]=\"false\"\n            [items]=\"codeNumberInfos\"\n            [searchFn]=\"phoneNumberCodeSearchFn\"\n            (blur)=\"onTouched()\">\n            <ng-template\n                let-item=\"item\"\n                ng-label-tmp>\n                @if (item && item.countryCode) {\n                    <div class=\"flag\">\n                        @if (!!flagsBucketUrl) {\n                            <img\n                                width=\"24\"\n                                height=\"16\"\n                                alt=\"flag\"\n                                [ngSrc]=\"flagsBucketUrl + '/' + item.countryCode.toUpperCase() + '.png'\" />\n                        } @else {\n                            <span>{{ item.countryCode }}</span>\n                        }\n                    </div>\n                }\n            </ng-template>\n            <ng-template\n                let-item=\"item\"\n                let-item$=\"item$\"\n                ng-option-tmp>\n                <ap-dropdown-item-single-one-line\n                    [text]=\"item.phoneNumberCode + ' ' + item.countryName\"\n                    [avatarUrl]=\"flagsBucketUrl + '/' + item.countryCode.toUpperCase() + '.png'\"\n                    [selected]=\"item$.selected\"\n                    [roundedAvatar]=\"false\"\n                />\n            </ng-template>\n            <ng-template\n                let-searchTerm=\"searchTerm\"\n                ng-header-tmp>\n                <ap-dropdown-search-form\n                  [searchPlaceholder]=\"searchPlaceholder\"\n                  [select]=\"select\"\n                />\n              </ng-template>\n    </ng-select>\n    <ap-input-group class=\"phone-number-input-group\">\n        @let countryCode = formGroup.controls.countryCode.value;\n        @let phoneNumberCode = countryCode ? countryCodeMappedPhoneNumberInfos[countryCode]?.phoneNumberCode : '';\n        \n        @if (phoneNumberCode) {\n            <ap-input-prefix>{{phoneNumberCode}}</ap-input-prefix>\n        }\n        <input\n                apInput\n                class=\"phone-field\"\n                data-test=\"subscription-billing-infos-phoneNumberInput\"\n                type=\"text\"\n                data-recurly=\"phone\"\n                formControlName=\"phoneNumber\"\n                [placeholder]=\"placeholder\"\n                [attr.name]=\"name\"\n                (beforeinput)=\"filterChars($event)\"\n                (blur)=\"onTouched()\"\n        />\n    </ap-input-group>\n</ng-container>\n", styles: ["ng-dropdown-panel.ap-phone-number-code-select{width:auto!important;min-width:310px!important;max-width:310px}ng-dropdown-panel.ap-phone-number-code-select ap-dropdown-item-single-one-line .option{display:flex;flex-direction:row;align-items:center}ng-dropdown-panel.ap-phone-number-code-select ap-dropdown-item-single-one-line ap-avatar{border:0;max-height:16px;min-height:16px;height:initial;box-shadow:unset;overflow:hidden;background:none}ap-phone-number-input{display:flex;flex-direction:row;align-items:center;justify-content:flex-start;gap:var(--ref-spacing-xxs)}ap-phone-number-input .ap-phone-number-code-select{flex:0 0 70px;width:70px}ap-phone-number-input .ap-phone-number-code-select .flag{display:flex;flex-direction:row;align-items:center;justify-content:center;overflow:hidden}ap-phone-number-input .ap-phone-number-code-select .flag img{max-height:16px;max-width:24px;object-fit:cover;border-radius:4px;object-position:center center}ap-phone-number-input .ap-phone-number-code-select .ng-input{padding:2px var(--ref-spacing-sm)}ap-phone-number-input .ap-phone-number-code-select .ng-input input{display:none}ap-phone-number-input .phone-number-input-group{flex:1 0 auto}\n"], dependencies: [{ kind: "ngmodule", type: FormsModule }, { kind: "directive", type: i2.DefaultValueAccessor, selector: "input:not([type=checkbox])[formControlName],textarea[formControlName],input:not([type=checkbox])[formControl],textarea[formControl],input:not([type=checkbox])[ngModel],textarea[ngModel],[ngDefaultControl]" }, { kind: "directive", type: i2.NgControlStatus, selector: "[formControlName],[ngModel],[formControl]" }, { kind: "directive", type: i2.NgControlStatusGroup, selector: "[formGroupName],[formArrayName],[ngModelGroup],[formGroup],[formArray],form:not([ngNoForm]),[ngForm]" }, { kind: "ngmodule", type: NgSelectModule }, { kind: "component", type: i3.NgSelectComponent, selector: "ng-select", inputs: ["ariaLabelDropdown", "ariaLabel", "markFirst", "placeholder", "fixedPlaceholder", "notFoundText", "typeToSearchText", "preventToggleOnRightClick", "addTagText", "loadingText", "clearAllText", "dropdownPosition", "appendTo", "outsideClickEvent", "loading", "closeOnSelect", "hideSelected", "selectOnTab", "openOnEnter", "maxSelectedItems", "groupBy", "groupValue", "bufferAmount", "virtualScroll", "selectableGroup", "tabFocusOnClearButton", "selectableGroupAsModel", "searchFn", "trackByFn", "clearOnBackspace", "labelForId", "inputAttrs", "tabIndex", "readonly", "searchWhileComposing", "minTermLength", "editableSearchTerm", "ngClass", "typeahead", "multiple", "addTag", "searchable", "clearable", "clearKeepsDisabledOptions", "deselectOnClick", "clearSearchOnAdd", "compareWith", "keyDownFn", "popover", "bindLabel", "bindValue", "appearance", "isOpen", "items"], outputs: ["bindLabelChange", "bindValueChange", "appearanceChange", "isOpenChange", "itemsChange", "blur", "focus", "change", "open", "close", "search", "clear", "add", "remove", "scroll", "scrollToEnd"], exportAs: ["ngSelect"] }, { kind: "directive", type: i3.NgOptionTemplateDirective, selector: "[ng-option-tmp]" }, { kind: "directive", type: i3.NgLabelTemplateDirective, selector: "[ng-label-tmp]" }, { kind: "directive", type: i3.NgHeaderTemplateDirective, selector: "[ng-header-tmp]" }, { kind: "component", type: InputGroupComponent, selector: "ap-input-group", inputs: ["symbolPosition"] }, { kind: "directive", type: InputDirective, selector: "[apInput]" }, { kind: "component", type: InputPrefixComponent, selector: "ap-input-prefix" }, { kind: "component", type: DropdownItemSingleOneLineComponent, selector: "ap-dropdown-item-single-one-line", inputs: ["text", "selected", "disabled", "avatarUrl", "showAvatarInitials", "symbolId", "disabledTooltip", "badgeText", "dividerEnabled", "network", "roundedAvatar", "isFeatureLocked"], outputs: ["lockedFeatureClicked"] }, { kind: "ngmodule", type: ReactiveFormsModule }, { kind: "directive", type: i2.FormGroupDirective, selector: "[formGroup]", inputs: ["formGroup"], outputs: ["ngSubmit"], exportAs: ["ngForm"] }, { kind: "directive", type: i2.FormControlName, selector: "[formControlName]", inputs: ["formControlName", "disabled", "ngModel"], outputs: ["ngModelChange"] }, { kind: "directive", type: NgOptimizedImage, selector: "img[ngSrc]", inputs: ["ngSrc", "ngSrcset", "sizes", "width", "height", "decoding", "loading", "priority", "loaderParams", "disableOptimizedSrcset", "fill", "placeholder", "placeholderConfig", "src", "srcset"] }, { kind: "component", type: DropdownSearchFormComponent, selector: "ap-dropdown-search-form", inputs: ["searchPlaceholder", "createNewEnabled", "createText", "select"], outputs: ["createNew"] }], encapsulation: i0.ViewEncapsulation.None });
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.16", ngImport: i0, type: PhoneNumberInputComponent, decorators: [{
            type: Component,
            args: [{ selector: 'ap-phone-number-input', imports: [
                        FormsModule,
                        NgSelectModule,
                        InputGroupComponent,
                        SelectBaseDirective,
                        InputDirective,
                        InputPrefixComponent,
                        DropdownItemSingleOneLineComponent,
                        ReactiveFormsModule,
                        NgOptimizedImage,
                        DropdownSearchFormComponent,
                    ], providers: [
                        {
                            provide: NG_VALUE_ACCESSOR,
                            useExisting: forwardRef(() => PhoneNumberInputComponent),
                            multi: true,
                        },
                        {
                            provide: NG_VALIDATORS,
                            useExisting: forwardRef(() => PhoneNumberInputComponent),
                            multi: true,
                        },
                    ], encapsulation: ViewEncapsulation.None, template: "<ng-container [formGroup]=\"formGroup\">\n    <ng-select\n            #select\n            apSelectSingle\n            data-test=\"subscription-billing-infos-phoneNumberCode\"\n            class=\"ap-phone-number-code-select ap-select\"\n            bindLabel=\"countryName\"\n            bindValue=\"countryCode\"\n            notFoundText=\"\"\n            formControlName=\"countryCode\"\n            appendTo=\"body\"\n            [clearable]=\"false\"\n            [items]=\"codeNumberInfos\"\n            [searchFn]=\"phoneNumberCodeSearchFn\"\n            (blur)=\"onTouched()\">\n            <ng-template\n                let-item=\"item\"\n                ng-label-tmp>\n                @if (item && item.countryCode) {\n                    <div class=\"flag\">\n                        @if (!!flagsBucketUrl) {\n                            <img\n                                width=\"24\"\n                                height=\"16\"\n                                alt=\"flag\"\n                                [ngSrc]=\"flagsBucketUrl + '/' + item.countryCode.toUpperCase() + '.png'\" />\n                        } @else {\n                            <span>{{ item.countryCode }}</span>\n                        }\n                    </div>\n                }\n            </ng-template>\n            <ng-template\n                let-item=\"item\"\n                let-item$=\"item$\"\n                ng-option-tmp>\n                <ap-dropdown-item-single-one-line\n                    [text]=\"item.phoneNumberCode + ' ' + item.countryName\"\n                    [avatarUrl]=\"flagsBucketUrl + '/' + item.countryCode.toUpperCase() + '.png'\"\n                    [selected]=\"item$.selected\"\n                    [roundedAvatar]=\"false\"\n                />\n            </ng-template>\n            <ng-template\n                let-searchTerm=\"searchTerm\"\n                ng-header-tmp>\n                <ap-dropdown-search-form\n                  [searchPlaceholder]=\"searchPlaceholder\"\n                  [select]=\"select\"\n                />\n              </ng-template>\n    </ng-select>\n    <ap-input-group class=\"phone-number-input-group\">\n        @let countryCode = formGroup.controls.countryCode.value;\n        @let phoneNumberCode = countryCode ? countryCodeMappedPhoneNumberInfos[countryCode]?.phoneNumberCode : '';\n        \n        @if (phoneNumberCode) {\n            <ap-input-prefix>{{phoneNumberCode}}</ap-input-prefix>\n        }\n        <input\n                apInput\n                class=\"phone-field\"\n                data-test=\"subscription-billing-infos-phoneNumberInput\"\n                type=\"text\"\n                data-recurly=\"phone\"\n                formControlName=\"phoneNumber\"\n                [placeholder]=\"placeholder\"\n                [attr.name]=\"name\"\n                (beforeinput)=\"filterChars($event)\"\n                (blur)=\"onTouched()\"\n        />\n    </ap-input-group>\n</ng-container>\n", styles: ["ng-dropdown-panel.ap-phone-number-code-select{width:auto!important;min-width:310px!important;max-width:310px}ng-dropdown-panel.ap-phone-number-code-select ap-dropdown-item-single-one-line .option{display:flex;flex-direction:row;align-items:center}ng-dropdown-panel.ap-phone-number-code-select ap-dropdown-item-single-one-line ap-avatar{border:0;max-height:16px;min-height:16px;height:initial;box-shadow:unset;overflow:hidden;background:none}ap-phone-number-input{display:flex;flex-direction:row;align-items:center;justify-content:flex-start;gap:var(--ref-spacing-xxs)}ap-phone-number-input .ap-phone-number-code-select{flex:0 0 70px;width:70px}ap-phone-number-input .ap-phone-number-code-select .flag{display:flex;flex-direction:row;align-items:center;justify-content:center;overflow:hidden}ap-phone-number-input .ap-phone-number-code-select .flag img{max-height:16px;max-width:24px;object-fit:cover;border-radius:4px;object-position:center center}ap-phone-number-input .ap-phone-number-code-select .ng-input{padding:2px var(--ref-spacing-sm)}ap-phone-number-input .ap-phone-number-code-select .ng-input input{display:none}ap-phone-number-input .phone-number-input-group{flex:1 0 auto}\n"] }]
        }], ctorParameters: () => [{ type: i1.SymbolRegistry }], propDecorators: { errorsDisplayForced: [{
                type: Input
            }], flagsBucketUrl: [{
                type: Input,
                args: [{ required: true }]
            }], phoneNumberInfos: [{
                type: Input,
                args: [{ required: true }]
            }], name: [{
                type: Input,
                args: [{ required: true }]
            }], placeholder: [{
                type: Input,
                args: [{ required: true }]
            }], searchPlaceholder: [{
                type: Input,
                args: [{ required: true }]
            }], phoneNumber: [{
                type: Input
            }], phoneNumberCode: [{
                type: Input
            }], initialCountryCode: [{
                type: Input
            }], changePhoneNumber: [{
                type: Output
            }], changePhoneNumberCode: [{
                type: Output
            }] } });

/**
 * Generated bundle index. Do not edit.
 */

export { PhoneNumberInputComponent };
//# sourceMappingURL=agorapulse-ui-components-phone-number-input.mjs.map
