import {
  getMapBackgroundTileId,
  parseHeightLayers,
  parseRoomLayers,
} from "./worldshaperShared";
import type { JsonObject } from "../editorCore";

describe("worldshaperShared", () => {
  it("prefers top-level background tile ids and falls back to the legacy nested shape", () => {
    expect(getMapBackgroundTileId({ backgroundTileId: "grass" })).toBe("grass");
    expect(getMapBackgroundTileId({ tiles: { backgroundTileId: "water" } as unknown as JsonObject })).toBe("water");
    expect(getMapBackgroundTileId({})).toBe("");
  });

  it("synthesizes and resizes room layers from the current map payload", () => {
    const result = parseRoomLayers({
      rows: ["##", "#"],
      roomLayers: [
        {
          layer: 2,
          name: "Objects",
          rows: ["A"],
          instanceIds: ["npc_1", ""],
        },
      ],
    }, 3, 2);

    expect(result).toEqual([
      {
        layer: 0,
        name: undefined,
        zIndex: 0,
        rows: ["##.", "#.."],
        instanceIds: [],
      },
      {
        layer: 2,
        name: "Objects",
        zIndex: 0,
        rows: ["A  ", "   "],
        instanceIds: ["npc_1"],
      },
    ]);
  });

  it("normalizes, trims, and bounds height patches while dropping duplicate ids", () => {
    const result = parseHeightLayers({
      heightLayers: [
        {
          id: "ridge",
          z: 3,
          x: -1,
          y: -1,
          rows: [
            "...",
            ".9.",
            "..8",
          ],
        },
        {
          id: "ridge",
          z: 9,
          x: 0,
          y: 0,
          rows: ["1"],
        },
      ],
    }, 4, 4);

    expect(result).toEqual([
      {
        id: "ridge",
        name: undefined,
        z: 3,
        x: 0,
        y: 0,
        rows: ["9", " 8"],
      },
    ]);
  });
});
