import { ChangeDetectionStrategy, Component, computed, input } from '@angular/core';

let nextFormFieldId = 0;

/**
 * Injected by form controls (e.g. app-input) nested inside app-form-field so they can
 * self-apply `id` and `aria-describedby` without the parent template wiring them manually.
 */
export abstract class FormFieldContext {
  abstract readonly fieldId: string;
  abstract readonly describedBy: () => string | null;
}

@Component({
  selector: 'app-form-field',
  standalone: true,
  templateUrl: './form-field.component.html',
  styleUrl: './form-field.component.scss',
  changeDetection: ChangeDetectionStrategy.OnPush,
  providers: [{ provide: FormFieldContext, useExisting: FormFieldComponent }]
})
export class FormFieldComponent implements FormFieldContext {
  readonly label = input<string | null>(null);
  readonly hint = input<string | null>(null);
  readonly error = input<string | null>(null);
  readonly required = input(false);

  readonly fieldId = `app-form-field-${++nextFormFieldId}`;
  protected readonly hintId = `${this.fieldId}-hint`;
  protected readonly errorId = `${this.fieldId}-error`;

  readonly describedBy = computed(() => this.error() ? this.errorId : (this.hint() ? this.hintId : null));
}
