/* eslint-disable @typescript-eslint/ban-ts-comment, @typescript-eslint/no-unused-vars, no-empty, no-useless-escape */
// @ts-nocheck
import { buildSpritePreviewDataUrl } from "../editorCore";
import {
  buildSpriteCatalog,
  buildTileCatalogById,
  DEFAULT_MAP_BACKGROUND_COLOR,
} from "../components/worldshaperShared";
import type { WorldshaperStudioBootstrap } from "./bootstrap";

function getContentRecords(payload: unknown, key: string) {
  const records = payload && Array.isArray(payload[key]) ? payload[key] : [];
  return records.filter((entry) => Boolean(entry) && typeof entry === "object" && !Array.isArray(entry));
}

export function cloneRuntimeValue<T>(value: T): T {
  if (typeof structuredClone === "function") {
    return structuredClone(value);
  }
  return value == null ? value : JSON.parse(JSON.stringify(value));
}

export function buildSpriteCatalogFromBootstrap(bootstrap: WorldshaperStudioBootstrap) {
  const spriteRecords = getContentRecords(bootstrap?.contentByType?.sprites, "sprites");
  if (spriteRecords.length > 0) {
    return buildSpriteCatalog(spriteRecords, buildSpritePreviewDataUrl);
  }
  return cloneRuntimeValue(bootstrap?.spriteCatalog) || {};
}

export function buildTileCatalogByIdFromBootstrap(bootstrap: WorldshaperStudioBootstrap) {
  const tileRecords = getContentRecords(bootstrap?.contentByType?.tiles, "tiles");
  if (tileRecords.length > 0) {
    return buildTileCatalogById(tileRecords, buildSpritePreviewDataUrl);
  }
  return cloneRuntimeValue(bootstrap?.tileCatalogById) || {};
}

export function buildNpcOverlaysFromWorldChunks(
  chunks: unknown[],
  spriteCatalog: Record<string, unknown>,
  chunkWidth: number,
  chunkHeight: number,
  originChunkX: number,
  originChunkY: number,
) {
  return (Array.isArray(chunks) ? chunks : []).flatMap((chunk) => {
    const baseChunkX = Math.floor(Number(chunk?.chunkX) || 0);
    const baseChunkY = Math.floor(Number(chunk?.chunkY) || 0);
    const offsetX = (baseChunkX - originChunkX) * chunkWidth;
    const offsetY = (baseChunkY - originChunkY) * chunkHeight;
    const instances = Array.isArray(chunk?.instances) ? chunk.instances : [];
    return instances
      .filter((entry) => Boolean(entry) && typeof entry === "object" && !Array.isArray(entry))
      .map((entry) => {
        const record = entry.record && typeof entry.record === "object" && !Array.isArray(entry.record)
          ? cloneRuntimeValue(entry.record)
          : {};
        const spriteId = String(record.spriteId || entry.spriteId || "").trim();
        const spriteEntry = spriteCatalog[spriteId] || null;
        const overlayX = offsetX + Math.max(0, Number(entry.x) || 0);
        const overlayY = offsetY + Math.max(0, Number(entry.y) || 0);
        record.position = {
          x: overlayX,
          y: overlayY,
        };
        return {
          id: String(entry.id || "").trim(),
          layer: Number(entry.layer) || 0,
          name: String(record.name || entry.id || "NPC"),
          spriteId,
          x: overlayX,
          y: overlayY,
          dataUrl: spriteEntry ? spriteEntry.dataUrl : null,
          spriteWidth: spriteEntry ? spriteEntry.spriteWidth : 28,
          spriteHeight: spriteEntry ? spriteEntry.spriteHeight : 28,
          opacity: spriteEntry ? spriteEntry.opacity : 1,
          record,
        };
      })
      .filter((entry) => entry.id);
  });
}

export function normalizeMapBackgroundColor(value: unknown, fallback?: string) {
  const safeFallback = fallback || DEFAULT_MAP_BACKGROUND_COLOR;
  const raw = String(value || "").trim();
  return /^#[0-9a-fA-F]{6}$/.test(raw) ? raw.toUpperCase() : safeFallback;
}

export function createInitialWorldRuntimeState(bootstrap: WorldshaperStudioBootstrap) {
  const worldId = String(bootstrap.worldId || bootstrap.mapId || "").trim();
  const chunkRadius = Math.max(0, Math.floor(Number(bootstrap.worldChunkRadius) || 0));
  const originChunkX = Math.floor(Number(bootstrap.worldOriginChunkX) || 0);
  const originChunkY = Math.floor(Number(bootstrap.worldOriginChunkY) || 0);

  return {
    enabled: !!worldId,
    worldId,
    worldName: String(bootstrap.worldName || bootstrap.mapName || bootstrap.worldId || bootstrap.mapId || "World").trim() || "World",
    defaultBackgroundTileId: String(bootstrap.backgroundTileId || "").trim(),
    heightBlurStep: Math.max(0, Math.min(1, Number(bootstrap.heightBlurStep ?? bootstrap.heightDetailStep) || 0.1)),
    chunkWidth: Math.max(1, Number(bootstrap.worldChunkWidth) || 32),
    chunkHeight: Math.max(1, Number(bootstrap.worldChunkHeight) || 32),
    chunkRadius,
    originChunkX,
    originChunkY,
    tileOffsetX: Math.floor(Number(bootstrap.worldTileOffsetX) || 0),
    tileOffsetY: Math.floor(Number(bootstrap.worldTileOffsetY) || 0),
    spawnX: Math.floor(Number(bootstrap.worldSpawnX) || 0),
    spawnY: Math.floor(Number(bootstrap.worldSpawnY) || 0),
    centerChunkX: originChunkX + chunkRadius,
    centerChunkY: originChunkY + chunkRadius,
    sourceChunks: Array.isArray(bootstrap.sourceChunks)
      ? bootstrap.sourceChunks.map((entry) => ({
        chunkX: Math.floor(Number(entry?.chunkX) || 0),
        chunkY: Math.floor(Number(entry?.chunkY) || 0),
      }))
      : [],
    bookmarks: Array.isArray(bootstrap.worldBookmarks)
      ? bootstrap.worldBookmarks.map((entry, index) => ({
        id: String(entry?.id || `poi_${index + 1}`).trim() || `poi_${index + 1}`,
        label: String(entry?.label || entry?.id || `POI ${index + 1}`).trim() || `POI ${index + 1}`,
        x: Math.floor(Number(entry?.x) || 0),
        y: Math.floor(Number(entry?.y) || 0),
      }))
      : [],
    chunkCache: new Map(),
    dirtyChunkKeys: new Set(),
    pendingNeighborhoodFetches: new Map(),
    prefetchedNeighborhoodKeys: new Set(),
    pendingLoadKey: "",
    pendingLoadPromise: null,
    requestSerial: 0,
    documentDirty: false,
  };
}

export const MAX_WORLD_CHUNK_CACHE_ENTRIES = 256;
export const MAX_DYNAMIC_WORLD_CHUNK_RADIUS = 4;
export const TILE_SYMBOL_POOL = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!$%&()*+,-/:;<=>?@[]^_{|}~=";
