export class PostProcessor {
  static ensureConnectivity(grid) {
    // 1. Identify all empty (Air) regions
    const regions = [];
    const visited = new Set();

    for (let x = 0; x < grid.size.x; x++) {
      for (let z = 0; z < grid.size.z; z++) {
        // We only care about "Floor" tiles (Air with Solid below)
        // because that's where units stand
        if (grid.getCell(x, 1, z) === 0 && grid.getCell(x, 0, z) !== 0) {
          const key = `${x},1,${z}`;
          if (!visited.has(key)) {
            const region = this.floodFill(grid, x, 1, z, visited);
            regions.push(region);
          }
        }
      }
    }

    if (regions.length === 0) return;

    // 2. Sort by size (largest first)
    regions.sort((a, b) => b.length - a.length);

    // 3. Fill all smaller regions with stone (or connect them later)
    // For prototype, we just fill them to avoid soft-locks
    for (let i = 1; i < regions.length; i++) {
      for (const pos of regions[i]) {
        grid.setCell(pos.x, pos.y, pos.z, 1); // Fill air with stone
      }
    }
  }

  static floodFill(grid, startX, startY, startZ, visitedGlobal) {
    const region = [];
    const stack = [{ x: startX, y: startY, z: startZ }];

    while (stack.length > 0) {
      const { x, y, z } = stack.pop();
      const key = `${x},${y},${z}`;

      if (visitedGlobal.has(key)) continue;
      visitedGlobal.add(key);
      region.push({ x, y, z });

      // Check neighbors (Cardinal)
      const neighbors = [
        { x: x + 1, y, z },
        { x: x - 1, y, z },
        { x, y, z: z + 1 },
        { x, y, z: z - 1 },
      ];

      for (const n of neighbors) {
        if (grid.isValidBounds(n.x, n.y, n.z)) {
          // Is it also an Air tile?
          if (grid.getCell(n.x, n.y, n.z) === 0) {
            stack.push(n);
          }
        }
      }
    }
    return region;
  }
}
