import { describe, it, expect } from 'vitest';
import { parseUvtt, toUvtt } from './uvtt';

// 1x1 transparent PNG
const PNG = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==';

const sample = JSON.stringify({
  format: 0.3,
  resolution: { map_origin: { x: 0, y: 0 }, map_size: { x: 30, y: 21 }, pixels_per_grid: 100 },
  line_of_sight: [[{ x: 1, y: 1 }, { x: 5, y: 1 }, { x: 5, y: 4 }]],
  portals: [{ position: { x: 5, y: 2.5 }, bounds: [{ x: 5, y: 2 }, { x: 5, y: 3 }], closed: true }],
  lights: [{ position: { x: 3, y: 3 }, range: 6, color: 'ff8040', intensity: 0.7 }],
  image: PNG,
});

describe('parseUvtt', () => {
  it('converts grid-unit geometry to image pixels using pixels_per_grid', () => {
    const m = parseUvtt(sample)!;
    expect(m).toBeTruthy();
    expect(m.gridSize).toBe(100);
    expect(m.cols).toBe(30);
    expect(m.rows).toBe(21);
    expect(m.image.startsWith('data:image/png;base64,')).toBe(true);
    // wall: 3 points scaled ×100
    expect(m.walls).toHaveLength(1);
    expect(m.walls[0]!.points).toEqual([{ x: 100, y: 100 }, { x: 500, y: 100 }, { x: 500, y: 400 }]);
    // door: bounds → segment, closed → open=false
    expect(m.doors[0]).toEqual({ a: { x: 500, y: 200 }, b: { x: 500, y: 300 }, open: false });
    // light: position ×100, range ×100, color normalized
    expect(m.lights[0]).toEqual({ x: 300, y: 300, range: 600, color: '#ff8040', intensity: 0.7 });
  });

  it('returns null for non-JSON or imageless files', () => {
    expect(parseUvtt('not json')).toBeNull();
    expect(parseUvtt(JSON.stringify({ resolution: { pixels_per_grid: 70 } }))).toBeNull();
  });

  it('round-trips walls/doors back to grid units on export', () => {
    const m = parseUvtt(sample)!;
    const out = toUvtt({ image: m.image, gridSize: m.gridSize, cols: m.cols, rows: m.rows, walls: m.walls, doors: m.doors, lights: m.lights }) as {
      resolution: { pixels_per_grid: number }; line_of_sight: { x: number; y: number }[][];
    };
    expect(out.resolution.pixels_per_grid).toBe(100);
    expect(out.line_of_sight[0]).toEqual([{ x: 1, y: 1 }, { x: 5, y: 1 }, { x: 5, y: 4 }]);
  });
});
