import * as i0 from '@angular/core';
import { numberAttribute, input, signal, computed, inject, effect, HostBinding, ViewChild, ChangeDetectionStrategy, Component } from '@angular/core';
import * as i2 from 'primeng/inputtext';
import { InputTextModule } from 'primeng/inputtext';
import * as i1 from '@angular/forms';
import { NgControl, FormsModule } from '@angular/forms';
import { Tooltip } from '@masterteam/components/tooltip';
import { characterLimitValidator, FieldValidation } from '@masterteam/components/field-validation';
import { isInvalid } from '@masterteam/components';
import { Icon } from '@masterteam/icons';
import { TranslocoService } from '@jsverse/transloco';

const requiredNoWhitespace = (control) => {
    const value = control.value;
    if (value === null || value === undefined)
        return { required: true };
    if (typeof value === 'string' && value.trim() === '')
        return { required: true };
    return null;
};
const TEXT_FIELD_MAX_LENGTH = 300;
const optionalNumberAttribute = (value) => value === null || value === undefined
    ? null
    : numberAttribute(value, TEXT_FIELD_MAX_LENGTH);
// TODO: text stuck when reset
class TextField {
    inputText;
    field = input(true, ...(ngDevMode ? [{ debugName: "field" }] : /* istanbul ignore next */ []));
    hint = input(...(ngDevMode ? [undefined, { debugName: "hint" }] : /* istanbul ignore next */ []));
    label = input(...(ngDevMode ? [undefined, { debugName: "label" }] : /* istanbul ignore next */ []));
    placeholder = input(...(ngDevMode ? [undefined, { debugName: "placeholder" }] : /* istanbul ignore next */ []));
    class = input('', ...(ngDevMode ? [{ debugName: "class" }] : /* istanbul ignore next */ []));
    type = input('text', ...(ngDevMode ? [{ debugName: "type" }] : /* istanbul ignore next */ []));
    readonly = input(false, ...(ngDevMode ? [{ debugName: "readonly" }] : /* istanbul ignore next */ []));
    pInputs = input(...(ngDevMode ? [undefined, { debugName: "pInputs" }] : /* istanbul ignore next */ []));
    // readonly pKeyFilter = input<KeyFilterPattern | RegExp>();
    required = input(false, ...(ngDevMode ? [{ debugName: "required" }] : /* istanbul ignore next */ []));
    maxLength = input(TEXT_FIELD_MAX_LENGTH, { ...(ngDevMode ? { debugName: "maxLength" } : /* istanbul ignore next */ {}), transform: optionalNumberAttribute });
    icon = input(...(ngDevMode ? [undefined, { debugName: "icon" }] : /* istanbul ignore next */ []));
    iconPosition = input('start', ...(ngDevMode ? [{ debugName: "iconPosition" }] : /* istanbul ignore next */ []));
    // readonly externalControl = input<any>(null);
    styleClass;
    requiredValidator = requiredNoWhitespace;
    maxLengthValidator = null;
    value = signal(null, ...(ngDevMode ? [{ debugName: "value" }] : /* istanbul ignore next */ []));
    disabled = signal(false, ...(ngDevMode ? [{ debugName: "disabled" }] : /* istanbul ignore next */ []));
    passwordVisible = signal(false, ...(ngDevMode ? [{ debugName: "passwordVisible" }] : /* istanbul ignore next */ []));
    isPasswordField = computed(() => this.type() === 'password', ...(ngDevMode ? [{ debugName: "isPasswordField" }] : /* istanbul ignore next */ []));
    inputType = computed(() => this.isPasswordField() && this.passwordVisible() ? 'text' : this.type(), ...(ngDevMode ? [{ debugName: "inputType" }] : /* istanbul ignore next */ []));
    hasStartIcon = computed(() => Boolean(this.icon()) && this.iconPosition() === 'start', ...(ngDevMode ? [{ debugName: "hasStartIcon" }] : /* istanbul ignore next */ []));
    hasEndIcon = computed(() => this.isPasswordField() ||
        (Boolean(this.icon()) && this.iconPosition() === 'end'), ...(ngDevMode ? [{ debugName: "hasEndIcon" }] : /* istanbul ignore next */ []));
    hasHint = computed(() => Boolean(this.hint()), ...(ngDevMode ? [{ debugName: "hasHint" }] : /* istanbul ignore next */ []));
    hasEndActions = computed(() => this.hasEndIcon() || this.hasHint(), ...(ngDevMode ? [{ debugName: "hasEndActions" }] : /* istanbul ignore next */ []));
    hasTwoEndActions = computed(() => this.hasEndIcon() && this.hasHint(), ...(ngDevMode ? [{ debugName: "hasTwoEndActions" }] : /* istanbul ignore next */ []));
    passwordToggleIcon = computed(() => this.passwordVisible() ? 'general.eye-off' : 'general.eye', ...(ngDevMode ? [{ debugName: "passwordToggleIcon" }] : /* istanbul ignore next */ []));
    transloco = inject(TranslocoService);
    passwordToggleLabel = computed(() => this.passwordVisible()
        ? this.transloco.translate('components.textField.hidePassword')
        : this.transloco.translate('components.textField.showPassword'), ...(ngDevMode ? [{ debugName: "passwordToggleLabel" }] : /* istanbul ignore next */ []));
    alphaNum = /[\u0621-\u064A\u0660-\u0669a-z0-9\s]/i;
    onTouched = () => { };
    onModelChange = () => { };
    ngControl = null;
    isInvalid = isInvalid;
    constructor() {
        try {
            // Try to inject NgControl if available
            this.ngControl = inject(NgControl, { self: true, optional: true });
            if (this.ngControl) {
                this.ngControl.valueAccessor = this;
            }
        }
        catch (_e) {
            // If injection fails, ngControl will remain null
            this.ngControl = null;
        }
        effect(() => {
            const control = this.ngControl?.control;
            if (!control) {
                return;
            }
            if (this.required()) {
                control.addValidators(this.requiredValidator);
            }
            if (this.maxLengthValidator) {
                control.removeValidators(this.maxLengthValidator);
                this.maxLengthValidator = null;
            }
            const maxLength = this.maxLength();
            if (maxLength !== null) {
                this.maxLengthValidator = characterLimitValidator(maxLength);
                control.addValidators(this.maxLengthValidator);
            }
            control.updateValueAndValidity({ emitEvent: false });
        });
    }
    ngOnInit() {
        this.styleClass = this.class();
        // if (this.externalControl()) {
        //   debugger
        //   this.ngControl = this.externalControl();
        // }
        if (this.pInputs()) {
            this.applyInputsToInputText();
        }
    }
    applyInputsToInputText() {
        Object.assign(this.inputText, this.pInputs());
    }
    onValueChange(value) {
        this.value.set(value);
        const control = this.ngControl?.control;
        if (control) {
            control.setValue(value);
            control.markAsDirty();
            control.markAsTouched();
            control.updateValueAndValidity({ emitEvent: false });
            return;
        }
        this.onModelChange(value);
        this.onTouched();
    }
    togglePasswordVisibility() {
        if (this.disabled() || this.readonly()) {
            return;
        }
        this.passwordVisible.update((visible) => !visible);
    }
    ngOnChanges(changes) {
        if (changes['pInputs']) {
            this.applyInputsToInputText();
        }
    }
    writeValue(value) {
        this.value.set(value);
    }
    registerOnChange(fn) {
        this.onModelChange = fn;
    }
    registerOnTouched(fn) {
        this.onTouched = fn;
    }
    setDisabledState(disabled) {
        this.disabled.set(disabled);
    }
    static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.8", ngImport: i0, type: TextField, deps: [], target: i0.ɵɵFactoryTarget.Component });
    static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "21.2.8", type: TextField, isStandalone: true, selector: "mt-text-field", inputs: { field: { classPropertyName: "field", publicName: "field", isSignal: true, isRequired: false, transformFunction: null }, hint: { classPropertyName: "hint", publicName: "hint", isSignal: true, isRequired: false, transformFunction: null }, label: { classPropertyName: "label", publicName: "label", isSignal: true, isRequired: false, transformFunction: null }, placeholder: { classPropertyName: "placeholder", publicName: "placeholder", isSignal: true, isRequired: false, transformFunction: null }, class: { classPropertyName: "class", publicName: "class", isSignal: true, isRequired: false, transformFunction: null }, type: { classPropertyName: "type", publicName: "type", isSignal: true, isRequired: false, transformFunction: null }, readonly: { classPropertyName: "readonly", publicName: "readonly", isSignal: true, isRequired: false, transformFunction: null }, pInputs: { classPropertyName: "pInputs", publicName: "pInputs", isSignal: true, isRequired: false, transformFunction: null }, required: { classPropertyName: "required", publicName: "required", isSignal: true, isRequired: false, transformFunction: null }, maxLength: { classPropertyName: "maxLength", publicName: "maxLength", isSignal: true, isRequired: false, transformFunction: null }, icon: { classPropertyName: "icon", publicName: "icon", isSignal: true, isRequired: false, transformFunction: null }, iconPosition: { classPropertyName: "iconPosition", publicName: "iconPosition", isSignal: true, isRequired: false, transformFunction: null } }, host: { properties: { "class": "this.styleClass" }, classAttribute: "grid gap-1" }, viewQueries: [{ propertyName: "inputText", first: true, predicate: ["inputText"], descendants: true, static: true }], usesOnChanges: true, ngImport: i0, template: "@if (label()) {\r\n  <label\r\n    [class.required]=\"ngControl?.control?.hasValidator(requiredValidator)\"\r\n    [for]=\"ngControl?.name || label()\"\r\n    >{{ label() }}</label\r\n  >\r\n}\r\n\r\n<div\r\n  class=\"mt-text-field__input\"\r\n  [class.mt-text-field__input--start-icon]=\"hasStartIcon()\"\r\n  [class.mt-text-field__input--end-action]=\"hasEndActions()\"\r\n  [class.mt-text-field__input--two-end-actions]=\"hasTwoEndActions()\"\r\n>\r\n  @if (icon() && iconPosition() === \"start\") {\r\n    <span class=\"mt-text-field__icon mt-text-field__icon--start\">\r\n      <mt-icon [icon]=\"icon()\" />\r\n    </span>\r\n  }\r\n\r\n  <input\r\n    #inputText=\"\"\r\n    pInputText=\"\"\r\n    [ngModel]=\"value()\"\r\n    (ngModelChange)=\"onValueChange($event)\"\r\n    [disabled]=\"disabled() || readonly()\"\r\n    [type]=\"inputType()\"\r\n    [id]=\"ngControl?.name || label()\"\r\n    [invalid]=\"isInvalid(ngControl?.control)\"\r\n    (blur)=\"onTouched()\"\r\n    placeholder=\"{{ placeholder() ?? label() ?? '' }}\"\r\n    class=\"w-full\"\r\n  />\r\n\r\n  @if (isPasswordField()) {\r\n    <button\r\n      type=\"button\"\r\n      class=\"mt-text-field__action\"\r\n      [class.mt-text-field__action--before-hint]=\"hasHint()\"\r\n      [disabled]=\"disabled() || readonly()\"\r\n      [attr.aria-label]=\"passwordToggleLabel()\"\r\n      [mtTooltip]=\"passwordToggleLabel()\"\r\n      tooltipPosition=\"top\"\r\n      (click)=\"togglePasswordVisibility()\"\r\n    >\r\n      <mt-icon [icon]=\"passwordToggleIcon()\" />\r\n    </button>\r\n  } @else if (icon() && iconPosition() === \"end\") {\r\n    <span\r\n      class=\"mt-text-field__icon mt-text-field__icon--end\"\r\n      [class.mt-text-field__icon--before-hint]=\"hasHint()\"\r\n    >\r\n      <mt-icon [icon]=\"icon()\" />\r\n    </span>\r\n  }\r\n\r\n  @if (hint()) {\n    <span\n      class=\"mt-text-field__icon mt-text-field__icon--end\"\n      [mtTooltip]=\"hint()\"\n      tooltipPosition=\"top\"\n    >\n      <mt-icon icon=\"general.info-circle\" />\r\n    </span>\r\n  }\r\n</div>\r\n\r\n<mt-field-validation [control]=\"ngControl?.control\"></mt-field-validation>\r\n", styles: [".mt-text-field__input{flex:1 1 auto;position:relative;width:100%}.mt-text-field__input--start-icon input{padding-inline-start:2.25rem}.mt-text-field__input--end-action input{padding-inline-end:2.25rem}.mt-text-field__input--two-end-actions input{padding-inline-end:4.25rem}.mt-text-field__icon,.mt-text-field__action{align-items:center;color:var(--p-text-muted-color);display:inline-flex;height:100%;inset-block-start:0;justify-content:center;position:absolute;width:2.25rem;z-index:1}.mt-text-field__icon--start{inset-inline-start:0}.mt-text-field__icon--end,.mt-text-field__action{inset-inline-end:0}.mt-text-field__icon--before-hint,.mt-text-field__action--before-hint{inset-inline-end:2rem}.mt-text-field__action{background:transparent;border:0;cursor:pointer;padding:0}.mt-text-field__action:disabled{cursor:default;opacity:.65}\n"], dependencies: [{ kind: "ngmodule", type: FormsModule }, { kind: "directive", type: i1.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: i1.NgControlStatus, selector: "[formControlName],[ngModel],[formControl]" }, { kind: "directive", type: i1.NgModel, selector: "[ngModel]:not([formControlName]):not([formControl])", inputs: ["name", "disabled", "ngModel", "ngModelOptions"], outputs: ["ngModelChange"], exportAs: ["ngModel"] }, { kind: "ngmodule", type: InputTextModule }, { kind: "directive", type: i2.InputText, selector: "[pInputText]", inputs: ["hostName", "ptInputText", "pInputTextPT", "pInputTextUnstyled", "pSize", "variant", "fluid", "invalid"] }, { kind: "directive", type: 
                // INFO: if we need this filter uncomment the import, and next line and add this to the template input
                //[pKeyFilter]="
                //   pKeyFilter()
                //     ? pKeyFilter() === 'alphanum'
                //       ? alphaNum
                //       : pKeyFilter()
                //     : null
                // "
                // KeyFilterModule,
                Tooltip, selector: "[mtTooltip]" }, { kind: "component", type: FieldValidation, selector: "mt-field-validation", inputs: ["control", "touched"] }, { kind: "component", type: Icon, selector: "mt-icon", inputs: ["icon"] }], changeDetection: i0.ChangeDetectionStrategy.OnPush });
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.8", ngImport: i0, type: TextField, decorators: [{
            type: Component,
            args: [{ selector: 'mt-text-field', standalone: true, imports: [
                        FormsModule,
                        InputTextModule,
                        // INFO: if we need this filter uncomment the import, and next line and add this to the template input
                        //[pKeyFilter]="
                        //   pKeyFilter()
                        //     ? pKeyFilter() === 'alphanum'
                        //       ? alphaNum
                        //       : pKeyFilter()
                        //     : null
                        // "
                        // KeyFilterModule,
                        Tooltip,
                        FieldValidation,
                        Icon,
                    ], changeDetection: ChangeDetectionStrategy.OnPush, host: {
                        class: 'grid gap-1',
                    }, template: "@if (label()) {\r\n  <label\r\n    [class.required]=\"ngControl?.control?.hasValidator(requiredValidator)\"\r\n    [for]=\"ngControl?.name || label()\"\r\n    >{{ label() }}</label\r\n  >\r\n}\r\n\r\n<div\r\n  class=\"mt-text-field__input\"\r\n  [class.mt-text-field__input--start-icon]=\"hasStartIcon()\"\r\n  [class.mt-text-field__input--end-action]=\"hasEndActions()\"\r\n  [class.mt-text-field__input--two-end-actions]=\"hasTwoEndActions()\"\r\n>\r\n  @if (icon() && iconPosition() === \"start\") {\r\n    <span class=\"mt-text-field__icon mt-text-field__icon--start\">\r\n      <mt-icon [icon]=\"icon()\" />\r\n    </span>\r\n  }\r\n\r\n  <input\r\n    #inputText=\"\"\r\n    pInputText=\"\"\r\n    [ngModel]=\"value()\"\r\n    (ngModelChange)=\"onValueChange($event)\"\r\n    [disabled]=\"disabled() || readonly()\"\r\n    [type]=\"inputType()\"\r\n    [id]=\"ngControl?.name || label()\"\r\n    [invalid]=\"isInvalid(ngControl?.control)\"\r\n    (blur)=\"onTouched()\"\r\n    placeholder=\"{{ placeholder() ?? label() ?? '' }}\"\r\n    class=\"w-full\"\r\n  />\r\n\r\n  @if (isPasswordField()) {\r\n    <button\r\n      type=\"button\"\r\n      class=\"mt-text-field__action\"\r\n      [class.mt-text-field__action--before-hint]=\"hasHint()\"\r\n      [disabled]=\"disabled() || readonly()\"\r\n      [attr.aria-label]=\"passwordToggleLabel()\"\r\n      [mtTooltip]=\"passwordToggleLabel()\"\r\n      tooltipPosition=\"top\"\r\n      (click)=\"togglePasswordVisibility()\"\r\n    >\r\n      <mt-icon [icon]=\"passwordToggleIcon()\" />\r\n    </button>\r\n  } @else if (icon() && iconPosition() === \"end\") {\r\n    <span\r\n      class=\"mt-text-field__icon mt-text-field__icon--end\"\r\n      [class.mt-text-field__icon--before-hint]=\"hasHint()\"\r\n    >\r\n      <mt-icon [icon]=\"icon()\" />\r\n    </span>\r\n  }\r\n\r\n  @if (hint()) {\n    <span\n      class=\"mt-text-field__icon mt-text-field__icon--end\"\n      [mtTooltip]=\"hint()\"\n      tooltipPosition=\"top\"\n    >\n      <mt-icon icon=\"general.info-circle\" />\r\n    </span>\r\n  }\r\n</div>\r\n\r\n<mt-field-validation [control]=\"ngControl?.control\"></mt-field-validation>\r\n", styles: [".mt-text-field__input{flex:1 1 auto;position:relative;width:100%}.mt-text-field__input--start-icon input{padding-inline-start:2.25rem}.mt-text-field__input--end-action input{padding-inline-end:2.25rem}.mt-text-field__input--two-end-actions input{padding-inline-end:4.25rem}.mt-text-field__icon,.mt-text-field__action{align-items:center;color:var(--p-text-muted-color);display:inline-flex;height:100%;inset-block-start:0;justify-content:center;position:absolute;width:2.25rem;z-index:1}.mt-text-field__icon--start{inset-inline-start:0}.mt-text-field__icon--end,.mt-text-field__action{inset-inline-end:0}.mt-text-field__icon--before-hint,.mt-text-field__action--before-hint{inset-inline-end:2rem}.mt-text-field__action{background:transparent;border:0;cursor:pointer;padding:0}.mt-text-field__action:disabled{cursor:default;opacity:.65}\n"] }]
        }], ctorParameters: () => [], propDecorators: { inputText: [{
                type: ViewChild,
                args: ['inputText', { static: true }]
            }], field: [{ type: i0.Input, args: [{ isSignal: true, alias: "field", required: false }] }], hint: [{ type: i0.Input, args: [{ isSignal: true, alias: "hint", required: false }] }], label: [{ type: i0.Input, args: [{ isSignal: true, alias: "label", required: false }] }], placeholder: [{ type: i0.Input, args: [{ isSignal: true, alias: "placeholder", required: false }] }], class: [{ type: i0.Input, args: [{ isSignal: true, alias: "class", required: false }] }], type: [{ type: i0.Input, args: [{ isSignal: true, alias: "type", required: false }] }], readonly: [{ type: i0.Input, args: [{ isSignal: true, alias: "readonly", required: false }] }], pInputs: [{ type: i0.Input, args: [{ isSignal: true, alias: "pInputs", required: false }] }], required: [{ type: i0.Input, args: [{ isSignal: true, alias: "required", required: false }] }], maxLength: [{ type: i0.Input, args: [{ isSignal: true, alias: "maxLength", required: false }] }], icon: [{ type: i0.Input, args: [{ isSignal: true, alias: "icon", required: false }] }], iconPosition: [{ type: i0.Input, args: [{ isSignal: true, alias: "iconPosition", required: false }] }], styleClass: [{
                type: HostBinding,
                args: ['class']
            }] } });

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

export { TextField };
//# sourceMappingURL=masterteam-components-text-field.mjs.map
