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('Message');
  readonly placeholder = input('Write your message...');
  readonly hint = input('Keep it concise and include the details someone needs to respond.');
  readonly error = input('');
  readonly required = input(false);
  readonly disabled = input(false);
  readonly readOnly = input(false);
  readonly rows = input(4);
  readonly maxLength = input<number | null>(280);
  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 counterId = computed(() => `${this.instanceId}-counter`);

  protected readonly remainingCharacters = computed(() => {
    const maxLength = this.maxLength();
    return maxLength === null ? null : maxLength - this.value().length;
  });

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

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

    if (this.maxLength() !== null) {
      ids.push(this.counterId());
    }

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

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

  protected updateValue(event: Event): void {
    this.value.set((event.target as HTMLTextAreaElement).value);
  }
}
