// ============================================================
// LEARNING HUB — search, category pills, feed rendering.
// Quiz flow is gated by having quiz content; just verify the UI
// scaffolding works without requiring a specific topic to exist.
// ============================================================

const { test, expect, E2E_BASE } = require('../fixtures');

async function openTab(page) {
  await page.goto(E2E_BASE + '/');
  await page.waitForSelector('button.tab-btn', { timeout: 15000 });
  const vp = page.viewportSize();
  if (vp && vp.width <= 768) {
    await page.click('#btn-menu-toggle').catch(() => {});
  }
  await page.click('button.tab-btn[data-tab="learning"]');
  await page.waitForFunction(() => {
    const el = document.getElementById('learning-tab');
    return el && el.classList.contains('active') && el.innerHTML.trim().length > 100;
  }, { timeout: 15000 });
}

test.describe('Learning Hub — navigation + search', () => {

  test('search input + categories + feed all render', async ({ authedPage: _, page }) => {
    await openTab(page);
    await expect(page.locator('#lh-search')).toBeVisible();
    await expect(page.locator('#lh-categories')).toBeVisible();
    await expect(page.locator('#lh-feed')).toBeVisible();
  });

  test('typing in search filters the feed (even if zero matches)', async ({ authedPage: _, page }) => {
    await openTab(page);
    // Wait for feed to render some content or be flagged as empty
    await expect.poll(async () =>
      (await page.locator('#lh-feed').innerText()).trim().length,
    { timeout: 10000 }).toBeGreaterThan(0);
    const initialHtml = await page.locator('#lh-feed').innerHTML();

    // Type a very specific string that likely won't match any topic
    await page.fill('#lh-search', 'xyzzy-unlikely-topic-name');
    // Feed should update — either to empty state or different filtered list
    await expect.poll(async () =>
      (await page.locator('#lh-feed').innerHTML()) !== initialHtml,
    { timeout: 3000 }).toBe(true);
  });

  test('clicking a category pill (if present) does not crash the UI', async ({ authedPage: _, page }) => {
    await openTab(page);
    const pills = page.locator('#lh-categories button, #lh-categories .category-pill');
    const count = await pills.count();
    test.skip(count === 0, 'No category pills rendered — nothing to test');
    await pills.first().click();
    // Feed must still be visible and have some content after filtering
    await expect(page.locator('#lh-feed')).toBeVisible();
  });
});
