import * as i0 from '@angular/core';
import { inject, Pipe, input, booleanAttribute, Component } from '@angular/core';
import { Message } from 'primeng/message';
import { TranslocoService } from '@jsverse/transloco';
import { isInvalid } from '@masterteam/components';

class ErrorMessagePipe {
    translocoService = inject(TranslocoService);
    transform(errors) {
        if (!errors) {
            return '';
        }
        const t = (key, params) => this.translocoService.translate(`components.validation.${key}`, params);
        if (errors['required']) {
            return t('required');
        }
        if (errors['email']) {
            return t('email');
        }
        if (errors['minlength']) {
            const { requiredLength } = errors['minlength'];
            return t('minLength', { requiredLength });
        }
        if (errors['maxlength']) {
            const { requiredLength } = errors['maxlength'];
            return t('maxLength', { requiredLength });
        }
        if (errors['characterLimit']) {
            const { requiredLength } = errors['characterLimit'];
            return t('maxLength', { requiredLength });
        }
        if (errors['min']) {
            const { min } = errors['min'];
            return t('min', { min });
        }
        if (errors['max']) {
            const { max } = errors['max'];
            return t('max', { max });
        }
        if (errors['pattern']) {
            return t('pattern');
        }
        if (errors['fileSizeLimited']) {
            return t('fileSizeLimited');
        }
        // Handle custom errors that provide their own message
        for (const key in errors) {
            const errorValue = errors[key];
            if (errorValue && typeof errorValue === 'object' && errorValue.message) {
                return errorValue.message;
            }
        }
        // Fallback for any other error
        const firstErrorKey = Object.keys(errors)[0];
        return t('invalid', { key: firstErrorKey });
    }
    static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.8", ngImport: i0, type: ErrorMessagePipe, deps: [], target: i0.ɵɵFactoryTarget.Pipe });
    static ɵpipe = i0.ɵɵngDeclarePipe({ minVersion: "14.0.0", version: "21.2.8", ngImport: i0, type: ErrorMessagePipe, isStandalone: true, name: "errorMessage", pure: false });
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.8", ngImport: i0, type: ErrorMessagePipe, decorators: [{
            type: Pipe,
            args: [{
                    name: 'errorMessage',
                    standalone: true,
                    pure: false,
                }]
        }] });

class FieldValidation {
    control = input(null, ...(ngDevMode ? [{ debugName: "control" }] : /* istanbul ignore next */ []));
    touched = input(false, { ...(ngDevMode ? { debugName: "touched" } : /* istanbul ignore next */ {}), transform: booleanAttribute });
    isInvalid = isInvalid;
    /**
     * Reserve the error-message line whenever the control can surface an error —
     * i.e. it has sync/async validators, or is already showing one. This keeps the
     * field's height constant so showing the error never pushes sibling fields or
     * the content below the row. Re-evaluated each change-detection cycle, so it
     * picks up validators that fields add asynchronously after init.
     */
    shouldReserveSpace() {
        const control = this.control();
        if (!control) {
            return false;
        }
        return (control.validator !== null ||
            control.asyncValidator !== null ||
            isInvalid(control));
    }
    static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.8", ngImport: i0, type: FieldValidation, deps: [], target: i0.ɵɵFactoryTarget.Component });
    static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "21.2.8", type: FieldValidation, isStandalone: true, selector: "mt-field-validation", inputs: { control: { classPropertyName: "control", publicName: "control", isSignal: true, isRequired: false, transformFunction: null }, touched: { classPropertyName: "touched", publicName: "touched", isSignal: true, isRequired: false, transformFunction: null } }, host: { properties: { "class.mt-field-validation--reserved": "shouldReserveSpace()" }, classAttribute: "mt-field-validation" }, ngImport: i0, template: `
    @if (isInvalid(control())) {
      <p-message
        severity="error"
        variant="simple"
        size="small"
        [text]="control().errors | errorMessage"
      >
      </p-message>
    }
  `, isInline: true, styles: [".mt-field-validation{display:none}.mt-field-validation--reserved{display:block;min-height:1.25rem}\n"], dependencies: [{ kind: "component", type: Message, selector: "p-message", inputs: ["severity", "text", "escape", "style", "styleClass", "closable", "icon", "closeIcon", "life", "showTransitionOptions", "hideTransitionOptions", "size", "variant", "motionOptions"], outputs: ["onClose"] }, { kind: "pipe", type: ErrorMessagePipe, name: "errorMessage" }] });
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.8", ngImport: i0, type: FieldValidation, decorators: [{
            type: Component,
            args: [{ selector: 'mt-field-validation', standalone: true, imports: [Message, ErrorMessagePipe], template: `
    @if (isInvalid(control())) {
      <p-message
        severity="error"
        variant="simple"
        size="small"
        [text]="control().errors | errorMessage"
      >
      </p-message>
    }
  `, host: {
                        class: 'mt-field-validation',
                        // Reserve one line of space for fields that can produce an error so the
                        // message appears/disappears without shifting the field height (and the
                        // rest of the form). Fields with no validators stay compact.
                        '[class.mt-field-validation--reserved]': 'shouldReserveSpace()',
                    }, styles: [".mt-field-validation{display:none}.mt-field-validation--reserved{display:block;min-height:1.25rem}\n"] }]
        }], propDecorators: { control: [{ type: i0.Input, args: [{ isSignal: true, alias: "control", required: false }] }], touched: [{ type: i0.Input, args: [{ isSignal: true, alias: "touched", required: false }] }] } });

const characterLimitValidator = (maxLength) => (control) => {
    const value = control.value;
    if (value === null || value === undefined) {
        return null;
    }
    const length = String(value).length;
    return length > maxLength
        ? {
            characterLimit: {
                requiredLength: maxLength,
                actualLength: length,
            },
        }
        : null;
};

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

export { FieldValidation, characterLimitValidator };
//# sourceMappingURL=masterteam-components-field-validation.mjs.map
