import { expect } from "@esm-bundle/chai";
import { VoxelGrid } from "../../src/grid/VoxelGrid.js";

describe("Phase 1: VoxelGrid Implementation", () => {
  let grid;

  beforeEach(() => {
    grid = new VoxelGrid(10, 5, 10);
  });

  it("CoA 1: Should store and retrieve IDs", () => {
    grid.setCell(1, 1, 1, 5);
    expect(grid.getCell(1, 1, 1)).to.equal(5);
  });

  it("CoA 2: Should handle out of bounds gracefully", () => {
    expect(grid.getCell(-1, 0, 0)).to.equal(0);
    expect(grid.getCell(20, 20, 20)).to.equal(0);
  });

  it("Should fill grid with value", () => {
    grid.fill(1); // Set all to Stone
    expect(grid.getCell(0, 0, 0)).to.equal(1);
    expect(grid.getCell(9, 4, 9)).to.equal(1);
  });

  it("Should clone grid data correctly", () => {
    grid.setCell(5, 0, 5, 99);
    const copy = grid.clone();

    expect(copy.getCell(5, 0, 5)).to.equal(99);

    // Modify original, check copy is independent
    grid.setCell(5, 0, 5, 0);
    expect(copy.getCell(5, 0, 5)).to.equal(99);
  });

  it("Should find voxels in radius", () => {
    // Setup a wall at 2,0,2
    grid.setCell(2, 0, 2, 1);
    const center = { x: 0, y: 0, z: 0 };

    // Search radius 3 for ID 1
    const results = grid.getVoxelsInRadius(center, 3, (id) => id === 1);

    expect(results).to.have.lengthOf(1);
    expect(results[0].x).to.equal(2);
  });

  it("Should track unit placement", () => {
    const unit = { id: "u1" };
    const pos = { x: 5, y: 0, z: 5 };

    grid.placeUnit(unit, pos);

    expect(grid.isOccupied(pos)).to.be.true;
    expect(grid.getUnitAt(pos)).to.equal(unit);
    expect(unit.position).to.deep.equal(pos);
  });

  it("Should handle destructible terrain", () => {
    const pos = { x: 3, y: 0, z: 3 };
    grid.setCell(pos.x, pos.y, pos.z, 15); // ID 15 = Destructible

    expect(grid.isDestructible(pos)).to.be.true;

    const success = grid.destroyVoxel(pos);

    expect(success).to.be.true;
    expect(grid.getCell(pos.x, pos.y, pos.z)).to.equal(0); // Now Air
  });
});
