import { CommonModule } from '@angular/common';
import { APP_TRANSLATE_IMPORTS } from '../../../../../../core/i18n';
import {
  Component,
  ElementRef,
  effect,
  inject,
  input,
  output
} from '@angular/core';
import type { PluginApiSlashCommandOption } from '../../../../../plugins';
import type { SlashCommandEntry } from '../../../../../plugins';

@Component({
  selector: 'app-chat-slash-command-menu',
  standalone: true,
  imports: [CommonModule, ...APP_TRANSLATE_IMPORTS],
  templateUrl: './chat-slash-command-menu.component.html',
  host: {
    class: 'block'
  }
})
export class ChatSlashCommandMenuComponent {
  readonly commands = input<SlashCommandEntry[]>([]);
  readonly activeIndex = input<number>(0);

  readonly commandPicked = output<SlashCommandEntry>();
  readonly activeIndexChanged = output<number>();

  private readonly host = inject<ElementRef<HTMLElement>>(ElementRef);

  constructor() {
    effect(() => {
      // Re-run whenever the active row changes so it stays visible while
      // navigating the list with the keyboard.
      this.activeIndex();
      queueMicrotask(() => this.scrollActiveIntoView());
    });
  }

  badgeLabel(entry: SlashCommandEntry): string {
    return entry.contribution.icon?.trim() || entry.contribution.name.charAt(0).toUpperCase() || '/';
  }

  usage(entry: SlashCommandEntry): string {
    return (entry.contribution.options ?? []).map((option) => this.formatOption(option)).join(' ');
  }

  pick(entry: SlashCommandEntry): void {
    this.commandPicked.emit(entry);
  }

  hover(index: number): void {
    this.activeIndexChanged.emit(index);
  }

  private formatOption(option: PluginApiSlashCommandOption): string {
    return option.required ? `<${option.name}>` : `[${option.name}]`;
  }

  private scrollActiveIntoView(): void {
    const active = this.host.nativeElement.querySelector<HTMLElement>('[data-slash-active="true"]');

    active?.scrollIntoView({ block: 'nearest' });
  }
}
