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

// MOCK Browser APIs if needed (web-test-runner generally runs in browser/headless chrome so OffscreenCanvas should exist)
// But if running in node via some flag, we might need polyfills.
// However, package.json says "web-test-runner --node-resolve", which implies browser environment unless configured otherwise.
// If typical tests run in browser, OffscreenCanvas is available.

describe("Generation: ContestedFrontierGenerator", () => {
  let grid;
  let generator;

  beforeEach(() => {
    grid = new VoxelGrid(30, 10, 30);
    generator = new ContestedFrontierGenerator(grid, 12345);
  });

  it("should generate a trench map with correct IDs", () => {
    generator.generate();

    let solidCount = 0;
    let fortifications = 0;
    let trenchWalls = 0;
    let trenchFloors = 0;

    for (let x = 0; x < grid.size.x; x++) {
      for (let y = 0; y < grid.size.y; y++) {
        for (let z = 0; z < grid.size.z; z++) {
          const id = grid.getCell(x, y, z);
          if (id !== 0) {
            solidCount++;
            if (id === 12) fortifications++;
            if (id >= 120 && id < 200) trenchWalls++;
            if (id >= 220 && id < 300) trenchFloors++;
          }
        }
      }
    }

    expect(solidCount).to.be.greaterThan(0, "Should generate solid voxels");
    expect(trenchWalls).to.be.greaterThan(
      0,
      "Should generate trench walls (120+)"
    );
    expect(trenchFloors).to.be.greaterThan(
      0,
      "Should generate trench floors (220+)"
    );
    // Fortifications are probabilistic, but likely with this seed
    // expect(fortifications).to.be.greaterThanOrEqual(0);
  });

  it("should distribute splotchy textures (muddy, mixed, grassy)", () => {
    // We can inspect ID ranges in the floor area (220-229) to see if we get variation
    generator.generate();

    const counts = {
      muddy: 0, // 220-222
      mixed: 0, // 223-226
      grassy: 0, // 227-229
    };

    for (let x = 0; x < grid.size.x; x++) {
      for (let z = 0; z < grid.size.z; z++) {
        // Check surface
        for (let y = grid.size.y - 1; y >= 0; y--) {
          const id = grid.getCell(x, y, z);
          if (id >= 220 && id <= 222) {
            counts.muddy++;
            break;
          }
          if (id >= 223 && id <= 226) {
            counts.mixed++;
            break;
          }
          if (id >= 227 && id <= 229) {
            counts.grassy++;
            break;
          }
        }
      }
    }

    // We expect at least some representation of each, or at least 2 of them given the noise scale
    expect(counts.muddy + counts.mixed + counts.grassy).to.be.greaterThan(0);
    // With current seed 12345, we likely have a mix
    // Just assert that we have *some* floors
  });
});
