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

interface <%= classify(name) %>Option {
  id: number;
  label: string;
}

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 options: <%= classify(name) %>Option[] = [
    { id: 1, label: 'Primeira opção' },
    { id: 2, label: 'Segunda opção' },
  ];

  protected readonly activeIndex = signal(0);

  readonly label = input('Escolha uma opção');

  protected readonly activeDescendantId = computed(
    () => `${this.instanceId}-option-${this.options[this.activeIndex()].id}`
  );

  protected select(index: number): void {
    this.activeIndex.set(index);
  }

  // Up/Down move the active option; Home/End jump to first/last (APG listbox, active-descendant model).
  protected navigateList(event: KeyboardEvent): void {
    switch (event.key) {
      case 'ArrowDown':
        event.preventDefault();
        this.activeIndex.update((index) => Math.min(index + 1, this.options.length - 1));
        break;
      case 'ArrowUp':
        event.preventDefault();
        this.activeIndex.update((index) => Math.max(index - 1, 0));
        break;
      case 'Home':
        event.preventDefault();
        this.activeIndex.set(0);
        break;
      case 'End':
        event.preventDefault();
        this.activeIndex.set(this.options.length - 1);
        break;
    }
  }
}
