import { Component, computed, input, model, signal } 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++}`;
  protected readonly codeVisible = signal(false);

  readonly label = input('Senha da transação');
  readonly length = input(4);
  readonly hint = input('Informe seu código seguro de transação.');
  readonly error = input('');
  readonly required = input(true);
  readonly disabled = input(false);
  readonly readOnly = input(false);
  readonly numericOnly = input(true);
  readonly autocomplete = input('current-password');
  readonly showLabel = input('Mostrar código');
  readonly hideLabel = input('Ocultar código');
  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 inputType = computed(() => this.codeVisible() ? 'text' : 'password');
  protected readonly toggleLabel = computed(() => this.codeVisible() ? this.hideLabel() : this.showLabel());
  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;
    this.value.set(value.slice(0, this.length()));
  }

  protected toggleVisibility(): void {
    this.codeVisible.update((visible) => !visible);
  }
}
