// Navigation tests for sx-docs
// Verifies navigation works correctly with the OCaml sx-host.

const { test, expect } = require('playwright/test');
const { BASE_URL, waitForSxReady, loadPage, trackErrors } = require('./helpers');

test.describe('Page Navigation', () => {
  let t;
  test.beforeEach(({ page }) => { t = trackErrors(page); });
  test.afterEach(() => { expect(t.errors()).toEqual([]); });

  test('clicking nav button navigates to new page', async ({ page }) => {
    await loadPage(page, '(geography)');

    // Click "Reactive Islands" nav link
    await page.click('a[href*="geography.(reactive)"]:not([href*="runtime"])');
    await expect(page).toHaveURL(/reactive/, { timeout: 5000 });

    // Page should show Reactive Islands content
    const body = await page.textContent('body');
    expect(body).toContain('Reactive Islands');
  });

  test('clicking header logo navigates home', async ({ page }) => {
    await loadPage(page, '(geography)');

    // Click the logo in the header island
    await page.click('[data-sx-island="layouts/header"] a[href="/sx/"]');
    await expect(page).toHaveURL(/\/sx\/?$/, { timeout: 5000 });
  });

  test('back button works after navigation', async ({ page }) => {
    await loadPage(page, '(geography)');

    // Navigate to Reactive Islands
    await page.click('a[href*="geography.(reactive)"]:not([href*="runtime"])');
    await expect(page).toHaveURL(/reactive/, { timeout: 5000 });

    // Go back
    await page.goBack();
    await expect(page).toHaveURL(/geography/, { timeout: 5000 });
    await expect(page).not.toHaveURL(/reactive/);

    // Geography heading should be visible
    const heading = await page.locator('h1, h2').first();
    await expect(heading).toContainText('Geography', { timeout: 5000 });
  });

  test('no console errors on page load', async ({ page }) => {
    await loadPage(page, '(geography)');
    // afterEach handles assertion
  });

  test('copyright updates path after SX navigation', async ({ page }) => {
    await loadPage(page, '(geography)');

    // Before: copyright shows geography path
    const before = await page.evaluate(() =>
      document.querySelector('[data-sx-lake="copyright"]')?.textContent);
    expect(before).toContain('/sx/(geography)');

    // Navigate via SX to Reactive Islands
    await page.click('a[sx-get*="(geography.(reactive))"]:not([href*="runtime"])');
    await expect(page).toHaveURL(/reactive/, { timeout: 5000 });
    await page.waitForTimeout(1000);

    // After: copyright must show the NEW path, not the old one
    const after = await page.evaluate(() =>
      document.querySelector('[data-sx-lake="copyright"]')?.textContent);
    expect(after).toContain('(reactive)');
  });

  test('back button reverses nav and copyright to previous page', async ({ page }) => {
    await loadPage(page, '');

    // Home page: nav shows top-level sections, copyright shows /sx/
    await expect(page.locator('#sx-nav')).toContainText('Geography');
    await expect(page.locator('#sx-nav')).toContainText('Language');
    const homeCopyright = await page.evaluate(() =>
      document.querySelector('[data-sx-lake="copyright"]')?.textContent);
    expect(homeCopyright).toContain('/sx/');
    expect(homeCopyright).not.toContain('(language)');

    // Navigate to Language
    await page.click('a[sx-get*="(language)"]');
    await expect(page).toHaveURL(/language/, { timeout: 5000 });
    await page.waitForTimeout(1000);

    // Nav should show Language sub-pages
    await expect(page.locator('#sx-nav')).toContainText('Docs');
    const langCopyright = await page.evaluate(() =>
      document.querySelector('[data-sx-lake="copyright"]')?.textContent);
    expect(langCopyright).toContain('(language)');

    // Go back
    await page.goBack();
    await expect(page).toHaveURL(/\/sx\/?$/, { timeout: 5000 });
    await page.waitForTimeout(2000);

    // Nav must revert to home top-level sections
    await expect(page.locator('#sx-nav')).toContainText('Geography');
    await expect(page.locator('#sx-nav')).toContainText('Language');
    // Must NOT still show Language sub-pages
    await expect(page.locator('#sx-nav')).not.toContainText('Docs');

    // Copyright must revert to /sx/
    const backCopyright = await page.evaluate(() =>
      document.querySelector('[data-sx-lake="copyright"]')?.textContent);
    expect(backCopyright).toContain('/sx/');
    expect(backCopyright).not.toContain('(language)');
  });

  test('stepper persists index across navigation', async ({ page }) => {
    await loadPage(page, '');

    // Get the initial stepper index
    const getIndex = () => page.evaluate(() => {
      const el = document.querySelector('[data-sx-island="home/stepper"]');
      const m = el && el.textContent.match(/(\d+)\s*\/\s*\d+/);
      return m ? parseInt(m[1]) : null;
    });

    const initial = await getIndex();
    expect(initial).not.toBeNull();

    // Step back first (initial may be at max), then forward
    await page.evaluate(() => {
      const btns = document.querySelectorAll('[data-sx-island="home/stepper"] button');
      if (btns.length >= 2) btns[0].click();  // back button
    });
    await page.waitForTimeout(500);

    const backed = await getIndex();
    expect(backed).toBe(initial - 1);

    // Now advance
    await page.evaluate(() => {
      const btns = document.querySelectorAll('[data-sx-island="home/stepper"] button');
      if (btns.length >= 2) btns[1].click();  // next button
    });
    await page.waitForTimeout(500);

    const advanced = await getIndex();
    expect(advanced).toBe(backed + 1);

    // Navigate away
    await page.click('a[sx-get*="(geography)"]');
    await expect(page).toHaveURL(/geography/, { timeout: 5000 });

    // Navigate back home
    await page.evaluate(() => {
      const link = document.querySelector('a[sx-get*="/sx/"]');
      if (link) link.click();
    });
    await expect(page).toHaveURL(/\/sx\/?$/, { timeout: 5000 });

    // Stepper should still show the advanced index
    const afterNav = await getIndex();
    expect(afterNav).toBe(advanced);
  });

  test('sx-get link fetches SX not HTML and preserves layout', async ({ page }) => {
    await loadPage(page, '');

    // Mark page so we can detect full reload vs SPA nav
    await page.evaluate(() => window.__spa_marker = true);

    // Click a nav link (Geography)
    await page.click('a[sx-get*="(geography)"]');
    await expect(page).toHaveURL(/geography/, { timeout: 5000 });

    // Must be SPA navigation — marker survives (full reload clears it)
    const marker = await page.evaluate(() => window.__spa_marker);
    expect(marker).toBe(true);

    // After SPA nav, key layout elements should still exist (not destroyed by swap)
    const layout = await page.evaluate(() => ({
      hasNav: !!document.querySelector('#sx-nav'),
      hasPanel: !!document.querySelector('#main-panel'),
      navCount: document.querySelectorAll('#sx-nav').length,
      panelCount: document.querySelectorAll('#main-panel').length,
    }));
    expect(layout.hasNav).toBe(true);
    expect(layout.hasPanel).toBe(true);
    expect(layout.navCount).toBe(1);
    expect(layout.panelCount).toBe(1);
  });

  test('SPA nav: single fetch, no duplicate elements', async ({ page }) => {
    await loadPage(page, '(geography)');

    // Track network requests during SPA navigation
    const fetches = [];
    page.on('request', req => {
      if (req.url().includes('/sx/') && !req.url().includes('/static/'))
        fetches.push(req.url());
    });

    // SPA navigate
    await page.click('a[sx-get*="(geography.(reactive))"]:not([href*="runtime"])');
    await expect(page).toHaveURL(/reactive/, { timeout: 5000 });
    await page.waitForTimeout(1000);

    // Should be exactly 1 fetch, not 2 (double-fetch bug)
    expect(fetches.length).toBe(1);

    // No duplicate nav or main-panel elements (sign of nested layout swap)
    const counts = await page.evaluate(() => ({
      navCount: document.querySelectorAll('#sx-nav').length,
      panelCount: document.querySelectorAll('#main-panel').length,
    }));
    expect(counts.navCount).toBe(1);
    expect(counts.panelCount).toBe(1);
  });

  test('header island renders with SSR', async ({ page }) => {
    await loadPage(page, '(geography)');

    // Header should be visible
    const header = page.locator('[data-sx-island="layouts/header"]');
    await expect(header).toBeVisible();

    // Should contain the logo
    await expect(header).toContainText('sx');

    // Should contain copyright
    await expect(header).toContainText('Giles Bradshaw');
  });

  // Snapshot #sx-root structure, skipping reactive internals
  const snapshotJS = `(function() {
    function snap(el) {
      if (el.nodeType === 3) { const t = el.textContent.trim(); return t ? { t } : null; }
      if (el.nodeType !== 1) return null;
      const tag = el.tagName.toLowerCase();
      // Skip style/script elements — they differ between SSR and SPA (hoisting)
      if (tag === 'style' || tag === 'script') return null;
      const n = { tag };
      if (el.id) n.id = el.id;
      const cls = Array.from(el.classList).sort().join(' ');
      if (cls) n.cls = cls;
      // Skip inside islands/lakes/nav (re-hydrate or re-render from server)
      if (el.hasAttribute('data-sx-island') || el.hasAttribute('data-sx-lake')
          || el.hasAttribute('data-sx-reactive') || el.id === 'sx-nav') {
        n.island = el.getAttribute('data-sx-island') || el.getAttribute('data-sx-lake') || el.id || 'reactive';
        return n;
      }
      const ch = [];
      for (const c of el.childNodes) { const s = snap(c); if (s) ch.push(s); }
      if (ch.length) n.ch = ch;
      return n;
    }
    const root = document.querySelector('#main-panel') || document.querySelector('#sx-root');
    return root ? snap(root) : null;
  })()`;

  function diffDOM(spaStr, freshStr, label) {
    if (spaStr === freshStr) return;
    const spaLines = spaStr.split('\n');
    const freshLines = freshStr.split('\n');
    const diffs = [];
    for (let i = 0; i < Math.max(spaLines.length, freshLines.length); i++) {
      if (spaLines[i] !== freshLines[i]) {
        diffs.push(`  Line ${i+1}:`);
        diffs.push(`    SPA:   ${(spaLines[i]||'(missing)').trim()}`);
        diffs.push(`    Fresh: ${(freshLines[i]||'(missing)').trim()}`);
        if (diffs.length > 15) { diffs.push('  ...'); break; }
      }
    }
    expect(spaStr === freshStr, `${label}\n${diffs.join('\n')}`).toBe(true);
  }

  const navRoutes = [
    { from: '(geography)', click: 'a[sx-get*="(geography.(reactive))"]:not([href*="runtime"])', url: /reactive/ },
    { from: '', click: 'a[sx-get*="(language)"]', url: /language/ },
    { from: '', click: 'a[sx-get*="(geography)"]', url: /geography/ },
  ];

  for (const { from, click, url } of navRoutes) {
    test(`SPA nav DOM matches fresh: ${from || '/'} → ${click.match(/\(([^)]+)\)/)?.[0] || '?'}`, async ({ page }) => {
      await loadPage(page, from);
      await page.click(click);
      await expect(page).toHaveURL(url, { timeout: 5000 });
      await page.waitForTimeout(1000);
      const spaDOM = await page.evaluate(snapshotJS);

      // Fresh load same URL
      await page.goto(page.url(), { waitUntil: 'domcontentloaded' });
      await waitForSxReady(page);
      const freshDOM = await page.evaluate(snapshotJS);

      diffDOM(
        JSON.stringify(spaDOM, null, 2),
        JSON.stringify(freshDOM, null, 2),
        `SPA from ${from || '/'} to ${page.url()}`
      );
    });
  }
});
