import { Tile, TileType } from "./tile";
import {createNoise2D } from 'simplex-noise';
import seedrandom from 'seedrandom';

export class GameMap {
  private tiles: Tile[] = [];

  constructor(
    public readonly width: number,
    public readonly height: number,
    private readonly seed: number = Date.now()
  ) {
    this.generate();
  }

  private generate(): void {
    // 👇 create a deterministic RNG from the seed
    const rng = seedrandom(this.seed.toString());
    const noise2D = createNoise2D(rng); // ✅ expects a RandomFn
    this.tiles = [];

    const scale = 0.08;

    for (let y = 0; y < this.height; y++) {
      for (let x = 0; x < this.width; x++) {
        const n = noise2D(x * scale, y * scale); // [-1, 1]
        const value = (n + 1) / 2; // [0, 1]

        let type: TileType = 'grass';
        if (value < 0.15) type = 'water';
        else if (value < 0.25) type = 'stone';
        else if (value > 0.65) type = 'forest';

        this.tiles.push(new Tile({ x, y, type }));
      }
    }
  }

  getTile(x: number, y: number): Tile | null {
    if (x < 0 || y < 0 || x >= this.width || y >= this.height) return null;
    return this.tiles[y * this.width + x];
  }

  forEach(fn: (tile: Tile) => void): void {
    for (const tile of this.tiles) fn(tile);
  }
}