import { expect, test } from '@playwright/test';
import { readFileSync } from 'node:fs';
import { MAP_KEYS } from '../src/game/data';

const doors = MAP_KEYS.flatMap((source) => {
  const map = JSON.parse(readFileSync(`public/maps/${source}.json`, 'utf8')) as {
    layers: Array<{ name: string; objects?: Array<{ type: string; properties?: Array<{ name: string; value: string }> }> }>;
  };
  return (map.layers.find((layer) => layer.name === 'objects')?.objects ?? [])
    .filter((object) => object.type === 'door')
    .map((object) => ({ source, target: object.properties?.find((property) => property.name === 'target')?.value ?? '' }));
});

test('every authored door reaches its paired target scene', async ({ page }) => {
  await page.goto('/');
  await page.locator('#player-name').press('Enter');
  await expect.poll(() => page.evaluate(() => window.__HONEY_GAME__.scene.isActive('HouseScene'))).toBe(true);

  for (const { source, target } of doors) {
    await page.evaluate((key) => {
      const director = window.__HONEY_GAME__.registry.get('director') as { emit: (event: string, value: string) => void };
      director.emit('debug-teleport', key);
    }, source);
    await expect.poll(() => page.evaluate((key) => window.__HONEY_GAME__.scene.isActive(key), source)).toBe(true);
    await page.evaluate(({ sceneKey, targetKey }) => {
      const scene = window.__HONEY_GAME__.scene.getScene(sceneKey) as unknown as {
        objects: Array<{ type: string; x: number; y: number; properties?: Array<{ name: string; value: string }> }>;
        player: { setPosition: (x: number, y: number) => void };
      };
      const door = scene.objects.find((object) => object.type === 'door' && object.properties?.some((property) => property.name === 'target' && property.value === targetKey));
      if (!door) throw new Error(`Door ${sceneKey} -> ${targetKey} not found`);
      scene.player.setPosition(door.x, door.y);
    }, { sceneKey: source, targetKey: target });
    await page.waitForTimeout(80);
    await page.keyboard.press('e');
    await expect.poll(() => page.evaluate((key) => window.__HONEY_GAME__.scene.isActive(key), target)).toBe(true);
  }
});
