import type { BattleMap } from '@/lib/schemas';
import { tokenCells } from './grid';
import type { PlayerDrawing, PlayerMap, PlayerToken } from './types';

/**
 * Reduce a full BattleMap to what players may see: GM-only tokens/drawings are
 * removed; the image data URL is excluded (it travels separately / from local
 * Dexie). Revealed cells pass through (the player renderer fogs the rest).
 */
export function toPlayerProjection(map: BattleMap): PlayerMap {
  // When fog is on, a token is only visible to players if at least one of its
  // footprint cells is revealed — so names/positions stay hidden in the dark.
  const revealed = new Set(map.revealed);
  const visible = (t: BattleMap['tokens'][number]) =>
    !map.fogEnabled || tokenCells({ col: t.col, row: t.row, size: t.size }).some((k) => revealed.has(k));

  const tokens: PlayerToken[] = map.tokens
    .filter((t) => !t.gmOnly && visible(t))
    .map((t) => ({
      id: t.id, label: t.label, color: t.color, col: t.col, row: t.row, size: t.size, kind: t.kind,
      ...(t.hp ? { hp: t.hp } : {}),
      conditions: t.conditions.map((c) => ({ name: c.name, ...(c.value !== undefined ? { value: c.value } : {}) })),
    }));

  const drawings: PlayerDrawing[] = map.drawings
    .filter((d) => !d.gmOnly)
    .map((d) => ({
      id: d.id, kind: d.kind, points: d.points, color: d.color, width: d.width,
      ...(d.text !== undefined ? { text: d.text } : {}),
    }));

  return {
    id: map.id,
    name: map.name,
    gridSize: map.gridSize,
    showGrid: map.showGrid,
    fogEnabled: map.fogEnabled,
    revealed: map.revealed,
    gridType: map.gridType,
    gridUnit: map.gridUnit,
    tokens,
    drawings,
    hasImage: !!map.image,
  };
}
