import type { Drupal } from '@drupal/playwright';
import { expect, type Locator, type Page } from '@playwright/test';

import type { Canvas } from './Canvas.js';

export class Conductor {
  readonly page: Page;
  readonly drupal: Drupal;
  readonly canvas: Canvas;

  constructor({ drupal, canvas }: { drupal: Drupal; canvas: Canvas }) {
    this.drupal = drupal;
    this.canvas = canvas;
    this.page = drupal.page;
  }

  async open(): Promise<Locator> {
    await this.drupal.login({ username: 'editor', password: 'editor' });
    await this.canvas.openCanvas(await this.canvas.createCanvas());
    await this.page
      .locator('[data-testid="canvas-side-menu"]')
      .getByRole('button', { name: 'Extensions' })
      .click();
    await this.page
      .locator('[data-testid="canvas-primary-panel"]')
      .getByRole('button', { name: 'Writing Assistant' })
      .click();
    await expect(this.page.getByRole('heading', { name: 'Writing Assistant' })).toBeVisible();
    await expect(
      this.page
        .locator('#extensionPortalContainer')
        .getByRole('tablist')
        .and(this.page.locator('ul')),
    ).toBeVisible();
    return this.page.locator('#extensionPortalContainer');
  }

  async initializeKeywordsAndCompetitorUrls(app: Locator): Promise<void> {
    await expect(app.getByRole('button', { name: 'Evaluate' })).toBeDisabled();
    await app.getByRole('textbox').fill('jawn');
    await app.getByRole('textbox').press('Enter');
    await expect(app.getByRole('button', { name: 'Evaluate' })).toBeEnabled();
    await expect(app.getByRole('tab', { name: 'Competitors' })).toBeVisible();
    await app.getByRole('tab', { name: 'Competitors' }).click();
    const competitorsList = app.locator('.competitors__list');
    await expect(competitorsList.locator('li').first()).toBeVisible();
    const itemCount = await app.locator('li').count();
    expect(itemCount).toBeGreaterThan(0);
  }
}
