import { GameMap } from './game-map';
import { Tile, TileType } from './tile';

function heuristic(ax: number, ay: number, bx: number, by: number) {
  // Diagonale Heuristik (Chebyshev-Distanz)
  return Math.max(Math.abs(ax - bx), Math.abs(ay - by));
}

export function findPath(map: GameMap, start: Tile, goal: Tile): Tile[] {
  const open: Tile[] = [start];
  const cameFrom = new Map<Tile, Tile>();
  const gScore = new Map<Tile, number>();
  const fScore = new Map<Tile, number>();

  gScore.set(start, 0);
  fScore.set(start, heuristic(start.x, start.y, goal.x, goal.y));

  const walkable = (tile: Tile | null) =>
    tile && tile.type !== 'water' && tile.type !== 'stone';

  while (open.length > 0) {
    // Knoten mit niedrigstem fScore wählen
    open.sort(
      (a, b) => (fScore.get(a) ?? Infinity) - (fScore.get(b) ?? Infinity)
    );
    const current = open.shift()!;
    if (current === goal) {
      const path: Tile[] = [];
      let c: Tile | undefined = current;
      while (c) {
        path.unshift(c);
        c = cameFrom.get(c);
      }
      return path;
    }

    // 🔸 Alle 8 Nachbarn (inkl. Diagonalen)
    const neighborOffsets = [
      [1, 0], [-1, 0], [0, 1], [0, -1],
      [1, 1], [-1, -1], [1, -1], [-1, 1]
    ];

    for (const [dx, dy] of neighborOffsets) {
      const n = map.getTile(current.x + dx, current.y + dy);
      if (!n ||!isWalkable(n)) {
        continue;
      }

      // Diagonalbewegung etwas teurer machen
      const moveCost = (dx !== 0 && dy !== 0) ? 1.414 : 1;
      const tentativeG = (gScore.get(current) ?? Infinity) + moveCost;

      if (tentativeG < (gScore.get(n) ?? Infinity)) {
        cameFrom.set(n, current);
        gScore.set(n, tentativeG);
        fScore.set(n, tentativeG + heuristic(n.x, n.y, goal.x, goal.y));
        if (!open.includes(n)) open.push(n);
      }
    }
  }
  console.log("return empty")
  return []; // kein Pfad gefunden
}

export function isWalkable(tile: Tile | null): boolean {
    return !!tile && tile.type !== 'water' && tile.type !== 'stone';
}