/* eslint-disable @typescript-eslint/ban-ts-comment */
// @ts-nocheck

import { refreshCanvasTexture } from "./pixiSurfaceHelpers";

export function buildChunkSignature(symbolAt, tileWidth, tileHeight, prefix) {
  const parts = [String(prefix || "")];
  for (let localY = 0; localY < tileHeight; localY += 1) {
    let row = "";
    for (let localX = 0; localX < tileWidth; localX += 1) {
      row += String(symbolAt(localX, localY) || " ");
    }
    parts.push(row);
  }
  return parts.join("\n");
}

export function redrawChunkEntrySurface(entry, symbolAt, options) {
  options.syncChunkEntryDimensions(entry);
  const pixelTileSize = Math.max(1, Number(options.baseTileSize) || Number(options.tileSize) || 32);
  const pixelWidth = Math.max(1, entry.tileWidth * pixelTileSize);
  const pixelHeight = Math.max(1, entry.tileHeight * pixelTileSize);
  entry.ctx.setTransform(1, 0, 0, 1, 0, 0);
  entry.ctx.clearRect(0, 0, pixelWidth, pixelHeight);
  entry.ctx.imageSmoothingEnabled = false;
  let hasContent = false;
  for (let localY = 0; localY < entry.tileHeight; localY += 1) {
    for (let localX = 0; localX < entry.tileWidth; localX += 1) {
      const symbol = symbolAt(localX, localY);
      if (!symbol) {
        continue;
      }
      const tileSurface = options.getTileSurface(symbol);
      if (!tileSurface) {
        continue;
      }
      const tileOpacity = typeof options.getTileOpacity === "function"
        ? Number(options.getTileOpacity(symbol))
        : 1;
      const normalizedTileOpacity = Number.isFinite(tileOpacity)
        ? Math.max(0, Math.min(1, tileOpacity))
        : 1;
      entry.ctx.globalAlpha = normalizedTileOpacity;
      entry.ctx.drawImage(
        tileSurface,
        localX * pixelTileSize,
        localY * pixelTileSize,
        pixelTileSize,
        pixelTileSize,
      );
      entry.ctx.globalAlpha = 1;
      hasContent = true;
    }
  }
  refreshCanvasTexture(entry.texture);
  entry.lastRenderedAt = performance.now();
  entry.sprite.visible = hasContent;
  return hasContent;
}

export function rebuildChunkEntrySurface(entry, symbolAt, tileWidth, tileHeight, signaturePrefix, options) {
  const safeWidth = Math.max(1, Number(tileWidth) || Number(options.chunkSize) || 32);
  const safeHeight = Math.max(1, Number(tileHeight) || Number(options.chunkSize) || 32);
  if (entry.tileWidth !== safeWidth || entry.tileHeight !== safeHeight) {
    entry.tileWidth = safeWidth;
    entry.tileHeight = safeHeight;
  }
  const signature = buildChunkSignature(symbolAt, safeWidth, safeHeight, signaturePrefix);
  if (entry.signature === signature) {
    return entry.sprite.visible;
  }
  entry.signature = signature;
  return redrawChunkEntrySurface(entry, symbolAt, options);
}
