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

test.beforeEach(async ({ page }) => {
  await page.goto('/');
  await page.evaluate(async () => {
    indexedDB.deleteDatabase('ttrpg-manager');
    localStorage.clear();
  });
  await page.reload();
});

test('compendium: browse 5e categories, switch to PF2e, cross-link a spell', async ({ page }) => {
  // Set up a 5e campaign + character to receive a spell
  await page.getByRole('button', { name: '+ New campaign' }).first().click();
  await page.locator('input[data-autofocus]').fill('Saltmarsh');
  await page.getByRole('button', { name: 'Create' }).click();
  await page.getByRole('link', { name: 'Characters' }).click();
  await createCharacter(page, 'Wizard Wendy');

  // Compendium → 5e categories exist (Feats is a new one)
  await page.getByRole('link', { name: 'Compendium' }).click();
  await expect(page.getByRole('button', { name: 'Feats' })).toBeVisible();

  // Classes category (Open5e data) lists classes with detail
  await page.getByRole('button', { name: 'Classes', exact: true }).click();
  await page.getByRole('button', { name: /^Wizard/ }).first().click();
  await expect(page.getByText('Hit die')).toBeVisible();
  await expect(page.getByText(/School of Evocation/)).toBeVisible();
  await page.getByRole('button', { name: 'Conditions' }).click();
  await expect(page.getByText(/results/)).toBeVisible();

  // Spells → add one to the character
  await page.getByRole('button', { name: 'Spells', exact: true }).click();
  await page.getByPlaceholder(/Search spells/i).fill('fireball');
  await page.getByRole('button', { name: /Fireball/ }).first().click();
  await page.getByLabel('Add spell to character').selectOption({ label: 'Wizard Wendy' });
  await expect(page.getByText(/Added to Wizard Wendy/)).toBeVisible();

  // Switch to PF2e — bestiary loads from the static dataset
  await page.getByRole('button', { name: 'Pathfinder 2e' }).click();
  await page.getByRole('button', { name: 'Bestiary' }).click();
  await expect.poll(async () => {
    const t = (await page.getByText(/results/).textContent()) ?? '';
    return parseInt(t.replace(/\D/g, ''), 10) || 0;
  }, { timeout: 15000 }).toBeGreaterThan(0);

  // Verify the spell landed on the character sheet
  await page.getByRole('link', { name: 'Characters' }).click();
  await page.getByRole('link', { name: /Wizard Wendy/ }).click();
  await expect(page.getByText('Fireball')).toBeVisible();
});
