import assert from 'node:assert/strict';
import fs from 'node:fs/promises';
import path from 'node:path';
import test from 'node:test';

const root = path.resolve(import.meta.dirname, '..');

async function read(relativePath) {
  return fs.readFile(path.join(root, relativePath), 'utf8');
}

test('start page keeps nearby recommendations and the complete route list', async () => {
  const html = await read('public/index.html');
  const app = await read('public/js/app.js');

  assert.match(html, /id="nearby-route-list"/);
  assert.match(html, /id="all-route-list"/);
  assert.match(html, /id="route-search"/);
  assert.match(app, /renderRouteItems\('#nearby-route-list'/);
  assert.match(app, /renderRouteItems\(\s*'#all-route-list'/);
  assert.doesNotMatch(app, /state\.routes\s*=\s*state\.routes[\s\S]*?\.filter\(route => route\.proximityM/);
});

test('route selection renders independently from geolocation and restores after mobile page resume', async () => {
  const html = await read('public/index.html');
  const app = await read('public/js/app.js');
  const loader = await read('public/js/bootstrap-loader.js');
  const css = await read('public/css/app.css');
  const server = await read('server.js');
  const api = await read('src/routes/api.js');

  assert.match(html, /vendor\/jquery-ui\/jquery-ui-1\.14\.2\.min\.css\?v=0\.12\.14/);
  assert.match(html, /css\/app\.css\?v=0\.12\.14/);
  assert.match(html, /id="all-routes-summary"[^>]*>Routen werden geladen/);
  assert.doesNotMatch(loader, /loadStyle\(/);
  assert.doesNotMatch(css, /:has\(/);
  assert.match(html, /<header class="has-back-button">/);

  const firstRender = app.indexOf('renderRoutes();', app.indexOf('async initialize(context)'));
  const locationStart = app.indexOf('await initializeLocation(context);', app.indexOf('async initialize(context)'));
  assert.ok(firstRender >= 0 && locationStart > firstRender, 'Routen müssen vor der Standortabfrage gerendert werden.');
  assert.match(app, /globalThis\.addEventListener\('pageshow', restoreRouteLists\)/);
  assert.match(app, /document\.visibilityState === 'visible'/);
  assert.match(app, /Array\.isArray\(response\?\.routes\)/);
  assert.match(app, /throw new TypeError\('Die Routen-API hat keine gültige Routenliste geliefert\.'\)/);
  assert.match(app, /route\?\.id != null && route\?\.name != null/);
  assert.doesNotMatch(app, /route && route\.id/);
  assert.match(server, /no-cache, no-store, must-revalidate/);
  assert.match(api, /api\.use\(\(req, res, next\)/);
});
