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

let nextId = 0;

@Component({
  selector: '<%= selector %>',
  imports: [],
  templateUrl: './<%= dasherize(name) %>.html',
  styleUrl: './<%= dasherize(name) %>.css',
})
export class <%= classify(name) %> {
  protected readonly instanceId = `<%= dasherize(name) %>-${nextId++}`;

  readonly label = input('Código de verificação');
  readonly length = input(6);
  readonly hint = input('Informe o código enviado para o seu dispositivo confiável.');
  readonly error = input('');
  readonly required = input(true);
  readonly disabled = input(false);
  readonly readOnly = input(false);
  readonly numericOnly = input(true);
  readonly value = model('');

  protected readonly controlId = computed(() => `${this.instanceId}-control`);
  protected readonly hintId = computed(() => `${this.instanceId}-hint`);
  protected readonly errorId = computed(() => `${this.instanceId}-error`);
  protected readonly codePattern = computed(() => this.numericOnly() ? '[0-9]*' : null);

  protected readonly describedBy = computed(() => {
    const ids = [];

    if (this.hint()) {
      ids.push(this.hintId());
    }

    if (this.error()) {
      ids.push(this.errorId());
    }

    return ids.length > 0 ? ids.join(' ') : null;
  });

  protected updateValue(event: Event): void {
    const rawValue = (event.target as HTMLInputElement).value;
    const value = this.numericOnly() ? rawValue.replace(/\D/g, '') : rawValue.trim();
    this.value.set(value.slice(0, this.length()));
  }
}
