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

test.describe('Search Functionality', () => {
  test.beforeEach(async ({ page }) => {
    await page.goto('/');
  });

  test('search input is accessible and functional', async ({ page }) => {
    // Find search input
    const searchInput = page.getByRole('combobox', { name: /search/i });
    await expect(searchInput).toBeVisible();

    // Type in search
    await searchInput.fill('synor1');

    // Should show suggestions dropdown
    const dropdown = page.locator('#search-listbox');
    await expect(dropdown).toBeVisible();

    // Should show address suggestion
    await expect(page.getByText(/address/i)).toBeVisible();
  });

  test('keyboard navigation in search dropdown', async ({ page }) => {
    const searchInput = page.getByRole('combobox', { name: /search/i });
    await searchInput.fill('12345');

    // Press arrow down to navigate
    await searchInput.press('ArrowDown');

    // Press Enter to select
    await searchInput.press('Enter');

    // Should navigate to search results
    await expect(page).toHaveURL(/\/search\?q=/);
  });

  test('clear search button works', async ({ page }) => {
    const searchInput = page.getByRole('combobox', { name: /search/i });
    await searchInput.fill('test query');

    // Find and click clear button
    const clearButton = page.getByRole('button', { name: /clear search/i });
    await clearButton.click();

    // Input should be empty
    await expect(searchInput).toHaveValue('');
  });

  test('escape key closes dropdown', async ({ page }) => {
    const searchInput = page.getByRole('combobox', { name: /search/i });
    await searchInput.fill('test');

    // Dropdown should be visible
    const dropdown = page.locator('#search-listbox');
    await expect(dropdown).toBeVisible();

    // Press escape
    await searchInput.press('Escape');

    // Dropdown should be hidden
    await expect(dropdown).not.toBeVisible();
  });
});
