import {
  DEFAULT_WORLD_CHUNK_SIZE,
  buildChunkFileName,
  buildChunkKey,
  createEmptyChunk,
  localToWorldCoord,
  normalizeChunkDimension,
  resolveWorldChunkAddress,
  worldToChunkCoord,
  worldToLocalCoord,
} from "./worldChunking";

describe("worldChunking", () => {
  it("normalizes chunk dimensions with flooring and fallback behavior", () => {
    expect(normalizeChunkDimension(12.9)).toBe(12);
    expect(normalizeChunkDimension(0, 24)).toBe(24);
    expect(normalizeChunkDimension(-5, 24)).toBe(1);
    expect(normalizeChunkDimension("bad", 18)).toBe(18);
  });

  it("converts world coordinates into chunk and local coordinates across the origin", () => {
    expect(worldToChunkCoord(0, 32)).toBe(0);
    expect(worldToChunkCoord(31, 32)).toBe(0);
    expect(worldToChunkCoord(32, 32)).toBe(1);
    expect(worldToChunkCoord(-1, 32)).toBe(-1);
    expect(worldToChunkCoord(-33, 32)).toBe(-2);

    expect(worldToLocalCoord(31, 32)).toBe(31);
    expect(worldToLocalCoord(32, 32)).toBe(0);
    expect(worldToLocalCoord(-1, 32)).toBe(31);
    expect(worldToLocalCoord(-33, 32)).toBe(31);

    expect(localToWorldCoord(-2, 31, 32)).toBe(-33);
  });

  it("resolves stable chunk addressing metadata", () => {
    expect(buildChunkKey(-3, 4)).toBe("-3:4");
    expect(buildChunkFileName(-3, 4)).toBe("-3_4.json");
    expect(resolveWorldChunkAddress(-33, 64, 32, 16)).toEqual({
      chunkX: -2,
      chunkY: 4,
      localX: 31,
      localY: 0,
      chunkKey: "-2:4",
      fileName: "-2_4.json",
    });
  });

  it("creates empty chunks with the current compatibility layer defaults", () => {
    const chunk = createEmptyChunk("overworld", 2, -1, "grass", 4, 3);

    expect(chunk).toEqual({
      schemaVersion: 1,
      worldId: "overworld",
      chunkX: 2,
      chunkY: -1,
      width: 4,
      height: 3,
      backgroundTileId: "grass",
      roomLayers: [
        {
          layer: 0,
          rows: ["....", "....", "...."],
          instanceIds: [],
        },
        {
          layer: 1,
          rows: ["    ", "    ", "    "],
          instanceIds: [],
        },
      ],
      heightLayers: [],
      instances: [],
    });
    expect(createEmptyChunk("world", 0, 0).width).toBe(DEFAULT_WORLD_CHUNK_SIZE);
  });
});
