import { expect } from "@esm-bundle/chai";
import { DampCaveTextureGenerator } from "../../src/generation/textures/DampCaveTextureGenerator.js";
import { BioluminescentCaveWallTextureGenerator } from "../../src/generation/textures/BioluminescentCaveWallTextureGenerator.js";

describe("System: Procedural Textures", function () {
  // Increase timeout for texture generation in CI environments/Headless browsers
  this.timeout(20000);

  describe("Floor Generator", () => {
    it("CoA 1: Should generate valid OffscreenCanvases for PBR maps", () => {
      const gen = new DampCaveTextureGenerator(123);
      const maps = gen.generateFloor(64);

      expect(maps.diffuse).to.be.instanceOf(OffscreenCanvas);
      expect(maps.normal).to.be.instanceOf(OffscreenCanvas);
      expect(maps.roughness).to.be.instanceOf(OffscreenCanvas);
      expect(maps.bump).to.be.instanceOf(OffscreenCanvas);

      expect(maps.diffuse.width).to.equal(64);
    });

    it("CoA 2: Should populate pixel data (not empty)", () => {
      const gen = new DampCaveTextureGenerator(123);
      const maps = gen.generateFloor(16);
      const ctx = maps.diffuse.getContext("2d");
      const data = ctx.getImageData(0, 0, 16, 16).data;

      const centerIndex = (8 * 16 + 8) * 4;
      expect(data[centerIndex + 3]).to.equal(255);
      expect(data[centerIndex]).to.be.within(20, 200); // Check valid color range
    });
  });

  describe("Wall Generator", () => {
    it("CoA 3: Should generate valid OffscreenCanvases for Wall PBR maps", () => {
      const gen = new BioluminescentCaveWallTextureGenerator(456);
      const maps = gen.generateWall(64);

      expect(maps.diffuse).to.be.instanceOf(OffscreenCanvas);
      expect(maps.emissive).to.be.instanceOf(OffscreenCanvas);
      expect(maps.diffuse.width).to.equal(64);
    });

    it("CoA 4: Should contain crystal colors (Purple/Cyan)", () => {
      const gen = new BioluminescentCaveWallTextureGenerator(456);
      const maps = gen.generateWall(64);
      const ctx = maps.diffuse.getContext("2d");
      const data = ctx.getImageData(0, 0, 64, 64).data;

      // Scan for a "Crystal" pixel (high saturation, specific hues)
      let foundCrystal = false;
      for (let i = 0; i < data.length; i += 4) {
        const r = data[i];
        const g = data[i + 1];
        const b = data[i + 2];

        // Check for Purple-ish (High Red/Blue, Low Green) or Cyan (High Green/Blue, Low Red)
        // Thresholds based on generator settings
        const isPurple = r > 150 && b > 200 && g < 150;
        const isCyan = r < 150 && g > 200 && b > 200;

        if (isPurple || isCyan) {
          foundCrystal = true;
          break;
        }
      }
      expect(foundCrystal).to.be.true;
    });
  });
});
