import { test, expect } from '@playwright/test';

import { login, navigateTo, PORT_SLUG } from '../smoke/helpers';

test.describe('exhaustive: EOI generate dialog', () => {
  test.beforeEach(async ({ page }) => {
    await login(page, 'super_admin');
  });

  test('dialog opens with Documenso option pre-selected', async ({ page }) => {
    await navigateTo(page, '/interests');
    await page.waitForLoadState('networkidle');

    const firstRow = page.locator('tbody tr a, tbody tr button').first();
    if (!(await firstRow.isVisible({ timeout: 3000 }).catch(() => false))) {
      test.skip(true, 'no interests seeded');
      return;
    }
    await firstRow.click();
    await page.waitForURL(new RegExp(`/${PORT_SLUG}/interests/[^/]+`), { timeout: 10_000 });
    await page.waitForLoadState('networkidle');

    const docsTab = page.getByRole('tab', { name: /documents/i }).first();
    if (await docsTab.isVisible({ timeout: 3000 }).catch(() => false)) {
      await docsTab.click();
      await page.waitForLoadState('networkidle');
    }

    const generateBtn = page.getByRole('button', { name: /generate eoi/i }).first();
    if (!(await generateBtn.isVisible({ timeout: 3000 }).catch(() => false))) {
      test.skip(true, 'Generate EOI button not present on this interest');
      return;
    }
    await generateBtn.click();

    const dialog = page.getByRole('dialog');
    await expect(dialog).toBeVisible({ timeout: 5000 });

    // Template dropdown shows the Documenso option.
    const trigger = dialog.locator('[role="combobox"], button[id="eoi-template"]').first();
    if (await trigger.isVisible({ timeout: 3000 }).catch(() => false)) {
      await trigger.click();
      await expect(page.getByRole('option', { name: /documenso/i })).toBeVisible({
        timeout: 3000,
      });
      // Close the listbox without changing selection.
      await page.keyboard.press('Escape');
    }

    const cancel = dialog.getByRole('button', { name: /cancel|close/i }).first();
    await cancel.click();
    await expect(dialog).toBeHidden({ timeout: 5000 });
  });
});
