import { describe, expect, it } from 'vitest';
import type { MapSprite, RenderedMap } from '@pixeloffice/protocol';
import { ROOF_OVERLAP, buildWorldMap, parseOffice, renderMap, roofBox, stripPieces } from '../src/index.ts';
import { ROOF_OFFICE, ROOMS_OFFICE, mutateYaml, roofCatalog } from './fixtures.ts';

const SHEET = '/sprites/test/sheet.png';
const render = (text = ROOF_OFFICE): RenderedMap => {
  const cat = roofCatalog();
  const layout = parseOffice(text, cat);
  if (!layout.ok) throw new Error(JSON.stringify(layout.errors));
  const map = buildWorldMap(layout.value, cat);
  if (!map.ok) throw new Error(JSON.stringify(map.errors));
  const r = renderMap(layout.value, map.value, cat);
  if (!r.ok) throw new Error(JSON.stringify(r.errors));
  return r.value;
};
// Спрайт в виде [x, y, w, h кадра, px, py] — для сравнения раскладки.
const lay = (s: MapSprite) => [s.frame.x, s.frame.y, s.frame.w, s.frame.h, s.px, s.py];

// Крыша ROOF_OFFICE: rect [0, 0, 5, 4] → px x 0–80, y −16…40 (низ: (0 + 4 − 2)·16 + 8); рамка 7/5/11/6 (сверху,
// справа, снизу, слева) → внутренняя коробка x 6–75 (69 px), y −9…29 (38 px).
describe('renderRoofs (спека крыш 4.4, 4.5)', () => {
  it('roofBox: по внешним краям боковых стен, сверху — кромка северной стены, снизу — нахлёст на лицо южной', () => {
    expect(roofBox([0, 0, 5, 4], 16)).toEqual({ x0: 0, y0: -16, x1: 80, y1: 2 * 16 + ROOF_OVERLAP });
    expect(roofBox([8, 0, 8, 8], 16)).toEqual({ x0: 128, y0: -16, x1: 256, y1: 104 }); // док local: 128×120, как макет
  });

  it('stripPieces: шаг — длина части, последний кусок обрезан', () => {
    expect(stripPieces(69, 16)).toEqual([[0, 16], [16, 16], [32, 16], [48, 16], [64, 5]]);
    expect(stripPieces(32, 16)).toEqual([[0, 16], [16, 16]]);
  });

  it('roofs: rect и спрайты; в sprites карты крыши нет; у всех sortY — низ южной стены', () => {
    const m = render();
    expect(m.roofs).toHaveLength(1);
    const roof = m.roofs![0]!;
    expect(roof.rect).toEqual([0, 0, 5, 4]);
    expect(roof.sprites).toHaveLength(15 + 5 + 5 + 3 + 3 + 4 + 1);
    expect(roof.sprites.every((s) => s.sortY === 4 * 16)).toBe(true);
    expect(roof.sprites.every((s) => s.frame.sheet === SHEET)).toBe(true);
    expect(m.sprites).toEqual(render(ROOMS_OFFICE).sprites); // тот же офис без roofs — те же спрайты карты
  });

  // Две крыши с общей стеной x 4 (спека крыш 4.4.5): при равном sortY сверху — позже в списке, вьюер кладёт крыши в
  // порядке roofs, поэтому порядок списка сохраняется.
  it('две крыши с общей стеной — в порядке списка roofs, с равным sortY', () => {
    const rects = (roofs: number[][]) => render(mutateYaml(ROOMS_OFFICE, (d) => (d.roofs = roofs.map((rect) => ({ rect }))))).roofs!;
    const ab = rects([[0, 0, 5, 4], [4, 0, 6, 4]]);
    expect(ab.map((r) => r.rect)).toEqual([[0, 0, 5, 4], [4, 0, 6, 4]]);
    expect(ab.map((r) => r.sprites[0]!.sortY)).toEqual([64, 64]);
    expect(rects([[4, 0, 6, 4], [0, 0, 5, 4]]).map((r) => r.rect)).toEqual([[4, 0, 6, 4], [0, 0, 5, 4]]);
  });

  it('границы спрайтов крыши — roofBox', () => {
    const s = render().roofs![0]!.sprites.slice(0, -1); // без короба
    expect(Math.min(...s.map((p) => p.px))).toBe(0);
    expect(Math.max(...s.map((p) => p.px + p.frame.w))).toBe(80);
    expect(Math.min(...s.map((p) => p.py))).toBe(-16);
    expect(Math.max(...s.map((p) => p.py + p.frame.h))).toBe(40);
  });

  it('порядок и раскладка: плитка, полосы n, s, w, e, углы nw, ne, sw, se, затем предметы крыши', () => {
    const s = render().roofs![0]!.sprites.map(lay);
    const fill = s.slice(0, 15);
    expect(fill[0]).toEqual([0, 0, 16, 16, 6, -9]);
    expect(fill[4]).toEqual([0, 0, 5, 16, 70, -9]); // последний столбец — 5 px
    expect(fill[14]).toEqual([0, 0, 5, 6, 70, 23]); // последний ряд — 6 px
    expect(s.slice(15, 20)).toEqual([[32, 0, 16, 7, 6, -16], [32, 0, 16, 7, 22, -16], [32, 0, 16, 7, 38, -16], [32, 0, 16, 7, 54, -16], [32, 0, 5, 7, 70, -16]]);
    expect(s.slice(20, 25).map((p) => p[5])).toEqual([29, 29, 29, 29, 29]); // s — от низа внутренней коробки
    expect(s.slice(25, 28)).toEqual([[48, 0, 6, 16, 0, -9], [48, 0, 6, 16, 0, 7], [48, 0, 6, 6, 0, 23]]);
    expect(s.slice(28, 31)).toEqual([[64, 0, 5, 16, 75, -9], [64, 0, 5, 16, 75, 7], [64, 0, 5, 6, 75, 23]]); // e — правая рамка 5 px
    expect(s.slice(31, 35)).toEqual([[0, 0, 6, 7, 0, -16], [16, 0, 5, 7, 75, -16], [0, 16, 6, 11, 0, 29], [16, 16, 5, 11, 75, 29]]);
    expect(s[35]).toEqual([96, 0, 32, 16, 16, 8]); // короб на клетке (1, 1), часть at [0, −8]
  });

  it('офис без roofs — поля roofs нет (hello как раньше)', () => {
    expect(render(ROOMS_OFFICE)).not.toHaveProperty('roofs');
    expect(render(mutateYaml(ROOF_OFFICE, (d) => (d.roofs = [])))).not.toHaveProperty('roofs');
  });
});
