const { test, expect } = require('@playwright/test');

const FAKE_TOKEN = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjk5OTk5OTk5OTksIm5hbWUiOiJUZXN0IFVzZXIifQ.signature';

async function setupAuth(page) {
  await page.goto('/pos/login');
  await page.evaluate((token) => {
    localStorage.setItem('pos_token', token);
    localStorage.setItem('pos_tenant_id', '11');
  }, FAKE_TOKEN);
}

async function mockCatalogAPIs(page) {
  await page.route('/pos/api/catalog/brands?mode=local', async (route) => {
    await route.fulfill({
      status: 200,
      contentType: 'application/json',
      body: JSON.stringify({
        data: [
          { id_brand: 1, name_brand: 'Toyota' },
          { id_brand: 2, name_brand: 'Nissan' },
        ],
      }),
    });
  });

  await page.route(/\/pos\/api\/catalog\/search\?q=.*&limit=20/, async (route) => {
    await route.fulfill({
      status: 200,
      contentType: 'application/json',
      body: JSON.stringify({
        data: [
          {
            id_part: 1,
            oem_part_number: 'ABC-123',
            name: 'Filtro de aceite',
            vehicle_info: 'Toyota Corolla 2020',
            local_stock: 5,
          },
        ],
      }),
    });
  });
}

test.describe('Nexus POS — Catalog', () => {
  test('catalog page loads with brand grid', async ({ page }) => {
    await setupAuth(page);
    await mockCatalogAPIs(page);
    await page.goto('/pos/catalog');

    await expect(page).toHaveTitle(/Catalogo|Catálogo/i);
    await expect(page.locator('#navGrid')).toBeVisible({ timeout: 5000 });
    // Wait for brands to render
    await page.waitForSelector('.nav-card', { timeout: 5000 });
    const cards = page.locator('.nav-card');
    await expect(cards).toHaveCount(2);
  });

  test('search functionality works', async ({ page }) => {
    await setupAuth(page);
    await mockCatalogAPIs(page);
    await page.goto('/pos/catalog');

    const searchInput = page.locator('#searchInput');
    await expect(searchInput).toBeVisible();
    await searchInput.fill('filtro');
    await searchInput.press('Enter');

    // Assert search dropdown becomes visible with results
    await expect(page.locator('#searchDropdown')).toHaveClass(/is-visible/, { timeout: 5000 });
    await expect(page.locator('.search-result-item')).toBeVisible();
  });
});
