import { BaseComponent } from '@/shared/base/BaseComponent';
import { getAttribute } from '@/shared/utils/locator-utils';
import { Locator } from '@playwright/test';

export class SingleAutocomplete extends BaseComponent {
  private readonly input = this.host.locator('input');
  private readonly clearButton = this.host.getByRole('button');

  async fill(value: string): Promise<void> {
    if (await this.clearButton.isVisible()) {
      await this.clearButton.click();
    }

    await this.input.fill(value);
    await (await this.getMenuOption(value)).click({ force: true }); // TODO: force option used until FE reka ui combobox bug is resolved
  }

  private async getMenuOption(name: string): Promise<Locator> {
    return (await this.getMenu()).locator(`div[role=option]:has(span:has-text("${name}"))`);
  }

  private async getMenu(): Promise<Locator> {
    const id = await getAttribute(this.input, 'aria-controls');
    return this.host.page().locator(`div[id=${id}]`);
  }
}
