import * as i0 from '@angular/core';
import { Component, Input, NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { Subject, takeUntil } from 'rxjs';

/**
 * @description Componente que exibe as mensagens de erro de validação associadas a um controle de formulário.
 * Observa as alterações de estado do controle e renderiza as mensagens mapeadas em `errorMessages`.
 * Compativel com `AbstractControl` do Reactive Forms e `NgModel` do Template-Driven Forms.
 *
 * @example
 * ```html
 * <s-control-errors
 *   [control]="form.get('email')"
 *   [errorMessages]="{ required: 'E-mail obrigatório', email: 'E-mail inválido' }"
 * />
 * ```
 *
 * @category Feedback
 */
class ControlErrorsComponent {
    static nextIdSeed = 0;
    static RANDOM_ID_END_INDEX = 9;
    static BASE_36 = 36;
    static _nextId = ControlErrorsComponent.nextIdSeed;
    static getNextId() {
        return this._nextId++;
    }
    /**
     * @description Identificador único do componente. Gerado automaticamente se não informado.
     * Usado para associação acessível com o campo correspondente.
     */
    id = `s-control-errors-${ControlErrorsComponent.getNextId()}`;
    /**
     * @description Controle do formulário cujos erros serão exibidos.
     * Aceita `AbstractControl` (Reactive Forms) ou `NgModel` (Template-Driven Forms). Campo obrigatório.
     */
    control;
    /**
     * @description Mapa de chaves de erro para mensagens de texto exibidas ao usuário.
     * Cada chave corresponde a um erro que pode estar presente em `control.errors`.
     *
     * @example
     * ```ts
     * { required: 'Campo obrigatório', minlength: 'Mínimo 8 caracteres' }
     * ```
     */
    errorMessages = {};
    /**
     * @description Referência ao formulário pai. Utilizado em cenários de validação customizada
     * que dependem do estado geral do formulário.
     */
    form;
    errorMessagesList = [];
    onDestroy$ = new Subject();
    ngOnChanges(changes) {
        if (changes['control'] && changes['control'].firstChange) {
            this.control?.valueChanges?.pipe(takeUntil(this.onDestroy$)).subscribe(() => this.setErrorMessagesList());
        }
    }
    setErrorMessagesList() {
        if (!this.control?.dirty) {
            this.errorMessagesList = [];
        }
        this.errorMessagesList = Object.keys(this.control.errors || {}).map((error) => ({
            id: `${Date.now()}-${Math.random().toString(ControlErrorsComponent.BASE_36).substring(2, ControlErrorsComponent.RANDOM_ID_END_INDEX)}`,
            message: this.errorMessages?.[error],
        }));
    }
    ngOnDestroy() {
        this.onDestroy$.next();
        this.onDestroy$.complete();
    }
    static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "18.2.14", ngImport: i0, type: ControlErrorsComponent, deps: [], target: i0.ɵɵFactoryTarget.Component });
    static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "18.2.14", type: ControlErrorsComponent, selector: "s-control-errors", inputs: { id: "id", control: "control", errorMessages: "errorMessages", form: "form" }, usesOnChanges: true, ngImport: i0, template: "@for (errorMessage of errorMessagesList; track errorMessage.id) {\n    @if (errorMessage) {\n        <div \n            class=\"error-message\" \n            role=\"alert\" \n            aria-live=\"assertive\" \n            aria-atomic=\"true\"\n        >\n            {{ errorMessage.message }}\n        </div>\n    }\n}\n", styles: [".error-message{color:#c13018;margin-top:5px;font-size:12px}\n"] });
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "18.2.14", ngImport: i0, type: ControlErrorsComponent, decorators: [{
            type: Component,
            args: [{ selector: 's-control-errors', template: "@for (errorMessage of errorMessagesList; track errorMessage.id) {\n    @if (errorMessage) {\n        <div \n            class=\"error-message\" \n            role=\"alert\" \n            aria-live=\"assertive\" \n            aria-atomic=\"true\"\n        >\n            {{ errorMessage.message }}\n        </div>\n    }\n}\n", styles: [".error-message{color:#c13018;margin-top:5px;font-size:12px}\n"] }]
        }], propDecorators: { id: [{
                type: Input
            }], control: [{
                type: Input,
                args: [{ required: true }]
            }], errorMessages: [{
                type: Input
            }], form: [{
                type: Input
            }] } });

class ControlErrorsModule {
    static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "18.2.14", ngImport: i0, type: ControlErrorsModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule });
    static ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "18.2.14", ngImport: i0, type: ControlErrorsModule, declarations: [ControlErrorsComponent], imports: [CommonModule, FormsModule, ReactiveFormsModule], exports: [ControlErrorsComponent] });
    static ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "18.2.14", ngImport: i0, type: ControlErrorsModule, imports: [CommonModule, FormsModule, ReactiveFormsModule] });
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "18.2.14", ngImport: i0, type: ControlErrorsModule, decorators: [{
            type: NgModule,
            args: [{
                    imports: [CommonModule, FormsModule, ReactiveFormsModule],
                    declarations: [ControlErrorsComponent],
                    exports: [ControlErrorsComponent],
                }]
        }] });

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

export { ControlErrorsComponent, ControlErrorsModule };
//# sourceMappingURL=seniorsistemas-angular-components-control-errors.mjs.map
