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

test('all internal links resolve', async ({ page }) => {
  await page.goto('/');
  const links = await page.locator('a[href]').all();
  const broken: string[] = [];
  for (const link of links) {
    const href = await link.getAttribute('href');
    if (!href) continue;
    if (href.startsWith('#') || href.startsWith('mailto:') || href.startsWith('tel:')) continue;
    if (href.startsWith('http') && !href.includes('localhost')) continue;
    if (href.startsWith('/') || !href.startsWith('http')) {
      try {
        const url = href.startsWith('/') ? `http://localhost:4321${href}` : href;
        const res = await page.request.get(url);
        if (!res.ok()) broken.push(`${href} → ${res.status()}`);
      } catch {
        broken.push(`${href} → fetch failed`);
      }
    }
  }
  expect(broken).toEqual([]);
});

test('all hash anchors point to existing IDs', async ({ page }) => {
  await page.goto('/');
  const anchors = await page.locator('a[href^="#"]').all();
  const missing: string[] = [];
  for (const a of anchors) {
    const href = await a.getAttribute('href');
    if (!href || href === '#') continue;
    const id = href.slice(1);
    const exists = await page.locator(`[id="${id}"]`).count();
    if (exists === 0) missing.push(`${href} — no element with id="${id}"`);
  }
  expect(missing).toEqual([]);
});
