Skip to content

A lightweight Clip Studio Paint alternative with real-time multiplayer collaborative drawing. Built with Tauri and React.

174 KB
Raw Blame
import {
  AccessDeniedCode,
  AccessDeniedMessage,
  AnimationSyncMessage,
  BrushAssetDataMessage,
  BrushAssetRequestMessage,
  BrushProfileDataMessage,
  BrushProfileRequestMessage,
  BrushRequestMessage,
  BrushShareMessage,
  CameraSyncMessage,
  CameraSyncRequestMessage,
  CanvasPingMessage,
  CanvasResizeMessage,
  ChatMessage,
  CollabDiagnostics,
  CollabPeer,
  CollabPeerCamera,
  CollabRole,
  CursorMoveMessage,
  DocSyncResponseMessage,
  LayerActionMessage,
  LayerChecksumEntry,
  LayerClearableField,
  LayerMaskDataMessage,
  LayerTreeSyncMessage,
  LayerUpdateMessage,
  MultiplayerMessage,
  PeerBanMessage,
  PeerKickMessage,
  PeerRoleUpdateMessage,
  PeerUnbanMessage,
  PerspectiveRulerSyncMessage,
  SelectiveUndoMessage,
  StateChecksumAuditMessage,
  StraightRulerSyncMessage,
  StrokeChunkMessage,
  StrokeFinishMessage,
  StrokeStartMessage,
  TileResyncRequestMessage,
  TileStreamMessage,
  WireLayerItem,
} from '../types/multiplayer';
import {
  AnimationTimeline,
  BrushSettings,
  CanvasDimensions,
  DirtyRect,
  LayerItem,
  Point,
  ToolType,
  VectorStroke,
} from '../types/editor';
import { PerspectiveRuler, StraightRuler } from '../types/perspective';
import { ResizeCanvasOptions } from '../types/settings';
import {
  TILE_CODEC_EMPTY,
  TILE_CODEC_SUBRECT_LZ4,
  WireTilePayload,
  deserializeWireTilePacketStrict,
  serializeWireTilePacket,
  wireCodeToFormat,
} from '../utils/collabTileCodec';
import {
  isNativeCanvasActive,
  nativeCollabEncodeMask,
  nativeCollabEncodeTiles,
} from '../utils/nativeEngineBridge';
import {
  BrushProfileDynamicOverrides,
  CanonicalBrushProfile,
  MAX_BRUSH_ASSET_BYTES,
  applyBrushProfileOverrides,
  computeBrushProfileHash,
  isAllowedBrushAssetMime,
  isValidBrushAssetHash,
  prepareBrushSettingsForWire,
  sanitizeBrushAssetRefs,
} from '../utils/brushAssetSync';
import { CollabDiagnosticsTracker } from '../utils/collabDiagnostics';
import { lz4CompressBlock, lz4DecompressBlock } from '../utils/lz4';
import {
  MAX_SYNC_CANVAS_DIM,
  sanitizeAnimationTimeline,
  sanitizeCanvasResize,
  sanitizeClearedFields,
  sanitizePerspectiveRuler,
  sanitizeStraightRuler,
  sanitizeWireLayer,
  sanitizeWireLayerPatch,
  sanitizeWireLayerTree,
  serializeLayerForWire,
} from '../utils/collabSyncUtils';
import { CollabSendOptions, CollabTransportKind, ICollabTransport } from './collabTransport';
import { normalizeRoomCode, normalizeRoomSecret } from './webrtcSignaling';

type MessageHandler = (msg: MultiplayerMessage) => void;

// Binary Message Codes (must stay 100% aligned with webrtcHostHub.ts & src-tauri/src/server.rs)
export const BINARY_MAGIC_0 = 0x49; // 'I'
export const BINARY_MAGIC_1 = 0x4e; // 'N'

export const CODE_STROKE_START = 0x01;
export const CODE_STROKE_CHUNK = 0x02;
export const CODE_STROKE_FINISH = 0x03;
export const CODE_TILE_DELTA = 0x04;
export const CODE_CURSOR_MOVE = 0x05;
export const CODE_SELECTIVE_UNDO = 0x06;
export const CODE_BRUSH_ASSET_DATA = 0x07;
export const CODE_BRUSH_ASSET_REQUEST = 0x08;
export const CODE_LAYER_MASK_DATA = 0x09;
export const CODE_CAMERA_SYNC = 0x0a;
export const CODE_BRUSH_PROFILE_DATA = 0x0b;
export const CODE_BRUSH_PROFILE_REQUEST = 0x0c;
export const CODE_STROKE_CHUNK_V2 = 0x0d;
export const CODE_PING = 0x0e;
export const CODE_PONG = 0x0f;

// Slim binary STROKE_START v2 format constants (first payload byte 0x02 != JSON '{' 0x7b)
export const STROKE_START_BINARY_VERSION = 0x02;
const STROKE_START_FLAG_IS_CORNER = 0x01;
const STROKE_START_FLAG_HAS_TILT_TWIST = 0x02;
const STROKE_START_FLAG_COLOR_RGB24 = 0x04;
const STROKE_START_FLAG_COLOR_STR = 0x08;
const STROKE_START_FLAG_HAS_SIZE = 0x10;
const STROKE_START_FLAG_HAS_OPACITY = 0x20;

// Compact STROKE_CHUNK v2 marker & point flags (0x8002 cannot collide with legacy V1 sIdLen <= 256)
export const STROKE_CHUNK_V2_MARKER = 0x8002;
const CHUNK_PT_IS_CORNER = 0x01;
const CHUNK_PT_ABSOLUTE = 0x02;
const CHUNK_PT_HAS_TILT_TWIST = 0x04;
const CHUNK_PT_PRESSURE_SAME = 0x08;
const CHUNK_PT_WIDTH_SAME = 0x10;

// Adaptive stroke point thinning thresholds (network emission only; zero impact on local rendering)
const THIN_MIN_DIST_PX = 0.35;
const THIN_MIN_DIST_SQ = THIN_MIN_DIST_PX * THIN_MIN_DIST_PX;
const THIN_MIN_PRESSURE_DELTA = 0.005;
const THIN_MIN_WIDTH_DELTA = 0.25;
const THIN_COLLINEAR_MAX_DEV_PX = 0.2;
const THIN_COLLINEAR_MAX_SEG_PX = 24;

// Brush profile cache & wire limits
const BRUSH_PROFILE_FLAG_LZ4 = 0x01;
const MAX_BRUSH_PROFILE_BYTES = 256 * 1024;
const MAX_CACHED_BRUSH_PROFILES = 256;
const MAX_PENDING_PROFILE_STROKES = 16;
const MAX_PENDING_PROFILE_CHUNKS = 64;
const PROFILE_MISS_FALLBACK_MS = 500;
const PROFILE_REQUEST_COOLDOWN_MS = 3000;

// Lightweight RTT ping cadence
const PING_INTERVAL_MS = 5000;
const PING_INITIAL_DELAY_MS = 1000;
const PING_PAYLOAD_BYTES = 12; // [pingId: u32 LE, sendMs: f64 LE]
const RGB24_HEX_RE = /^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/;

const CAMERA_FLAG_FLIP_X = 0x01;
const CAMERA_FLAG_FLIP_Y = 0x02;
const MAX_CHAT_TEXT_LEN = 1000;
const CAMERA_SYNC_THROTTLE_MS = 50;

const MASK_FLAG_FULL_REPLACE = 0x01;
const MASK_FLAG_LZ4 = 0x02;
const MASK_FLAG_SOLID_FILL = 0x04;
const MAX_MASK_DECODE_BYTES = 64 * 1024 * 1024; // 64 MB safety ceiling per mask packet (up to 8192×8192 alpha mask)

const MAX_BINARY_PACKET_BYTES = 16 * 1024 * 1024;
const MAX_JSON_MESSAGE_CHARS = 8 * 1024 * 1024;
const MAX_STROKE_CHUNK_POINTS = 4096;
const STROKE_CHUNK_POINT_STRIDE = 20;
const MAX_TILE_COORD = 4096;
const WS_CONNECT_TIMEOUT_MS = 15000;
const STATE_SYNC_THROTTLE_MS = 33;
export const LAYER_PROP_THROTTLE_MS = 40;
const MAX_OUTGOING_BUFFERED_BYTES = 2 * 1024 * 1024;

/** Continuous slider/color layer properties eligible for trailing-edge coalescing. */
const CONTINUOUS_LAYER_UPDATE_KEYS = new Set<string>([
  'opacity',
  'toneFrequency',
  'toneAngle',
  'toneDensity',
  'monoThreshold',
  'layerColor',
  'layerSubColor',
  'adjustmentData',
  'styles',
]);
const OUTGOING_TILE_BATCH_SIZE = 16;
const INCOMING_TILE_BATCH_SIZE = 32;
const TILE_PACKET_HEADER_BYTES = 14;

/** Maximum tiles encoded/decoded synchronously on the main thread before offloading to Rust/Worker batch codecs. */
export const SYNC_TILE_CODEC_THRESHOLD = 4;

// Shared module-level UTF-8 codecs (eliminates per-packet TextEncoder/TextDecoder allocations)
const sharedTextEncoder = new TextEncoder();
const sharedTextDecoder = new TextDecoder();

export interface OutgoingTileEntry {
  layerId: string;
  tile: WireTilePayload;
  /** Optional pre-encoded binary tile packet straight from Rust `ink-engine`. */
  encodedPacket?: Uint8Array;
}

export interface SendTileDeltasResult {
  tileCount: number;
  pending: boolean;
}

type OutgoingTileQueueJob =
  | {
      kind: 'tiles';
      entries: OutgoingTileEntry[];
      cursor: number;
      targetPeerId?: string | number;
      strokeId?: string;
      onFlushed?: () => void;
    }
  | {
      kind: 'barrier';
      strokeId?: string;
      run: () => void;
    };

type IncomingQueueEntry =
  | {
      kind: 'tile';
      layerId: string;
      tilePacket: Uint8Array;
      tileKey: string;
      serverSeq: number;
    }
  | {
      kind: 'message';
      msg: MultiplayerMessage;
    };

interface StrokeCommitMetadata {
  expectedTileCount: number;
  pending: boolean;
  layerId?: string;
}

interface PendingProfileStroke {
  profileHash: string;
  start: StrokeStartMessage;
  overrides: BrushProfileDynamicOverrides;
  chunks: StrokeChunkMessage[];
  finish?: StrokeFinishMessage;
  timer: ReturnType<typeof setTimeout>;
}

const BYPASS_INCOMING_TILE_QUEUE_TYPES = new Set<string>([
  'CURSOR_MOVE',
  'CAMERA_SYNC',
  'CAMERA_SYNC_REQUEST',
  'STROKE_START',
  'STROKE_CHUNK',
  'CHAT_MESSAGE',
  'CANVAS_PING',
  'BRUSH_ASSET_DATA',
  'BRUSH_ASSET_REQUEST',
  'BRUSH_PROFILE_DATA',
  'BRUSH_PROFILE_REQUEST',
  'BRUSH_REQUEST',
  'BRUSH_SHARE',
]);

export function hex32ToBytes16(hex: string): Uint8Array | null {
  if (!isValidBrushAssetHash(hex)) return null;
  const out = new Uint8Array(16);
  for (let i = 0; i < 16; i++) {
    out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
  }
  return out;
}

export function bytes16ToHex32(bytes: Uint8Array): string {
  let hex = '';
  for (let i = 0; i < 16; i++) {
    hex += bytes[i].toString(16).padStart(2, '0');
  }
  return hex;
}

function quantizeTilt(v?: number): number {
  return Math.max(-90, Math.min(90, Math.round(v ?? 0)));
}

function quantizeTwistByte(v?: number): number {
  return Math.max(0, Math.min(255, Math.round(((((v ?? 0) % 360) + 360) % 360) * (255 / 360))));
}

function quantizePressureU16(p?: number): number {
  const clamped = Number.isFinite(p) ? Math.max(0, Math.min(1, p as number)) : 0.5;
  return Math.round(clamped * 65535);
}

function quantizeWidthU16(w?: number): number {
  const clamped = Number.isFinite(w) ? Math.max(0.1, Math.min(2000, w as number)) : 1;
  return Math.max(1, Math.min(65535, Math.round(clamped * 16)));
}

/**
 * Light sub-pixel and collinear point thinning strictly for network STROKE_CHUNK emission.
 * Skips redundant micro-jitter points (`< 0.35 px` and `< 0.005` pressure delta) and strictly
 * collinear interior points (`< 0.2 px` perpendicular deviation) while always preserving
 * corners (`isCorner`) and the chunk's final endpoint.
 */
export function thinStrokeChunkPoints(
  points: ReadonlyArray<Point>,
  prevEmittedPoint?: Point | null
): Point[] {
  if (points.length === 0) return [];

  // Stage 1: Sub-pixel / redundant sample filter
  const stage1: Point[] = [];
  let lastKept: Point | null = prevEmittedPoint ?? null;

  for (let i = 0; i < points.length; i++) {
    const pt = points[i];
    if (!Number.isFinite(pt.x) || !Number.isFinite(pt.y)) continue;

    if (!lastKept || pt.isCorner) {
      stage1.push(pt);
      lastKept = pt;
      continue;
    }

    const dx = pt.x - lastKept.x;
    const dy = pt.y - lastKept.y;
    const distSq = dx * dx + dy * dy;
    const dp = Math.abs((pt.pressure ?? 0.5) - (lastKept.pressure ?? 0.5));
    const dw = Math.abs((pt.width ?? 1) - (lastKept.width ?? 1));
    const tiltChanged =
      Math.abs((pt.tiltX ?? 0) - (lastKept.tiltX ?? 0)) >= 2 ||
      Math.abs((pt.tiltY ?? 0) - (lastKept.tiltY ?? 0)) >= 2 ||
      Math.abs((pt.twist ?? 0) - (lastKept.twist ?? 0)) >= 4;

    if (
      distSq < THIN_MIN_DIST_SQ &&
      dp < THIN_MIN_PRESSURE_DELTA &&
      dw < THIN_MIN_WIDTH_DELTA &&
      !tiltChanged
    ) {
      continue;
    }

    stage1.push(pt);
    lastKept = pt;
  }

  if (stage1.length <= 2) return stage1;

  // Stage 2: Light collinear interior thinning (always preserves first and last points)
  const out: Point[] = [stage1[0]];
  for (let i = 1; i < stage1.length - 1; i++) {
    const a = out[out.length - 1];
    const b = stage1[i];
    const c = stage1[i + 1];

    if (b.isCorner) {
      out.push(b);
      continue;
    }

    const abx = b.x - a.x;
    const aby = b.y - a.y;
    const acx = c.x - a.x;
    const acy = c.y - a.y;
    const acLenSq = acx * acx + acy * acy;
    if (acLenSq <= 1e-6 || acLenSq > THIN_COLLINEAR_MAX_SEG_PX * THIN_COLLINEAR_MAX_SEG_PX) {
      out.push(b);
      continue;
    }

    const t = (abx * acx + aby * acy) / acLenSq;
    if (t <= 0 || t >= 1) {
      out.push(b);
      continue;
    }

    const cross = Math.abs(abx * acy - aby * acx);
    const perpDist = cross / Math.sqrt(acLenSq);
    const interpPressure = (a.pressure ?? 0.5) + ((c.pressure ?? 0.5) - (a.pressure ?? 0.5)) * t;
    const interpWidth = (a.width ?? 1) + ((c.width ?? 1) - (a.width ?? 1)) * t;
    const tiltDiff =
      Math.abs((b.tiltX ?? 0) - (a.tiltX ?? 0)) >= 2 ||
      Math.abs((b.tiltY ?? 0) - (a.tiltY ?? 0)) >= 2 ||
      Math.abs((b.twist ?? 0) - (a.twist ?? 0)) >= 4;

    if (
      perpDist < THIN_COLLINEAR_MAX_DEV_PX &&
      Math.abs((b.pressure ?? 0.5) - interpPressure) < THIN_MIN_PRESSURE_DELTA &&
      Math.abs((b.width ?? 1) - interpWidth) < THIN_MIN_WIDTH_DELTA &&
      !tiltDiff
    ) {
      continue;
    }

    out.push(b);
  }
  out.push(stage1[stage1.length - 1]);
  return out;
}

/**
 * Encodes a compact quantized/delta STROKE_CHUNK v2 payload:
 * `[sIdLen: u8, sId, pIdLen: u8, pId, pointCount: u16, points...]`
 * Each point:
 * - `flags: u8` (corner, absolute f32 vs i16 1/16px delta, optional tilt/twist, same-pressure, same-width)
 * - Position: anchor/jump `f32 x, f32 y` (8B) OR delta `i16 dx16, i16 dy16` (4B)
 * - Pressure (unless same): `u16` (0..65535)
 * - Width (unless same): `u16` (1/16 px)
 * - Tilt/twist (only when non-zero): `tiltX: i8, tiltY: i8, twist: u8` (3B)
 */
export function encodeStrokeChunkV2Payload(
  strokeId: string,
  peerId: string,
  points: ReadonlyArray<Point>
): Uint8Array | null {
  if (points.length === 0 || points.length > MAX_STROKE_CHUNK_POINTS) return null;
  const strokeIdBytes = sharedTextEncoder.encode(strokeId);
  const peerIdBytes = sharedTextEncoder.encode(peerId);
  if (
    strokeIdBytes.length === 0 ||
    strokeIdBytes.length > 255 ||
    peerIdBytes.length === 0 ||
    peerIdBytes.length > 255
  ) {
    return null;
  }

  // Worst-case size: 4 header + ids + points * (1 + 8 + 2 + 2 + 3 = 16)
  const maxBytes = 4 + strokeIdBytes.length + peerIdBytes.length + points.length * 16;
  const buf = new Uint8Array(maxBytes);
  const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);

  let offset = 0;
  buf[offset++] = strokeIdBytes.length;
  buf.set(strokeIdBytes, offset);
  offset += strokeIdBytes.length;

  buf[offset++] = peerIdBytes.length;
  buf.set(peerIdBytes, offset);
  offset += peerIdBytes.length;

  const countOffset = offset;
  offset += 2;

  let written = 0;
  let prevX = 0;
  let prevY = 0;
  let prevQPressure = -1;
  let prevQWidth = -1;

  for (let i = 0; i < points.length; i++) {
    const pt = points[i];
    if (!Number.isFinite(pt.x) || !Number.isFinite(pt.y)) continue;

    const tx = quantizeTilt(pt.tiltX);
    const ty = quantizeTilt(pt.tiltY);
    const tw = quantizeTwistByte(pt.twist);
    const hasTiltTwist = tx !== 0 || ty !== 0 || tw !== 0;
    const qPressure = quantizePressureU16(pt.pressure);
    const qWidth = quantizeWidthU16(pt.width);

    let isAbsolute = written === 0;
    let dx16 = 0;
    let dy16 = 0;
    if (!isAbsolute) {
      dx16 = Math.round((pt.x - prevX) * 16);
      dy16 = Math.round((pt.y - prevY) * 16);
      if (dx16 < -32768 || dx16 > 32767 || dy16 < -32768 || dy16 > 32767) {
        isAbsolute = true;
      }
    }

    const pressureSame = written > 0 && qPressure === prevQPressure;
    const widthSame = written > 0 && qWidth === prevQWidth;

    let flags = 0;
    if (pt.isCorner) flags |= CHUNK_PT_IS_CORNER;
    if (isAbsolute) flags |= CHUNK_PT_ABSOLUTE;
    if (hasTiltTwist) flags |= CHUNK_PT_HAS_TILT_TWIST;
    if (pressureSame) flags |= CHUNK_PT_PRESSURE_SAME;
    if (widthSame) flags |= CHUNK_PT_WIDTH_SAME;

    buf[offset++] = flags;
    if (isAbsolute) {
      view.setFloat32(offset, pt.x, true);
      view.setFloat32(offset + 4, pt.y, true);
      offset += 8;
      // Track exact f32-reconstructed anchor so delta chain never drifts
      prevX = Math.fround(pt.x);
      prevY = Math.fround(pt.y);
    } else {
      view.setInt16(offset, dx16, true);
      view.setInt16(offset + 2, dy16, true);
      offset += 4;
      prevX += dx16 / 16;
      prevY += dy16 / 16;
    }

    if (!pressureSame) {
      view.setUint16(offset, qPressure, true);
      offset += 2;
      prevQPressure = qPressure;
    }
    if (!widthSame) {
      view.setUint16(offset, qWidth, true);
      offset += 2;
      prevQWidth = qWidth;
    }
    if (hasTiltTwist) {
      view.setInt8(offset, tx);
      view.setInt8(offset + 1, ty);
      view.setUint8(offset + 2, tw);
      offset += 3;
    }
    written += 1;
  }

  if (written === 0) return null;
  view.setUint16(countOffset, written, true);
  return buf.subarray(0, offset);
}

/**
 * Strictly validates and decodes a compact STROKE_CHUNK v2 payload.
 * Returns null on truncated/oversized buffers, missing initial anchor, or corrupt coordinates.
 */
export function decodeStrokeChunkV2Payload(payloadBytes: Uint8Array): StrokeChunkMessage | null {
  const len = payloadBytes.byteLength;
  if (len < 6) return null;
  const view = new DataView(payloadBytes.buffer, payloadBytes.byteOffset, len);

  let offset = 0;
  const sIdLen = payloadBytes[offset++];
  if (sIdLen === 0 || offset + sIdLen + 3 > len) return null;
  const strokeId = sharedTextDecoder.decode(payloadBytes.subarray(offset, offset + sIdLen));
  offset += sIdLen;

  const pIdLen = payloadBytes[offset++];
  if (pIdLen === 0 || offset + pIdLen + 2 > len) return null;
  const peerId = sharedTextDecoder.decode(payloadBytes.subarray(offset, offset + pIdLen));
  offset += pIdLen;

  const pointCount = view.getUint16(offset, true);
  offset += 2;
  if (pointCount === 0 || pointCount > MAX_STROKE_CHUNK_POINTS) return null;

  const points: Point[] = [];
  let prevX = 0;
  let prevY = 0;
  let prevPressure = 0.5;
  let prevWidth = 1;

  for (let i = 0; i < pointCount; i++) {
    if (offset >= len) return null;
    const flags = payloadBytes[offset++];
    const isCorner = (flags & CHUNK_PT_IS_CORNER) !== 0;
    const isAbsolute = (flags & CHUNK_PT_ABSOLUTE) !== 0;
    const hasTiltTwist = (flags & CHUNK_PT_HAS_TILT_TWIST) !== 0;
    const pressureSame = (flags & CHUNK_PT_PRESSURE_SAME) !== 0;
    const widthSame = (flags & CHUNK_PT_WIDTH_SAME) !== 0;

    // First point must establish an absolute f32 anchor and initial pressure/width
    if (i === 0 && (!isAbsolute || pressureSame || widthSame)) {
      return null;
    }

    let x: number;
    let y: number;
    if (isAbsolute) {
      if (offset + 8 > len) return null;
      x = view.getFloat32(offset, true);
      y = view.getFloat32(offset + 4, true);
      offset += 8;
      if (!Number.isFinite(x) || !Number.isFinite(y)) return null;
      prevX = x;
      prevY = y;
    } else {
      if (offset + 4 > len) return null;
      const dx16 = view.getInt16(offset, true);
      const dy16 = view.getInt16(offset + 2, true);
      offset += 4;
      x = prevX + dx16 / 16;
      y = prevY + dy16 / 16;
      prevX = x;
      prevY = y;
    }

    let pressure = prevPressure;
    if (!pressureSame) {
      if (offset + 2 > len) return null;
      pressure = view.getUint16(offset, true) / 65535;
      offset += 2;
      prevPressure = pressure;
    }

    let width = prevWidth;
    if (!widthSame) {
      if (offset + 2 > len) return null;
      width = Math.max(0.1, Math.min(2000, view.getUint16(offset, true) / 16));
      offset += 2;
      prevWidth = width;
    }

    let tiltX = 0;
    let tiltY = 0;
    let twist = 0;
    if (hasTiltTwist) {
      if (offset + 3 > len) return null;
      tiltX = view.getInt8(offset);
      tiltY = view.getInt8(offset + 1);
      twist = (view.getUint8(offset + 2) * 360) / 255;
      offset += 3;
    }

    points.push({
      x,
      y,
      pressure,
      width,
      tiltX,
      tiltY,
      twist,
      isCorner,
    });
  }

  // Reject trailing unparsed garbage bytes
  if (offset !== len || points.length === 0) return null;

  return {
    type: 'STROKE_CHUNK',
    senderId: peerId,
    strokeId,
    peerId,
    points,
  };
}

function cloneTileBufferForAsyncSend(tile: WireTilePayload): WireTilePayload {
  if (tile.data === null) {
    return { ...tile, data: null };
  }
  const copy = new Uint8Array(tile.data.byteLength);
  copy.set(tile.data);
  return {
    ...tile,
    data: copy,
  };
}

function peekTileDeltaHeader(
  buf: ArrayBuffer
): {
  layerId: string;
  tilePacket: Uint8Array;
  tileKey: string;
  serverSeq: number;
} | null {
  if (buf.byteLength < 11 || buf.byteLength > MAX_BINARY_PACKET_BYTES) return null;
  const view = new DataView(buf);
  if (view.getUint8(0) !== BINARY_MAGIC_0 || view.getUint8(1) !== BINARY_MAGIC_1) return null;
  if (view.getUint8(2) !== CODE_TILE_DELTA) return null;

  const serverSeq = view.getUint32(3, true);
  const payloadLen = view.getUint32(7, true);
  if (payloadLen > MAX_BINARY_PACKET_BYTES || 11 + payloadLen > buf.byteLength || payloadLen < 2) {
    return null;
  }

  const payloadBytes = new Uint8Array(buf, 11, payloadLen);
  const pView = new DataView(buf, 11, payloadLen);
  const layerIdLen = pView.getUint16(0, true);
  if (
    layerIdLen === 0 ||
    layerIdLen > 256 ||
    2 + layerIdLen + TILE_PACKET_HEADER_BYTES > payloadLen
  ) {
    return null;
  }

  const layerId = sharedTextDecoder.decode(payloadBytes.subarray(2, 2 + layerIdLen));
  const tilePacket = payloadBytes.subarray(2 + layerIdLen);
  const tView = new DataView(tilePacket.buffer, tilePacket.byteOffset, tilePacket.byteLength);
  const tileX = tView.getInt32(0, true);
  const tileY = tView.getInt32(4, true);
  const formatCode = tView.getUint8(8);
  const codec = tView.getUint8(13);

  if (
    tileX < 0 ||
    tileY < 0 ||
    tileX >= MAX_TILE_COORD ||
    tileY >= MAX_TILE_COORD ||
    (formatCode !== 1 && formatCode !== 2 && formatCode !== 4) ||
    codec < TILE_CODEC_EMPTY ||
    codec > TILE_CODEC_SUBRECT_LZ4
  ) {
    return null;
  }

  return {
    layerId,
    tilePacket,
    tileKey: `${layerId}:${tileX}:${tileY}`,
    serverSeq,
  };
}

const TOOL_TYPES_LIST: ToolType[] = [
  'brush',
  'eraser',
  'pipette',
  'transform',
  'select-rect',
  'select-lasso',
  'select-wand',
  'select-pen',
  'select-eraser',
  'fill',
  'text',
  'frame',
  'balloon',
  'vector-edit',
  'liquify',
  'shape',
  'object',
  '3d',
  'gradient',
  'retouch',
  'pen',
  'decoration',
];

export const DEEP_LINK_SCHEME = 'inkstudio:';

export interface ParsedInviteLink {
  roomName: string;
  host: string;
  port: number;
  url: string;
  token?: string;
  isSecure: boolean;
  /** Optional custom WebSocket path (defaults to "/ws" when omitted). */
  wsPath?: string;
}

export function parseInviteUrl(raw: string): ParsedInviteLink | null {
  const trimmed = raw.trim();
  if (!trimmed) return null;

  let parsedUrl: URL;
  try {
    parsedUrl = new URL(trimmed);
  } catch {
    return null;
  }

  if (parsedUrl.protocol === 'http:' || parsedUrl.protocol === 'https:') {
    const hostname = parsedUrl.hostname.trim();
    if (!hostname) return null;
    const isTryCloudflare =
      parsedUrl.protocol === 'https:' && hostname.toLowerCase().endsWith('.trycloudflare.com');
    const roomParam = parsedUrl.searchParams.get('room');
    if (!roomParam && !isTryCloudflare) return null;
    const isSecure = parsedUrl.protocol === 'https:';
    const port = parsedUrl.port ? parseInt(parsedUrl.port, 10) : isSecure ? 443 : 80;
    if (!Number.isFinite(port) || port <= 0 || port > 65535) return null;
    const token = parsedUrl.searchParams.get('token') || undefined;
    return {
      roomName: (roomParam || 'Studio').trim() || 'Studio',
      host: hostname,
      port,
      url: trimmed,
      token,
      isSecure,
    };
  }

  if (parsedUrl.protocol === 'ws:' || parsedUrl.protocol === 'wss:') {
    const hostname = parsedUrl.hostname.trim();
    if (!hostname) return null;
    const isSecure = parsedUrl.protocol === 'wss:';
    const port = parsedUrl.port ? parseInt(parsedUrl.port, 10) : isSecure ? 443 : 80;
    if (!Number.isFinite(port) || port <= 0 || port > 65535) return null;
    const roomName = (parsedUrl.searchParams.get('room') || 'Studio').trim() || 'Studio';
    const token = parsedUrl.searchParams.get('token') || undefined;
    const pathname = parsedUrl.pathname;
    const wsPath = pathname && pathname !== '/' && pathname !== '/ws' ? pathname : undefined;
    return {
      roomName,
      host: hostname,
      port,
      url: trimmed,
      token,
      isSecure,
      ...(wsPath ? { wsPath } : {}),
    };
  }

  if (parsedUrl.protocol === DEEP_LINK_SCHEME) {
    const host = parsedUrl.searchParams.get('host');
    const portParam = parsedUrl.searchParams.get('port');
    if (!host) return null;
    const protoParam = parsedUrl.searchParams.get('protocol');
    const isSecure =
      protoParam === 'https' ||
      portParam === '443' ||
      host.toLowerCase().endsWith('.trycloudflare.com');
    const port = portParam ? parseInt(portParam, 10) : isSecure ? 443 : 30303;
    if (!Number.isFinite(port) || port <= 0 || port > 65535) return null;
    const roomName = parsedUrl.searchParams.get('room') || 'Studio';
    const token = parsedUrl.searchParams.get('token') || undefined;
    return {
      roomName,
      host,
      port,
      url: trimmed,
      token,
      isSecure,
    };
  }

  return null;
}

export interface ParsedP2pInvite {
  kind: 'p2p';
  roomCode: string;
  roomSecret: string;
  joinCode: string;
  roomName: string;
  signalingUrl?: string;
  url: string;
}

export interface ParsedWsInvite extends ParsedInviteLink {
  kind: 'ws';
}

export type ParsedCollabTarget = ParsedP2pInvite | ParsedWsInvite;

const P2P_SHORT_CODE_REGEX = /^INK-([A-Z0-9]{4,8})(?:[-:\s]+([A-Z0-9]{4,16}))?$/i;

function sanitizeSignalingUrlParam(raw: string | null): string | undefined {
  if (!raw) return undefined;
  const trimmed = raw.trim();
  if (!trimmed) return undefined;
  try {
    const parsed = new URL(trimmed);
    if (
      parsed.protocol === 'wss:' ||
      parsed.protocol === 'ws:' ||
      parsed.protocol === 'https:' ||
      parsed.protocol === 'http:'
    ) {
      return trimmed;
    }
  } catch {
    // ignore invalid signaling URL param
  }
  return undefined;
}

function splitEmbeddedP2pCode(rawCode: string, explicitSecret?: string | null): {
  roomCode: string;
  roomSecret: string;
} | null {
  const match = rawCode.trim().match(P2P_SHORT_CODE_REGEX);
  if (!match) return null;
  const roomCode = normalizeRoomCode(`INK-${match[1]}`);
  const roomSecret = normalizeRoomSecret(explicitSecret || match[2] || '');
  return { roomCode, roomSecret };
}

/**
 * Auto-detects whether user input is:
 *  - a short P2P room code (`INK-7429` or `INK-7429-K8P2M9`)
 *  - a P2P invite link (`https://.../?p2p=INK-7429&secret=...` or `inkstudio://p2p?code=...`)
 *  - a WebSocket / Cloudflare / LAN invite link (`wss://...`, `ws://...`, `https://...trycloudflare.com`, `http://.../?room=...`)
 */
export function parseCollabTarget(raw: string): ParsedCollabTarget | null {
  const trimmed = raw.trim();
  if (!trimmed) return null;

  // 1. Bare or combined short P2P room code (e.g. INK-7429 or INK-7429-K8P2M9)
  const directCode = splitEmbeddedP2pCode(trimmed);
  if (directCode) {
    const joinCode = directCode.roomSecret
      ? `${directCode.roomCode}-${directCode.roomSecret}`
      : directCode.roomCode;
    return {
      kind: 'p2p',
      roomCode: directCode.roomCode,
      roomSecret: directCode.roomSecret,
      joinCode,
      roomName: directCode.roomCode,
      url: trimmed,
    };
  }

  // 2. P2P URL (`https://.../?p2p=INK-7429&secret=...` or `inkstudio://p2p?code=INK-7429&secret=...`)
  try {
    const parsedUrl = new URL(trimmed);
    if (parsedUrl.protocol === 'http:' || parsedUrl.protocol === 'https:') {
      const p2pParam = parsedUrl.searchParams.get('p2p');
      if (p2pParam) {
        const split = splitEmbeddedP2pCode(
          p2pParam,
          parsedUrl.searchParams.get('secret') || parsedUrl.searchParams.get('token')
        );
        if (split) {
          const roomName =
            (parsedUrl.searchParams.get('room') || split.roomCode).trim() || split.roomCode;
          const signalingUrl = sanitizeSignalingUrlParam(parsedUrl.searchParams.get('sig'));
          return {
            kind: 'p2p',
            roomCode: split.roomCode,
            roomSecret: split.roomSecret,
            joinCode: split.roomSecret ? `${split.roomCode}-${split.roomSecret}` : split.roomCode,
            roomName,
            ...(signalingUrl ? { signalingUrl } : {}),
            url: trimmed,
          };
        }
      }
    } else if (parsedUrl.protocol === DEEP_LINK_SCHEME) {
      const hostOrPath = `${parsedUrl.hostname}${parsedUrl.pathname}`.toLowerCase();
      const codeParam = parsedUrl.searchParams.get('code') || parsedUrl.searchParams.get('p2p');
      if (codeParam && (hostOrPath.includes('p2p') || parsedUrl.searchParams.has('code'))) {
        const split = splitEmbeddedP2pCode(
          codeParam,
          parsedUrl.searchParams.get('secret') || parsedUrl.searchParams.get('token')
        );
        if (split) {
          const roomName =
            (parsedUrl.searchParams.get('room') || split.roomCode).trim() || split.roomCode;
          const signalingUrl = sanitizeSignalingUrlParam(parsedUrl.searchParams.get('sig'));
          return {
            kind: 'p2p',
            roomCode: split.roomCode,
            roomSecret: split.roomSecret,
            joinCode: split.roomSecret ? `${split.roomCode}-${split.roomSecret}` : split.roomCode,
            roomName,
            ...(signalingUrl ? { signalingUrl } : {}),
            url: trimmed,
          };
        }
      }
    }
  } catch {
    // Not a URL — fall through
  }

  // 3. WebSocket / Cloudflare / LAN / inkstudio://join invite URL
  const wsInvite = parseInviteUrl(trimmed);
  if (wsInvite) {
    return {
      kind: 'ws',
      ...wsInvite,
    };
  }

  return null;
}

export function buildP2pShareUrl(
  roomCode: string,
  roomSecret: string,
  roomName: string,
  customSignalingUrl?: string
): string {
  const params = new URLSearchParams();
  const sig = sanitizeSignalingUrlParam(customSignalingUrl || null);

  const isWebHttpOrigin =
    typeof window !== 'undefined' &&
    (window.location.protocol === 'http:' || window.location.protocol === 'https:') &&
    window.location.hostname !== 'tauri.localhost' &&
    window.location.hostname !== '';

  if (isWebHttpOrigin) {
    params.set('p2p', normalizeRoomCode(roomCode));
    if (roomSecret) params.set('secret', normalizeRoomSecret(roomSecret));
    if (roomName) params.set('room', roomName);
    if (sig) params.set('sig', sig);
    return `${window.location.origin}/?${params.toString()}`;
  }

  params.set('code', normalizeRoomCode(roomCode));
  if (roomSecret) params.set('secret', normalizeRoomSecret(roomSecret));
  if (roomName) params.set('room', roomName);
  if (sig) params.set('sig', sig);
  return `${DEEP_LINK_SCHEME}//p2p?${params.toString()}`;
}

function sanitizeRemoteBrushSettings(raw: unknown): BrushSettings | null {
  if (!raw || typeof raw !== 'object') return null;
  const bs = raw as BrushSettings;
  const size = Number.isFinite(bs.size) ? Math.max(0.5, Math.min(2000, bs.size)) : 8;
  const opacity = Number.isFinite(bs.opacity) ? Math.max(0, Math.min(1, bs.opacity)) : 1;
  const flow = Number.isFinite(bs.flow) ? Math.max(0.01, Math.min(1, bs.flow)) : 1;
  const spacing = Number.isFinite(bs.spacing) ? Math.max(0.01, Math.min(2, bs.spacing)) : 0.1;
  const dynamics = bs.dynamics
    ? {
        ...bs.dynamics,
        count: Number.isFinite(bs.dynamics.count)
          ? Math.max(1, Math.min(16, Math.round(bs.dynamics.count)))
          : 1,
      }
    : undefined;
  const spray = bs.spray
    ? {
        ...bs.spray,
        density: Number.isFinite(bs.spray.density)
          ? Math.max(1, Math.min(64, Math.round(bs.spray.density)))
          : 12,
        size: Number.isFinite(bs.spray.size)
          ? Math.max(1, Math.min(200, bs.spray.size))
          : 3,
      }
    : undefined;
  const {
    customTipDataUrl: _tipUrl,
    customTipImage: _tipImg,
    dualTipDataUrl: _dualUrl,
    dualTipImage: _dualImg,
    dualSubTips: _dualSubTips,
    dualSubTipImages: _dualSubImgs,
    dualBrushConfig: rawDualCfg,
    paperTexture: _paperUrl,
    paperTextureImage: _paperImg,
    subTips: _subTips,
    subTipImages: _subImgs,
    ...rest
  } = bs;
  let cleanDualCfg: BrushSettings['dualBrushConfig'] = undefined;
  if (rawDualCfg && typeof rawDualCfg === 'object') {
    const {
      tipDataUrl: _dUrl,
      tipImage: _dImg,
      subTips: _dSubTips,
      subTipImages: _dSubImgs,
      ...restDual
    } = rawDualCfg;
    cleanDualCfg = restDual;
  }
  return {
    ...rest,
    ...(cleanDualCfg ? { dualBrushConfig: cleanDualCfg } : {}),
    size,
    opacity,
    flow,
    spacing,
    dynamics,
    spray,
  };
}

function isValidRemotePoint(pt: unknown): pt is Point {
  if (!pt || typeof pt !== 'object') return false;
  const p = pt as Point;
  return Number.isFinite(p.x) && Number.isFinite(p.y);
}

/**
 * Strictly validates and sanitizes untrusted remote JSON messages before dispatching.
 * Returns null to drop malformed or malicious payloads.
 */
export function sanitizeIncomingJsonMessage(raw: unknown): MultiplayerMessage | null {
  if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
  const msg = raw as Record<string, unknown>;
  if (typeof msg.type !== 'string') return null;

  const senderId =
    typeof msg.senderId === 'string' || typeof msg.senderId === 'number'
      ? msg.senderId
      : undefined;
  const seq =
    typeof msg.seq === 'number' && Number.isSafeInteger(msg.seq) && msg.seq >= 0
      ? msg.seq
      : undefined;

  const sanitized = sanitizeIncomingJsonBody(msg, senderId);
  if (sanitized && seq !== undefined) {
    sanitized.seq = seq;
  }
  return sanitized;
}

function sanitizeIncomingJsonBody(
  msg: Record<string, unknown>,
  senderId: string | number | undefined
): MultiplayerMessage | null {
  switch (msg.type) {
    case 'LAYER_ADD': {
      const layerItem = sanitizeWireLayer(msg.layerItem);
      if (!layerItem) return null;
      const insertIndex =
        typeof msg.insertIndex === 'number' && Number.isInteger(msg.insertIndex) && msg.insertIndex >= 0
          ? msg.insertIndex
          : undefined;
      return {
        type: 'LAYER_ADD',
        senderId,
        layerId: layerItem.id,
        layerItem,
        insertIndex,
      };
    }

    case 'LAYER_DELETE':
    case 'LAYER_CLEAR': {
      if (typeof msg.layerId !== 'string' || !msg.layerId || msg.layerId.length > 256) return null;
      return {
        type: msg.type,
        senderId,
        layerId: msg.layerId,
      };
    }

    case 'LAYER_RENAME': {
      if (
        typeof msg.layerId !== 'string' ||
        !msg.layerId ||
        msg.layerId.length > 256 ||
        typeof msg.newName !== 'string'
      ) {
        return null;
      }
      return {
        type: 'LAYER_RENAME',
        senderId,
        layerId: msg.layerId,
        newName: msg.newName.slice(0, 256),
      };
    }

    case 'LAYER_VISIBILITY': {
      if (
        typeof msg.layerId !== 'string' ||
        !msg.layerId ||
        msg.layerId.length > 256 ||
        typeof msg.visible !== 'boolean'
      ) {
        return null;
      }
      return {
        type: 'LAYER_VISIBILITY',
        senderId,
        layerId: msg.layerId,
        visible: msg.visible,
      };
    }

    case 'LAYER_OPACITY': {
      if (
        typeof msg.layerId !== 'string' ||
        !msg.layerId ||
        msg.layerId.length > 256 ||
        typeof msg.opacity !== 'number' ||
        !Number.isFinite(msg.opacity)
      ) {
        return null;
      }
      return {
        type: 'LAYER_OPACITY',
        senderId,
        layerId: msg.layerId,
        opacity: Math.max(0, Math.min(1, msg.opacity)),
      };
    }

    case 'LAYER_UPDATE': {
      if (typeof msg.layerId !== 'string' || !msg.layerId || msg.layerId.length > 256) return null;
      const patch = sanitizeWireLayerPatch(msg.patch);
      const clearedFields = sanitizeClearedFields(msg.clearedFields);
      if (Object.keys(patch).length === 0 && clearedFields.length === 0) return null;
      const lamport =
        typeof msg.lamport === 'number' && Number.isFinite(msg.lamport) ? msg.lamport : undefined;
      return {
        type: 'LAYER_UPDATE',
        senderId,
        layerId: msg.layerId,
        patch,
        clearedFields: clearedFields.length > 0 ? clearedFields : undefined,
        lamport,
      };
    }

    case 'LAYER_TREE_SYNC': {
      const layers = sanitizeWireLayerTree(msg.layers);
      if (!layers) return null;
      const lamport =
        typeof msg.lamport === 'number' && Number.isFinite(msg.lamport) ? msg.lamport : 0;
      const dirtyTileLayerIds = Array.isArray(msg.dirtyTileLayerIds)
        ? msg.dirtyTileLayerIds
            .filter((x): x is string => typeof x === 'string' && x.length > 0 && x.length <= 256)
            .slice(0, 512)
        : undefined;
      const removedLayerIds = Array.isArray(msg.removedLayerIds)
        ? msg.removedLayerIds
            .filter((x): x is string => typeof x === 'string' && x.length > 0 && x.length <= 256)
            .slice(0, 512)
        : undefined;
      return {
        type: 'LAYER_TREE_SYNC',
        senderId,
        layers,
        lamport,
        dirtyTileLayerIds,
        removedLayerIds,
      };
    }

    case 'PERSPECTIVE_RULER_SYNC': {
      const perspectiveRuler = sanitizePerspectiveRuler(msg.perspectiveRuler);
      if (perspectiveRuler === undefined) return null;
      const lamport =
        typeof msg.lamport === 'number' && Number.isFinite(msg.lamport) ? msg.lamport : undefined;
      return {
        type: 'PERSPECTIVE_RULER_SYNC',
        senderId,
        perspectiveRuler,
        lamport,
      };
    }

    case 'STRAIGHT_RULER_SYNC': {
      const straightRuler = sanitizeStraightRuler(msg.straightRuler);
      if (straightRuler === undefined) return null;
      const lamport =
        typeof msg.lamport === 'number' && Number.isFinite(msg.lamport) ? msg.lamport : undefined;
      return {
        type: 'STRAIGHT_RULER_SYNC',
        senderId,
        straightRuler,
        lamport,
      };
    }

    case 'ANIMATION_SYNC': {
      const animationTimeline = sanitizeAnimationTimeline(msg.animationTimeline);
      if (animationTimeline === undefined) return null;
      const lamport =
        typeof msg.lamport === 'number' && Number.isFinite(msg.lamport) ? msg.lamport : undefined;
      return {
        type: 'ANIMATION_SYNC',
        senderId,
        animationTimeline,
        lamport,
      };
    }

    case 'CANVAS_RESIZE': {
      const safe = sanitizeCanvasResize(msg);
      if (!safe) return null;
      const lamport =
        typeof msg.lamport === 'number' && Number.isFinite(msg.lamport) ? msg.lamport : undefined;
      return {
        type: 'CANVAS_RESIZE',
        senderId,
        dimensions: safe.dimensions,
        options: safe.options,
        lamport,
      };
    }

    case 'DOC_SYNC_RESPONSE': {
      const layers = sanitizeWireLayerTree(msg.layers);
      const d = msg.dimensions as Record<string, unknown> | undefined;
      if (!layers || !d || typeof d !== 'object') return null;
      if (
        typeof d.width !== 'number' ||
        !Number.isFinite(d.width) ||
        d.width < 1 ||
        d.width > MAX_SYNC_CANVAS_DIM ||
        typeof d.height !== 'number' ||
        !Number.isFinite(d.height) ||
        d.height < 1 ||
        d.height > MAX_SYNC_CANVAS_DIM
      ) {
        return null;
      }
      const width = Math.round(d.width);
      const height = Math.round(d.height);
      const dpi =
        typeof d.dpi === 'number' && Number.isFinite(d.dpi)
          ? Math.max(36, Math.min(2400, Math.round(d.dpi)))
          : undefined;
      const colorMode =
        msg.colorMode === 'color' || msg.colorMode === 'grayscale' || msg.colorMode === 'monochrome'
          ? msg.colorMode
          : 'color';

      const perspectiveRuler =
        msg.perspectiveRuler !== undefined
          ? sanitizePerspectiveRuler(msg.perspectiveRuler) ?? null
          : null;
      const straightRuler =
        msg.straightRuler !== undefined ? sanitizeStraightRuler(msg.straightRuler) ?? null : null;
      const animationTimeline =
        msg.animationTimeline !== undefined
          ? sanitizeAnimationTimeline(msg.animationTimeline) ?? null
          : null;

      return {
        type: 'DOC_SYNC_RESPONSE',
        senderId,
        targetPeerId: (msg.targetPeerId as string | number) ?? '',
        roomName: typeof msg.roomName === 'string' ? msg.roomName.slice(0, 128) : undefined,
        assignedLayerId:
          typeof msg.assignedLayerId === 'string' ? msg.assignedLayerId.slice(0, 256) : undefined,
        dimensions: { width, height, dpi },
        colorMode,
        layers,
        perspectiveRuler,
        straightRuler,
        animationTimeline,
      } as DocSyncResponseMessage;
    }

    case 'PEER_ROLE_UPDATE': {
      const targetPeerId =
        typeof msg.targetPeerId === 'string' || typeof msg.targetPeerId === 'number'
          ? String(msg.targetPeerId).trim().slice(0, 128)
          : '';
      if (!targetPeerId) return null;
      if (msg.role !== 'host' && msg.role !== 'editor' && msg.role !== 'viewer') return null;
      return {
        type: 'PEER_ROLE_UPDATE',
        senderId,
        targetPeerId,
        role: msg.role,
      };
    }

    case 'PEER_KICK':
    case 'PEER_BAN': {
      const targetPeerId =
        typeof msg.targetPeerId === 'string' || typeof msg.targetPeerId === 'number'
          ? String(msg.targetPeerId).trim().slice(0, 128)
          : '';
      if (!targetPeerId) return null;
      const reason =
        typeof msg.reason === 'string' && msg.reason.trim()
          ? msg.reason.trim().slice(0, 256)
          : undefined;
      return {
        type: msg.type,
        senderId,
        targetPeerId,
        ...(reason ? { reason } : {}),
      };
    }

    case 'PEER_UNBAN': {
      const targetPeerId =
        typeof msg.targetPeerId === 'string' || typeof msg.targetPeerId === 'number'
          ? String(msg.targetPeerId).trim().slice(0, 128)
          : '';
      if (!targetPeerId) return null;
      return {
        type: 'PEER_UNBAN',
        senderId,
        targetPeerId,
      };
    }

    case 'ACCESS_DENIED': {
      const allowedCodes = new Set<AccessDeniedCode>([
        'BANNED',
        'KICKED',
        'VIEWER_READONLY',
        'LAYER_LOCKED',
        'NOT_OWNER',
        'FORBIDDEN',
      ]);
      const code: AccessDeniedCode = allowedCodes.has(msg.code as AccessDeniedCode)
        ? (msg.code as AccessDeniedCode)
        : 'FORBIDDEN';
      const reason =
        typeof msg.reason === 'string' && msg.reason.trim()
          ? msg.reason.trim().slice(0, 256)
          : 'Action not permitted';
      const targetPeerId =
        typeof msg.targetPeerId === 'string' || typeof msg.targetPeerId === 'number'
          ? String(msg.targetPeerId).trim().slice(0, 128)
          : undefined;
      return {
        type: 'ACCESS_DENIED',
        senderId,
        ...(targetPeerId ? { targetPeerId } : {}),
        code,
        reason,
      };
    }

    case 'CHAT_MESSAGE': {
      if (typeof msg.text !== 'string') return null;
      const text = msg.text.replace(/\r\n/g, '\n').trim().slice(0, MAX_CHAT_TEXT_LEN);
      if (!text) return null;
      const id =
        typeof msg.id === 'string' && msg.id.trim()
          ? msg.id.trim().slice(0, 128)
          : `chat-${Date.now()}-${Math.random().toString(36).slice(2, 7)}`;
      const senderName =
        typeof msg.senderName === 'string' && msg.senderName.trim()
          ? msg.senderName.trim().slice(0, 64)
          : 'Peer';
      const senderColor =
        typeof msg.senderColor === 'string' && /^#[0-9a-fA-F]{3,8}$/.test(msg.senderColor.trim())
          ? msg.senderColor.trim()
          : '#38bdf8';
      const timestamp =
        typeof msg.timestamp === 'number' && Number.isFinite(msg.timestamp) && msg.timestamp > 0
          ? msg.timestamp
          : Date.now();
      return {
        type: 'CHAT_MESSAGE',
        senderId,
        id,
        senderName,
        senderColor,
        text,
        timestamp,
      } as ChatMessage;
    }

    case 'CAMERA_SYNC_REQUEST': {
      const targetPeerId =
        typeof msg.targetPeerId === 'string' || typeof msg.targetPeerId === 'number'
          ? String(msg.targetPeerId).trim().slice(0, 128)
          : '';
      if (!targetPeerId) return null;
      return {
        type: 'CAMERA_SYNC_REQUEST',
        senderId,
        targetPeerId,
      } as CameraSyncRequestMessage;
    }

    case 'BRUSH_REQUEST': {
      const targetPeerId =
        typeof msg.targetPeerId === 'string' || typeof msg.targetPeerId === 'number'
          ? String(msg.targetPeerId).trim().slice(0, 128)
          : '';
      if (!targetPeerId) return null;
      return {
        type: 'BRUSH_REQUEST',
        senderId,
        targetPeerId,
      } as BrushRequestMessage;
    }

    case 'BRUSH_SHARE': {
      const safeSettings = sanitizeRemoteBrushSettings(msg.brushSettings);
      if (!safeSettings) return null;
      const peerId =
        typeof msg.peerId === 'string' || typeof msg.peerId === 'number'
          ? msg.peerId
          : senderId ?? '';
      if (peerId === '' || peerId === undefined) return null;
      const peerName =
        typeof msg.peerName === 'string' && msg.peerName.trim()
          ? msg.peerName.trim().slice(0, 64)
          : 'Peer';
      const brushName =
        typeof msg.brushName === 'string' && msg.brushName.trim()
          ? msg.brushName.trim().slice(0, 80)
          : 'Brush';
      const tool: 'brush' | 'decoration' =
        msg.tool === 'decoration' ? 'decoration' : 'brush';
      const targetPeerId =
        typeof msg.targetPeerId === 'string' || typeof msg.targetPeerId === 'number'
          ? String(msg.targetPeerId).trim().slice(0, 128)
          : undefined;
      return {
        type: 'BRUSH_SHARE',
        senderId: senderId ?? peerId,
        peerId,
        peerName,
        brushName,
        tool,
        brushSettings: safeSettings,
        brushAssetRefs: sanitizeBrushAssetRefs(msg.brushAssetRefs),
        ...(targetPeerId ? { targetPeerId } : {}),
        ...(msg.explicit ? { explicit: true } : {}),
      } as BrushShareMessage;
    }

    case 'STATE_CHECKSUM_AUDIT': {
      const auditSeq =
        typeof msg.auditSeq === 'number' && Number.isSafeInteger(msg.auditSeq) && msg.auditSeq >= 0
          ? msg.auditSeq
          : 0;
      const docHash =
        typeof msg.docHash === 'number' && Number.isFinite(msg.docHash)
          ? msg.docHash >>> 0
          : null;
      if (docHash === null || !Array.isArray(msg.layers)) return null;

      const layers: LayerChecksumEntry[] = [];
      const limit = Math.min(msg.layers.length, 512);
      for (let i = 0; i < limit; i++) {
        const rawEntry = msg.layers[i] as Record<string, unknown> | null;
        if (!rawEntry || typeof rawEntry !== 'object') continue;
        if (typeof rawEntry.layerId !== 'string' || !rawEntry.layerId || rawEntry.layerId.length > 256) {
          continue;
        }
        if (typeof rawEntry.hash !== 'number' || !Number.isFinite(rawEntry.hash)) continue;
        const tileCount =
          typeof rawEntry.tileCount === 'number' &&
          Number.isInteger(rawEntry.tileCount) &&
          rawEntry.tileCount >= 0 &&
          rawEntry.tileCount <= 65536
            ? rawEntry.tileCount
            : 0;

        let tileDigests: Record<string, number> | undefined;
        if (rawEntry.tileDigests && typeof rawEntry.tileDigests === 'object' && !Array.isArray(rawEntry.tileDigests)) {
          const digestsObj = rawEntry.tileDigests as Record<string, unknown>;
          const keys = Object.keys(digestsObj);
          if (keys.length <= 512) {
            const cleanDigests: Record<string, number> = {};
            let count = 0;
            for (let k = 0; k < keys.length; k++) {
              const coord = keys[k];
              if (!/^\d{1,4}:\d{1,4}$/.test(coord)) continue;
              const val = digestsObj[coord];
              if (typeof val === 'number' && Number.isFinite(val)) {
                cleanDigests[coord] = val >>> 0;
                count += 1;
              }
            }
            if (count > 0) tileDigests = cleanDigests;
          }
        }

        layers.push({
          layerId: rawEntry.layerId,
          hash: rawEntry.hash >>> 0,
          tileCount,
          ...(tileDigests ? { tileDigests } : {}),
        });
      }

      const targetPeerId =
        typeof msg.targetPeerId === 'string' || typeof msg.targetPeerId === 'number'
          ? String(msg.targetPeerId).trim().slice(0, 128)
          : undefined;
      return {
        type: 'STATE_CHECKSUM_AUDIT',
        senderId,
        auditSeq,
        docHash,
        layers,
        ...(targetPeerId ? { targetPeerId } : {}),
      } as StateChecksumAuditMessage;
    }

    case 'TILE_RESYNC_REQUEST': {
      const targetPeerId =
        typeof msg.targetPeerId === 'string' || typeof msg.targetPeerId === 'number'
          ? String(msg.targetPeerId).trim().slice(0, 128)
          : undefined;
      const tileKeys = Array.isArray(msg.tileKeys)
        ? msg.tileKeys
            .filter(
              (k): k is string =>
                typeof k === 'string' && k.length > 0 && k.length <= 280 && k.split(':').length === 3
            )
            .slice(0, 256)
        : undefined;
      const layerIds = Array.isArray(msg.layerIds)
        ? msg.layerIds
            .filter((id): id is string => typeof id === 'string' && id.length > 0 && id.length <= 256)
            .slice(0, 32)
        : undefined;
      if ((!tileKeys || tileKeys.length === 0) && (!layerIds || layerIds.length === 0)) {
        return null;
      }
      return {
        type: 'TILE_RESYNC_REQUEST',
        senderId,
        ...(targetPeerId ? { targetPeerId } : {}),
        ...(tileKeys && tileKeys.length > 0 ? { tileKeys } : {}),
        ...(layerIds && layerIds.length > 0 ? { layerIds } : {}),
      } as TileResyncRequestMessage;
    }

    default:
      return msg as unknown as MultiplayerMessage;
  }
}

export interface ConnectOptions {
  isReconnect?: boolean;
  sinceSeq?: number;
}

class MultiplayerService {
  private ws: WebSocket | null = null;
  private transport: ICollabTransport | null = null;
  private transportUnsubs: Array<() => void> = [];
  private messageHandlers: Set<MessageHandler> = new Set();
  private closeHandlers: Set<(reason?: string) => void> = new Set();
  private errorHandlers: Set<(err: Event | Error) => void> = new Set();
  private currentPeer: CollabPeer | null = null;
  private localRole: CollabRole = 'editor';

  // Lamport Logical Clock for Vector CRDT + authoritative server sequence tracking
  private lamportClock = 0;
  private lastServerSeq = 0;

  // Track already-broadcast brush asset hashes, per-peer unicast asset deliveries, tile versions, and tile delta batches
  private sentAssetHashes: Set<string> = new Set();
  private sentAssetHashesByPeer: Map<string, Set<string>> = new Map();
  private sentTileVersions: Map<string, number> = new Map();
  private knownRemoteBaseTiles: Set<string> = new Set();

  // Content-addressed BrushSettings profile caching (shrinks repeated STROKE_START to ~60-78 bytes)
  private brushProfileCache: Map<string, CanonicalBrushProfile> = new Map();
  private sentBrushProfileHashes: Set<string> = new Set();
  private peerMetaById: Map<string, { name: string; color: string }> = new Map();
  private inFlightProfileRequests: Map<string, number> = new Map();
  private pendingProfileStrokes: Map<string, PendingProfileStroke> = new Map();

  // Last emitted network point per active stroke for adaptive point thinning
  private lastEmittedStrokePoints: Map<string, Point> = new Map();

  // Lightweight network diagnostics & RTT ping/pong tracker
  private diagnostics = new CollabDiagnosticsTracker();
  private nextPingId = 1;
  private pingTimer: ReturnType<typeof setInterval> | null = null;
  private initialPingTimer: ReturnType<typeof setTimeout> | null = null;
  private localDroppedEphemeralCount = 0;

  // Connection generation epoch to safely cancel in-flight async codec jobs on disconnect/reconnect
  private connectionEpoch = 0;

  // Ordered FIFO outgoing tile & stroke-commit barrier queue
  private outgoingTileQueue: OutgoingTileQueueJob[] = [];
  private outgoingTileFlushInFlight = false;
  private outgoingTileTimer: ReturnType<typeof setTimeout> | null = null;
  private strokeCommitMeta: Map<string, StrokeCommitMetadata> = new Map();

  // Ordered FIFO incoming burst tile decoder queue
  private incomingQueue: IncomingQueueEntry[] = [];
  private incomingDrainInFlight = false;
  private incomingDrainScheduled = false;
  private incomingSyncTilesThisFrame = 0;
  private incomingSyncResetHandle: ReturnType<typeof setTimeout> | number | null = null;
  private incomingSyncResetUsesRaf = false;

  // Throttling for cursor movement (max 60fps) & active stroke cursor suppression
  private lastCursorSendTime = 0;
  private pendingCursor: { x: number; y: number; isDrawing: boolean; tool: ToolType } | null = null;
  private cursorThrottleRaf: number | null = null;
  private activeStrokeId: string | null = null;
  private activeStrokeTool: ToolType = 'brush';
  private lastMutationTxAt = 0;

  // Throttling for real-time Follow Camera updates (~20Hz with trailing flush)
  private lastCameraSendTime = 0;
  private pendingCamera: Omit<CollabPeerCamera, 'updatedAt'> | null = null;
  private cameraThrottleTimer: ReturnType<typeof setTimeout> | null = null;

  // Trailing-edge throttles for high-frequency ruler / animation / layer property drag updates (~25-30Hz)
  private perspectiveThrottleTimer: ReturnType<typeof setTimeout> | null = null;
  private pendingPerspectiveRuler: PerspectiveRuler | null | undefined = undefined;
  private straightThrottleTimer: ReturnType<typeof setTimeout> | null = null;
  private pendingStraightRuler: StraightRuler | null | undefined = undefined;
  private animationThrottleTimer: ReturnType<typeof setTimeout> | null = null;
  private pendingAnimationTimeline: AnimationTimeline | null | undefined = undefined;
  private pendingLayerOpacities: Map<string, number> = new Map();
  private layerOpacityThrottleTimers: Map<string, ReturnType<typeof setTimeout>> = new Map();
  private pendingLayerUpdates: Map<string, Partial<WireLayerItem>> = new Map();
  private layerUpdateThrottleTimers: Map<string, ReturnType<typeof setTimeout>> = new Map();

  public clearSentAssetHashes(): void {
    this.sentAssetHashes.clear();
    this.sentAssetHashesByPeer.clear();
    this.sentBrushProfileHashes.clear();
  }

  public clearBrushProfileCache(): void {
    this.brushProfileCache.clear();
    this.sentBrushProfileHashes.clear();
    this.inFlightProfileRequests.clear();
    this.clearPendingProfileStrokes();
  }

  public clearSentTileVersions(): void {
    this.sentTileVersions.clear();
    this.knownRemoteBaseTiles.clear();
  }

  public clearPeerDedupeState(peerId: string | number): void {
    this.sentAssetHashesByPeer.delete(String(peerId));
  }

  public hasSentAssetToRoom(hash: string): boolean {
    return this.sentAssetHashes.has(hash);
  }

  public hasSentAssetToPeer(peerId: string | number, hash: string): boolean {
    return this.sentAssetHashesByPeer.get(String(peerId))?.has(hash) ?? false;
  }

  public hasCachedBrushProfile(hash: string): boolean {
    return this.brushProfileCache.has(hash);
  }

  public getCachedBrushProfile(hash: string): CanonicalBrushProfile | null {
    const existing = this.brushProfileCache.get(hash);
    if (!existing) return null;
    // Refresh LRU recency
    this.brushProfileCache.delete(hash);
    this.brushProfileCache.set(hash, existing);
    return existing;
  }

  public registerBrushProfile(hash: string, profile: CanonicalBrushProfile): void {
    if (!isValidBrushAssetHash(hash)) return;
    if (this.brushProfileCache.has(hash)) {
      this.brushProfileCache.delete(hash);
    } else if (this.brushProfileCache.size >= MAX_CACHED_BRUSH_PROFILES) {
      const oldest = this.brushProfileCache.keys().next().value;
      if (oldest !== undefined) {
        this.brushProfileCache.delete(oldest);
      }
    }
    this.brushProfileCache.set(hash, profile);
  }

  public clearSyncDedupeCaches(): void {
    this.sentAssetHashes.clear();
    this.sentAssetHashesByPeer.clear();
    this.sentBrushProfileHashes.clear();
    this.sentTileVersions.clear();
    this.knownRemoteBaseTiles.clear();
    this.incomingSyncTilesThisFrame = 0;
  }

  private clearPendingProfileStrokes(): void {
    for (const pending of this.pendingProfileStrokes.values()) {
      clearTimeout(pending.timer);
    }
    this.pendingProfileStrokes.clear();
  }

  private pruneKnownBaseTilesForLayer(layerId: string): void {
    if (!layerId) return;
    const prefix = `${layerId}:`;
    for (const key of this.knownRemoteBaseTiles) {
      if (key.startsWith(prefix)) {
        this.knownRemoteBaseTiles.delete(key);
      }
    }
  }

  private flushPendingProfileStroke(strokeId: string, profile?: CanonicalBrushProfile): void {
    const pending = this.pendingProfileStrokes.get(strokeId);
    if (!pending) return;
    this.pendingProfileStrokes.delete(strokeId);
    clearTimeout(pending.timer);

    const startMsg: StrokeStartMessage = profile
      ? {
          ...pending.start,
          brushSettings: applyBrushProfileOverrides(profile.baseSettings, pending.overrides),
          ...(profile.assetRefs ? { brushAssetRefs: profile.assetRefs } : {}),
          brushProfileCacheMiss: false,
        }
      : {
          ...pending.start,
          brushProfileCacheMiss: false,
        };

    this.dispatchOrQueueIncomingMessage(startMsg);
    for (let i = 0; i < pending.chunks.length; i++) {
      this.dispatchOrQueueIncomingMessage(pending.chunks[i]);
    }
    if (pending.finish) {
      this.dispatchOrQueueIncomingMessage(pending.finish);
    }
  }

  private resolvePendingStrokesForProfile(hash: string, profile: CanonicalBrushProfile): void {
    const matchingIds: string[] = [];
    for (const [strokeId, pending] of this.pendingProfileStrokes.entries()) {
      if (pending.profileHash === hash) {
        matchingIds.push(strokeId);
      }
    }
    for (let i = 0; i < matchingIds.length; i++) {
      this.flushPendingProfileStroke(matchingIds[i], profile);
    }
  }

  private recordPeerMeta(peerId: string | number | undefined, name?: string, color?: string): void {
    if (peerId === undefined || peerId === null) return;
    const key = String(peerId);
    if (!key) return;
    const existing = this.peerMetaById.get(key);
    const nextName = name && name.trim() ? name.trim().slice(0, 64) : existing?.name || 'Peer';
    const nextColor = color && color.trim() ? color.trim().slice(0, 32) : existing?.color || '#38bdf8';
    this.peerMetaById.set(key, { name: nextName, color: nextColor });
  }

  private startPingLoop(): void {
    this.stopPingLoop();
    const epoch = this.connectionEpoch;
    this.initialPingTimer = setTimeout(() => {
      this.initialPingTimer = null;
      if (this.connectionEpoch !== epoch || !this.isConnected()) return;
      this.sendPingProbe();
    }, PING_INITIAL_DELAY_MS);
    this.pingTimer = setInterval(() => {
      if (this.connectionEpoch !== epoch || !this.isConnected()) {
        this.stopPingLoop();
        return;
      }
      this.sendPingProbe();
    }, PING_INTERVAL_MS);
  }

  private stopPingLoop(): void {
    if (this.initialPingTimer !== null) {
      clearTimeout(this.initialPingTimer);
      this.initialPingTimer = null;
    }
    if (this.pingTimer !== null) {
      clearInterval(this.pingTimer);
      this.pingTimer = null;
    }
  }

  public sendPingProbe(): void {
    if (!this.isConnected()) return;
    const pingId = this.nextPingId >>> 0;
    this.nextPingId = ((this.nextPingId + 1) >>> 0) || 1;
    const nowMs =
      typeof performance !== 'undefined' && typeof performance.now === 'function'
        ? performance.now()
        : Date.now();
    this.diagnostics.registerPing(pingId, nowMs);

    const packet = new Uint8Array(11 + PING_PAYLOAD_BYTES);
    const view = new DataView(packet.buffer);
    view.setUint8(0, BINARY_MAGIC_0);
    view.setUint8(1, BINARY_MAGIC_1);
    view.setUint8(2, CODE_PING);
    view.setUint32(3, 0, true);
    view.setUint32(7, PING_PAYLOAD_BYTES, true);
    view.setUint32(11, pingId, true);
    view.setFloat64(15, nowMs, true);

    this.sendBinary(packet, undefined, { ephemeral: true });
  }

  private sendPongEcho(pingId: number, clientSendMs: number): void {
    if (!this.isConnected()) return;
    const packet = new Uint8Array(11 + PING_PAYLOAD_BYTES);
    const view = new DataView(packet.buffer);
    view.setUint8(0, BINARY_MAGIC_0);
    view.setUint8(1, BINARY_MAGIC_1);
    view.setUint8(2, CODE_PONG);
    view.setUint32(3, 0, true);
    view.setUint32(7, PING_PAYLOAD_BYTES, true);
    view.setUint32(11, pingId >>> 0, true);
    view.setFloat64(15, clientSendMs, true);

    this.sendBinary(packet, undefined, { ephemeral: true });
  }

  public getActiveTileQueueDepth(): number {
    let depth = 0;
    for (let i = 0; i < this.outgoingTileQueue.length; i++) {
      const job = this.outgoingTileQueue[i];
      if (job.kind === 'tiles') {
        depth += Math.max(0, job.entries.length - job.cursor);
      }
    }
    for (let i = 0; i < this.incomingQueue.length; i++) {
      if (this.incomingQueue[i].kind === 'tile') {
        depth += 1;
      }
    }
    return depth;
  }

  public getDiagnosticsSnapshot(): CollabDiagnostics {
    const kind = this.getTransportKind();
    const transportFamily: 'ws' | 'webrtc' | null =
      kind === 'ws' ? 'ws' : kind === 'webrtc-host' || kind === 'webrtc-guest' ? 'webrtc' : null;
    const transportDropped = this.transport?.getDroppedEphemeralCount?.() ?? 0;
    return this.diagnostics.getSnapshot({
      transport: transportFamily,
      tileQueueDepth: this.getActiveTileQueueDepth(),
      droppedEphemeralCount: transportDropped + this.localDroppedEphemeralCount,
    });
  }

  public async refreshIceCandidateType(): Promise<void> {
    if (!this.transport || !this.transport.isOpen() || !this.transport.getActiveIceCandidateType) {
      this.diagnostics.setIceCandidateType(null);
      return;
    }
    const candidateType = await this.transport.getActiveIceCandidateType();
    this.diagnostics.setIceCandidateType(candidateType);
  }

  public recordAuditResult(status: 'ok' | 'resyncing'): void {
    this.diagnostics.recordAuditResult(status);
  }

  public getLastMutationTxAt(): number {
    return this.lastMutationTxAt;
  }

  public hasActiveLocalStroke(): boolean {
    return this.activeStrokeId !== null;
  }

  public resetDiagnostics(): void {
    this.diagnostics.reset();
    this.localDroppedEphemeralCount = 0;
    this.lastMutationTxAt = 0;
  }

  private clearLayerPropThrottlesForLayer(layerId: string): void {
    const opTimer = this.layerOpacityThrottleTimers.get(layerId);
    if (opTimer !== undefined) {
      clearTimeout(opTimer);
      this.layerOpacityThrottleTimers.delete(layerId);
    }
    this.pendingLayerOpacities.delete(layerId);

    const updTimer = this.layerUpdateThrottleTimers.get(layerId);
    if (updTimer !== undefined) {
      clearTimeout(updTimer);
      this.layerUpdateThrottleTimers.delete(layerId);
    }
    this.pendingLayerUpdates.delete(layerId);
  }

  private clearAllLayerPropThrottles(): void {
    for (const timer of this.layerOpacityThrottleTimers.values()) {
      clearTimeout(timer);
    }
    this.layerOpacityThrottleTimers.clear();
    this.pendingLayerOpacities.clear();
    for (const timer of this.layerUpdateThrottleTimers.values()) {
      clearTimeout(timer);
    }
    this.layerUpdateThrottleTimers.clear();
    this.pendingLayerUpdates.clear();
  }

  private clearIncomingSyncBudgetTimer(): void {
    if (this.incomingSyncResetHandle !== null) {
      if (this.incomingSyncResetUsesRaf) {
        if (typeof cancelAnimationFrame === 'function') {
          cancelAnimationFrame(this.incomingSyncResetHandle as number);
        } else if (typeof window !== 'undefined' && typeof window.cancelAnimationFrame === 'function') {
          window.cancelAnimationFrame(this.incomingSyncResetHandle as number);
        }
      } else {
        clearTimeout(this.incomingSyncResetHandle as ReturnType<typeof setTimeout>);
      }
      this.incomingSyncResetHandle = null;
      this.incomingSyncResetUsesRaf = false;
    }
  }

  private scheduleIncomingSyncBudgetReset(): void {
    if (this.incomingSyncResetHandle !== null) return;
    const reset = () => {
      this.incomingSyncResetHandle = null;
      this.incomingSyncResetUsesRaf = false;
      this.incomingSyncTilesThisFrame = 0;
    };
    const rafFn =
      typeof requestAnimationFrame === 'function'
        ? requestAnimationFrame
        : typeof window !== 'undefined' && typeof window.requestAnimationFrame === 'function'
          ? window.requestAnimationFrame.bind(window)
          : null;
    if (rafFn) {
      this.incomingSyncResetUsesRaf = true;
      this.incomingSyncResetHandle = rafFn(reset);
    } else {
      this.incomingSyncResetUsesRaf = false;
      this.incomingSyncResetHandle = setTimeout(reset, 16);
    }
  }

  private resetAsyncTilePipelines(): void {
    this.connectionEpoch++;
    this.stopPingLoop();
    this.clearPendingProfileStrokes();
    this.lastEmittedStrokePoints.clear();
    this.outgoingTileQueue.length = 0;
    this.outgoingTileFlushInFlight = false;
    if (this.outgoingTileTimer !== null) {
      clearTimeout(this.outgoingTileTimer);
      this.outgoingTileTimer = null;
    }
    this.strokeCommitMeta.clear();
    this.incomingQueue.length = 0;
    this.incomingDrainInFlight = false;
    this.incomingDrainScheduled = false;
    this.incomingSyncTilesThisFrame = 0;
    this.clearIncomingSyncBudgetTimer();
  }

  public hasPendingIncomingTilesForLayer(layerId: string): boolean {
    if (!layerId) return false;
    for (let i = 0; i < this.incomingQueue.length; i++) {
      const entry = this.incomingQueue[i];
      if (entry.kind === 'tile' && entry.layerId === layerId) {
        return true;
      }
    }
    return false;
  }

  public hasPendingOutgoingTilesForStroke(strokeId: string): boolean {
    if (!strokeId) return false;
    const meta = this.strokeCommitMeta.get(strokeId);
    if (meta?.pending) return true;
    for (let i = 0; i < this.outgoingTileQueue.length; i++) {
      const job = this.outgoingTileQueue[i];
      if (job.kind === 'tiles' && job.strokeId === strokeId) {
        return true;
      }
    }
    return false;
  }

  private hasPendingOutgoingTilesForLayer(layerId: string): boolean {
    if (!layerId) return false;
    for (let i = 0; i < this.outgoingTileQueue.length; i++) {
      const job = this.outgoingTileQueue[i];
      if (job.kind === 'tiles') {
        for (let k = job.cursor; k < job.entries.length; k++) {
          if (job.entries[k].layerId === layerId) return true;
        }
      }
    }
    return false;
  }

  public markStrokeTileCommit(strokeId: string, expectedTileCount: number, layerId?: string): void {
    if (!strokeId) return;
    this.strokeCommitMeta.set(strokeId, {
      expectedTileCount: Math.max(0, Math.floor(expectedTileCount)),
      pending: false,
      layerId,
    });
  }

  /**
   * Registers a callback to execute strictly after all pending outgoing BINARY_TILE
   * packets for `strokeId` have been serialized and pushed into the transport.
   * Returns `true` if queued asynchronously, or `false` if no tiles are pending
   * (in which case the caller can proceed immediately synchronously).
   */
  public enqueueAfterStrokeTiles(strokeId: string, callback: () => void): boolean {
    if (!strokeId || !this.hasPendingOutgoingTilesForStroke(strokeId)) {
      return false;
    }
    this.outgoingTileQueue.push({
      kind: 'barrier',
      strokeId,
      run: callback,
    });
    this.kickOutgoingTilePump();
    return true;
  }

  public getNextLamport(): number {
    return ++this.lamportClock;
  }

  public updateLamport(remoteLamport: number): void {
    this.lamportClock = Math.max(this.lamportClock, remoteLamport) + 1;
  }

  public getLastServerSeq(): number {
    return this.lastServerSeq;
  }

  public updateServerSeq(seq: number): void {
    if (Number.isSafeInteger(seq) && seq > this.lastServerSeq) {
      this.lastServerSeq = seq;
    }
  }

  public sendDocSyncRequest(sinceSeq?: number): void {
    if (!this.isConnected() || !this.currentPeer) return;
    this.sendMessage({
      type: 'DOC_SYNC_REQUEST',
      targetPeerId: this.currentPeer.id,
      ...(sinceSeq !== undefined && Number.isSafeInteger(sinceSeq) && sinceSeq >= 0
        ? { sinceSeq }
        : {}),
    });
  }

  public isConnected(): boolean {
    return (
      (this.ws !== null && this.ws.readyState === WebSocket.OPEN) ||
      (this.transport !== null && this.transport.isOpen())
    );
  }

  public getTransportKind(): CollabTransportKind | null {
    if (this.transport && this.transport.isOpen()) return this.transport.kind;
    if (this.ws && this.ws.readyState === WebSocket.OPEN) return 'ws';
    return null;
  }

  public getPeer(): CollabPeer | null {
    return this.currentPeer;
  }

  public setLocalRole(role: CollabRole): void {
    this.localRole = role;
    if (this.currentPeer) {
      this.currentPeer = {
        ...this.currentPeer,
        role,
        isHost: role === 'host',
      };
    }
  }

  public getLocalRole(): CollabRole {
    return this.localRole;
  }

  private canSendMutation(): boolean {
    return this.localRole !== 'viewer';
  }

  public getBufferedAmount(): number {
    if (this.transport) return this.transport.getBufferedAmount();
    return this.ws ? this.ws.bufferedAmount : 0;
  }

  private scheduleIncomingDrain(): void {
    if (this.incomingDrainScheduled || this.incomingDrainInFlight) return;
    this.incomingDrainScheduled = true;
    const epoch = this.connectionEpoch;
    queueMicrotask(() => {
      this.incomingDrainScheduled = false;
      if (this.connectionEpoch !== epoch) return;
      void this.drainIncomingQueue(epoch);
    });
  }

  private async drainIncomingQueue(epoch: number): Promise<void> {
    if (this.incomingDrainInFlight) return;
    this.incomingDrainInFlight = true;
    try {
      while (this.incomingQueue.length > 0 && this.connectionEpoch === epoch) {
        const head = this.incomingQueue[0];
        if (head.kind === 'message') {
          this.incomingQueue.shift();
          this.notifyHandlers(head.msg);
          continue;
        }

        // Collect a contiguous batch of raw tile frames for parallel off-main-thread decompression
        const tileBatch: Array<{
          layerId: string;
          tilePacket: Uint8Array;
          tileKey: string;
          serverSeq: number;
        }> = [];
        while (
          this.incomingQueue.length > 0 &&
          tileBatch.length < INCOMING_TILE_BATCH_SIZE &&
          this.incomingQueue[0].kind === 'tile'
        ) {
          const item = this.incomingQueue.shift() as Extract<IncomingQueueEntry, { kind: 'tile' }>;
          tileBatch.push(item);
        }

        if (tileBatch.length === 0) continue;

        if (this.connectionEpoch !== epoch) return;

        const nativeMode = isNativeCanvasActive();
        for (let i = 0; i < tileBatch.length; i++) {
          const meta = tileBatch[i];
          if (nativeMode) {
            const pView = new DataView(
              meta.tilePacket.buffer,
              meta.tilePacket.byteOffset,
              meta.tilePacket.byteLength
            );
            const tileX = pView.getInt32(0, true);
            const tileY = pView.getInt32(4, true);
            const format = wireCodeToFormat(pView.getUint8(8));
            const version = pView.getUint32(9, true);
            const codec = pView.getUint8(13);
            if (
              !format ||
              tileX < 0 ||
              tileY < 0 ||
              tileX >= MAX_TILE_COORD ||
              tileY >= MAX_TILE_COORD
            ) {
              continue;
            }
            if (codec !== TILE_CODEC_EMPTY) {
              this.knownRemoteBaseTiles.add(meta.tileKey);
            } else {
              this.knownRemoteBaseTiles.delete(meta.tileKey);
            }
            const msg: TileStreamMessage = {
              type: 'BINARY_TILE',
              layerId: meta.layerId,
              tileX,
              tileY,
              format,
              version,
              data: null,
              rawPacket: meta.tilePacket.slice(),
              ...(meta.serverSeq > 0 ? { seq: meta.serverSeq } : {}),
            };
            this.notifyHandlers(msg);
            continue;
          }

          const decoded = deserializeWireTilePacketStrict(meta.layerId, meta.tilePacket);
          if (!decoded) continue;
          if (decoded.kind === 'full') {
            const tile = decoded.tile;
            if (
              tile.tileX < 0 ||
              tile.tileY < 0 ||
              tile.tileX >= MAX_TILE_COORD ||
              tile.tileY >= MAX_TILE_COORD
            ) {
              continue;
            }
            const tileKey = `${meta.layerId}:${tile.tileX}:${tile.tileY}`;
            if (tile.data !== null) {
              this.knownRemoteBaseTiles.add(tileKey);
            } else {
              this.knownRemoteBaseTiles.delete(tileKey);
            }
            const msg: TileStreamMessage = {
              type: 'BINARY_TILE',
              layerId: meta.layerId,
              tileX: tile.tileX,
              tileY: tile.tileY,
              format: tile.format,
              version: tile.version,
              data: tile.data,
              rawPacket: meta.tilePacket.slice(),
              ...(meta.serverSeq > 0 ? { seq: meta.serverSeq } : {}),
            };
            this.notifyHandlers(msg);
          } else {
            if (
              decoded.tileX < 0 ||
              decoded.tileY < 0 ||
              decoded.tileX >= MAX_TILE_COORD ||
              decoded.tileY >= MAX_TILE_COORD
            ) {
              continue;
            }
            const msg: TileStreamMessage = {
              type: 'BINARY_TILE',
              layerId: meta.layerId,
              tileX: decoded.tileX,
              tileY: decoded.tileY,
              format: decoded.format,
              version: decoded.version,
              data: null,
              subRect: decoded.subRect,
              rawPacket: meta.tilePacket.slice(),
              ...(meta.serverSeq > 0 ? { seq: meta.serverSeq } : {}),
            };
            this.notifyHandlers(msg);
          }
        }
      }
    } catch (err) {
      console.error('[Multiplayer] Incoming tile batch drain failed:', err);
    } finally {
      this.incomingDrainInFlight = false;
      if (this.incomingQueue.length > 0 && this.connectionEpoch === epoch) {
        this.scheduleIncomingDrain();
      }
    }
  }

  private dispatchOrQueueIncomingMessage(msg: MultiplayerMessage): void {
    const queueActive = this.incomingDrainInFlight || this.incomingQueue.length > 0;
    if (!queueActive || BYPASS_INCOMING_TILE_QUEUE_TYPES.has(msg.type)) {
      this.notifyHandlers(msg);
      return;
    }
    this.incomingQueue.push({ kind: 'message', msg });
    this.scheduleIncomingDrain();
  }

  private handleIncomingBinaryPayload(buf: ArrayBuffer): void {
    if (buf.byteLength < 11 || buf.byteLength > MAX_BINARY_PACKET_BYTES) return;
    this.diagnostics.recordRx(buf.byteLength);
    const view = new DataView(buf);
    if (view.getUint8(0) !== BINARY_MAGIC_0 || view.getUint8(1) !== BINARY_MAGIC_1) return;

    const code = view.getUint8(2);
    const serverSeq = view.getUint32(3, true);

    // Fast-path lightweight RTT ping/pong control packets (never enter tile queue or op handlers)
    if (code === CODE_PING || code === CODE_PONG) {
      const payloadLen = view.getUint32(7, true);
      if (payloadLen !== PING_PAYLOAD_BYTES || 11 + payloadLen > buf.byteLength) return;
      const pingId = view.getUint32(11, true);
      const clientSendMs = view.getFloat64(15, true);
      if (code === CODE_PING) {
        this.sendPongEcho(pingId, clientSendMs);
      } else {
        const nowMs =
          typeof performance !== 'undefined' && typeof performance.now === 'function'
            ? performance.now()
            : Date.now();
        this.diagnostics.recordPong(pingId, nowMs, clientSendMs);
      }
      return;
    }

    if (code === CODE_TILE_DELTA) {
      const queueActive = this.incomingDrainInFlight || this.incomingQueue.length > 0;
      const shouldOffload =
        queueActive || this.incomingSyncTilesThisFrame >= SYNC_TILE_CODEC_THRESHOLD;

      if (shouldOffload) {
        const peeked = peekTileDeltaHeader(buf);
        if (!peeked) return;
        this.updateLamport(serverSeq);
        if (serverSeq > 0) {
          this.updateServerSeq(serverSeq);
        }
        this.incomingQueue.push({
          kind: 'tile',
          layerId: peeked.layerId,
          tilePacket: peeked.tilePacket,
          tileKey: peeked.tileKey,
          serverSeq: peeked.serverSeq,
        });
        this.scheduleIncomingDrain();
        return;
      }

      this.incomingSyncTilesThisFrame++;
      this.scheduleIncomingSyncBudgetReset();
    }

    const parsed = this.decodeBinaryPacket(buf);
    if (!parsed) return;
    if (serverSeq > 0) {
      parsed.seq = serverSeq;
      this.updateServerSeq(serverSeq);
    }

    // Profile cache-miss buffering & automatic recovery
    if (parsed.type === 'BRUSH_PROFILE_DATA') {
      const cached = this.getCachedBrushProfile(parsed.hash);
      if (cached) {
        this.resolvePendingStrokesForProfile(parsed.hash, cached);
      }
      this.dispatchOrQueueIncomingMessage(parsed);
      return;
    }

    if (parsed.type === 'BRUSH_PROFILE_REQUEST') {
      const matchesMe =
        parsed.targetPeerId === undefined ||
        (this.currentPeer !== null && String(parsed.targetPeerId) === String(this.currentPeer.id));
      if (matchesMe && this.hasCachedBrushProfile(parsed.hash)) {
        this.sendBrushProfileData(parsed.hash, parsed.senderId);
      }
      this.dispatchOrQueueIncomingMessage(parsed);
      return;
    }

    if (parsed.type === 'STROKE_START' && parsed.brushProfileCacheMiss && parsed.brushProfileHash) {
      const hash = parsed.brushProfileHash;
      const now = Date.now();
      const lastReq = this.inFlightProfileRequests.get(hash) ?? 0;
      if (now - lastReq >= PROFILE_REQUEST_COOLDOWN_MS) {
        this.inFlightProfileRequests.set(hash, now);
        this.sendBrushProfileRequest(hash, parsed.peerId);
      }

      if (this.pendingProfileStrokes.size >= MAX_PENDING_PROFILE_STROKES) {
        const oldestKey = this.pendingProfileStrokes.keys().next().value;
        if (oldestKey !== undefined) {
          this.flushPendingProfileStroke(oldestKey);
        }
      }
      const existingPending = this.pendingProfileStrokes.get(parsed.strokeId);
      if (existingPending) {
        clearTimeout(existingPending.timer);
      }
      const strokeId = parsed.strokeId;
      const timer = setTimeout(() => {
        this.flushPendingProfileStroke(strokeId);
      }, PROFILE_MISS_FALLBACK_MS);

      this.pendingProfileStrokes.set(strokeId, {
        profileHash: hash,
        start: parsed,
        overrides: {
          color: parsed.brushSettings.color,
          size: parsed.brushSettings.size,
          opacity: parsed.brushSettings.opacity,
        },
        chunks: [],
        timer,
      });
      return;
    }

    if (parsed.type === 'STROKE_CHUNK' && this.pendingProfileStrokes.has(parsed.strokeId)) {
      const pending = this.pendingProfileStrokes.get(parsed.strokeId)!;
      if (pending.chunks.length < MAX_PENDING_PROFILE_CHUNKS) {
        pending.chunks.push(parsed);
      }
      return;
    }

    if (parsed.type === 'STROKE_FINISH' && this.pendingProfileStrokes.has(parsed.strokeId)) {
      const pending = this.pendingProfileStrokes.get(parsed.strokeId)!;
      pending.finish = parsed;
      return;
    }

    this.dispatchOrQueueIncomingMessage(parsed);
  }

  private handleIncomingTextPayload(rawText: string): void {
    if (rawText.length > MAX_JSON_MESSAGE_CHARS) return;
    this.diagnostics.recordRx(rawText.length);
    const raw = JSON.parse(rawText) as unknown;
    const sanitized = sanitizeIncomingJsonMessage(raw);
    if (!sanitized) return;
    if (typeof sanitized.seq === 'number') {
      this.updateServerSeq(sanitized.seq);
    }
    const remoteLamport = (sanitized as { lamport?: unknown }).lamport;
    if (typeof remoteLamport === 'number' && Number.isFinite(remoteLamport)) {
      this.updateLamport(remoteLamport);
    }

    // Track peer metadata & remote tile base invalidation
    if (sanitized.type === 'PEER_JOINED' && sanitized.peer) {
      this.recordPeerMeta(sanitized.peer.id, sanitized.peer.name, sanitized.peer.color);
    } else if (sanitized.type === 'JOIN_ACCEPTED' && Array.isArray(sanitized.peers)) {
      for (let i = 0; i < sanitized.peers.length; i++) {
        const p = sanitized.peers[i];
        this.recordPeerMeta(p.id, p.name, p.color);
      }
    } else if (sanitized.type === 'LAYER_CLEAR' || sanitized.type === 'LAYER_DELETE') {
      this.pruneKnownBaseTilesForLayer(sanitized.layerId);
    } else if (sanitized.type === 'CANVAS_RESIZE' || sanitized.type === 'DOC_SYNC_RESPONSE') {
      this.knownRemoteBaseTiles.clear();
    }

    this.dispatchOrQueueIncomingMessage(sanitized);
  }

  private detachTransportQuietly(): void {
    for (const unsub of this.transportUnsubs) {
      try {
        unsub();
      } catch {
        // ignore
      }
    }
    this.transportUnsubs = [];
    if (this.transport) {
      const closing = this.transport;
      this.transport = null;
      try {
        closing.close();
      } catch {
        // ignore
      }
    }
  }

  private closeSocketQuietly(): void {
    this.resetAsyncTilePipelines();
    this.detachTransportQuietly();
    if (!this.ws) return;
    const closingWs = this.ws;
    this.ws = null;
    try {
      closingWs.onopen = null;
      closingWs.onmessage = null;
      closingWs.onclose = null;
      closingWs.onerror = null;
      closingWs.close();
    } catch {
      // ignore close errors
    }
  }

  /**
   * Attaches a custom `ICollabTransport` (e.g., WebRtcHostHub or WebRtcGuestClient)
   * so the entire existing binary (`IN...`) & JSON protocol works identically over WebRTC.
   */
  public attachTransport(
    transport: ICollabTransport,
    peer: CollabPeer,
    options?: ConnectOptions & { sendJoinRequest?: boolean }
  ): void {
    const isReconnect = Boolean(options?.isReconnect);
    if (isReconnect) {
      this.closeSocketQuietly();
    } else {
      this.disconnect();
    }

    this.transport = transport;
    this.currentPeer = peer;
    this.localRole = peer.isHost ? 'host' : peer.role ?? (isReconnect ? this.localRole : 'editor');

    const unsubText = transport.onTextMessage((text) => {
      if (this.transport !== transport) return;
      try {
        this.handleIncomingTextPayload(text);
      } catch (err) {
        console.error('[Multiplayer] Failed to parse transport JSON:', err);
      }
    });

    const unsubBin = transport.onBinaryMessage((buf) => {
      if (this.transport !== transport) return;
      try {
        this.handleIncomingBinaryPayload(buf);
      } catch (err) {
        console.error('[Multiplayer] Failed to parse transport binary:', err);
      }
    });

    const unsubClose = transport.onClose((reason) => {
      if (this.transport === transport) {
        this.stopPingLoop();
        this.transport = null;
        this.transportUnsubs = [];
        this.closeHandlers.forEach((h) => h(reason));
      }
    });

    const unsubErr = transport.onError((err) => {
      if (this.transport !== transport) return;
      this.errorHandlers.forEach((h) => h(err));
    });

    this.transportUnsubs = [unsubText, unsubBin, unsubClose, unsubErr];

    const shouldSendJoin =
      options?.sendJoinRequest !== undefined
        ? options.sendJoinRequest
        : transport.kind === 'webrtc-guest';

    if (shouldSendJoin && transport.isOpen()) {
      const resumeSeq =
        isReconnect &&
        typeof options?.sinceSeq === 'number' &&
        Number.isSafeInteger(options.sinceSeq) &&
        options.sinceSeq >= 0
          ? options.sinceSeq
          : isReconnect
            ? this.lastServerSeq
            : undefined;

      this.sendMessage({
        type: 'JOIN_REQUEST',
        peer: this.currentPeer,
        ...(isReconnect ? { isReconnect: true } : {}),
        ...(resumeSeq !== undefined ? { sinceSeq: resumeSeq } : {}),
      });
    }

    if (transport.isOpen()) {
      this.startPingLoop();
    }
  }

  public connect(
    url: string,
    peer: CollabPeer,
    token?: string,
    options?: ConnectOptions
  ): Promise<void> {
    return new Promise((resolve, reject) => {
      const isReconnect = Boolean(options?.isReconnect);
      if (isReconnect) {
        this.closeSocketQuietly();
      } else {
        this.disconnect();
      }
      this.currentPeer = peer;
      this.localRole = peer.isHost ? 'host' : peer.role ?? (isReconnect ? this.localRole : 'editor');

      const resumeSeq =
        isReconnect &&
        typeof options?.sinceSeq === 'number' &&
        Number.isSafeInteger(options.sinceSeq) &&
        options.sinceSeq >= 0
          ? options.sinceSeq
          : isReconnect
            ? this.lastServerSeq
            : undefined;

      let connectUrl = url;
      let displayUrl = url;
      try {
        const parsed = new URL(url);
        if (token && !parsed.searchParams.has('token')) {
          parsed.searchParams.set('token', token);
        }
        connectUrl = parsed.toString();
        parsed.searchParams.delete('token');
        displayUrl = parsed.toString();
      } catch {
        if (token && !/[?&]token=/.test(url)) {
          const sep = url.includes('?') ? '&' : '?';
          connectUrl = `${url}${sep}token=${encodeURIComponent(token)}`;
        }
      }

      let settled = false;
      const settleResolve = () => {
        if (settled) return;
        settled = true;
        if (timeoutId !== null) clearTimeout(timeoutId);
        resolve();
      };
      const settleReject = (err: Error) => {
        if (settled) return;
        settled = true;
        if (timeoutId !== null) clearTimeout(timeoutId);
        reject(err);
      };

      let timeoutId: ReturnType<typeof setTimeout> | null = null;

      try {
        const ws = new WebSocket(connectUrl);
        ws.binaryType = 'arraybuffer';
        this.ws = ws;

        timeoutId = setTimeout(() => {
          if (this.ws === ws && !settled) {
            try {
              ws.close();
            } catch {
              // ignore
            }
            this.ws = null;
            settleReject(new Error(`Connection timed out (${displayUrl})`));
          }
        }, WS_CONNECT_TIMEOUT_MS);

        ws.onopen = () => {
          if (this.ws !== ws) {
            ws.close();
            return;
          }
          // Send join handshake (carrying sinceSeq on reconnect for incremental op/tile catch-up)
          this.sendMessage({
            type: 'JOIN_REQUEST',
            peer: this.currentPeer!,
            ...(isReconnect ? { isReconnect: true } : {}),
            ...(resumeSeq !== undefined ? { sinceSeq: resumeSeq } : {}),
          });
          this.startPingLoop();
          settleResolve();
        };

        ws.onmessage = (event) => {
          if (this.ws !== ws) return;
          try {
            if (event.data instanceof ArrayBuffer) {
              this.handleIncomingBinaryPayload(event.data);
            } else if (typeof Blob !== 'undefined' && event.data instanceof Blob) {
              const epoch = this.connectionEpoch;
              void event.data.arrayBuffer().then((buf) => {
                if (this.ws !== ws || this.connectionEpoch !== epoch) return;
                try {
                  this.handleIncomingBinaryPayload(buf);
                } catch (err) {
                  console.error('[Multiplayer] Failed to parse binary blob:', err);
                }
              });
            } else if (typeof event.data === 'string') {
              this.handleIncomingTextPayload(event.data);
            }
          } catch (err) {
            console.error('[Multiplayer] Failed to parse message:', err, event.data);
          }
        };

        ws.onclose = (ev) => {
          if (this.ws === ws) {
            this.ws = null;
            this.stopPingLoop();
          }
          if (!settled) {
            const detail = ev.reason ? `: ${ev.reason}` : '';
            settleReject(new Error(`Failed to connect to socket server (${displayUrl})${detail}`));
          } else {
            this.closeHandlers.forEach((h) => h());
          }
        };

        ws.onerror = (err) => {
          if (this.ws !== ws) return;
          this.errorHandlers.forEach((h) => h(err));
          settleReject(new Error(`Failed to connect to socket server (${displayUrl})`));
        };
      } catch (err: any) {
        settleReject(new Error(err?.message || `WebSocket initialization error (${displayUrl})`));
      }
    });
  }

  public disconnect() {
    if (this.transport) {
      if (
        this.currentPeer &&
        this.transport.isOpen() &&
        this.transport.kind !== 'webrtc-host'
      ) {
        this.sendMessage({
          type: 'PEER_LEFT',
          peerId: this.currentPeer.id,
        });
      }
      this.detachTransportQuietly();
    }
    if (this.ws) {
      const closingWs = this.ws;
      if (this.currentPeer && closingWs.readyState === WebSocket.OPEN) {
        this.sendMessage({
          type: 'PEER_LEFT',
          peerId: this.currentPeer.id,
        });
      }
      this.ws = null;
      try {
        closingWs.onopen = null;
        closingWs.onmessage = null;
        closingWs.onclose = null;
        closingWs.onerror = null;
        closingWs.close();
      } catch {
        // ignore close errors
      }
    }
    this.resetAsyncTilePipelines();
    this.currentPeer = null;
    this.localRole = 'editor';
    this.lastServerSeq = 0;
    this.sentAssetHashes.clear();
    this.sentAssetHashesByPeer.clear();
    this.sentBrushProfileHashes.clear();
    this.brushProfileCache.clear();
    this.peerMetaById.clear();
    this.inFlightProfileRequests.clear();
    this.sentTileVersions.clear();
    this.knownRemoteBaseTiles.clear();
    this.diagnostics.reset();
    this.localDroppedEphemeralCount = 0;
    this.clearAllLayerPropThrottles();
    if (this.cursorThrottleRaf) {
      cancelAnimationFrame(this.cursorThrottleRaf);
      this.cursorThrottleRaf = null;
    }
    this.pendingCursor = null;
    this.activeStrokeId = null;
    this.activeStrokeTool = 'brush';
    if (this.cameraThrottleTimer) {
      clearTimeout(this.cameraThrottleTimer);
      this.cameraThrottleTimer = null;
    }
    this.pendingCamera = null;
    if (this.perspectiveThrottleTimer) {
      clearTimeout(this.perspectiveThrottleTimer);
      this.perspectiveThrottleTimer = null;
    }
    this.pendingPerspectiveRuler = undefined;
    if (this.straightThrottleTimer) {
      clearTimeout(this.straightThrottleTimer);
      this.straightThrottleTimer = null;
    }
    this.pendingStraightRuler = undefined;
    if (this.animationThrottleTimer) {
      clearTimeout(this.animationThrottleTimer);
      this.animationThrottleTimer = null;
    }
    this.pendingAnimationTimeline = undefined;
  }

  public onMessage(handler: MessageHandler): () => void {
    this.messageHandlers.add(handler);
    return () => this.messageHandlers.delete(handler);
  }

  public onClose(handler: (reason?: string) => void): () => void {
    this.closeHandlers.add(handler);
    return () => this.closeHandlers.delete(handler);
  }

  public onError(handler: (err: Event | Error) => void): () => void {
    this.errorHandlers.add(handler);
    return () => this.errorHandlers.delete(handler);
  }

  public sendMessage(msg: MultiplayerMessage) {
    const isNonMutation =
      msg.type === 'CURSOR_MOVE' ||
      msg.type === 'CANVAS_PING' ||
      msg.type === 'STATE_CHECKSUM_AUDIT' ||
      msg.type === 'TILE_RESYNC_REQUEST' ||
      msg.type === 'CAMERA_SYNC_REQUEST' ||
      msg.type === 'CHAT_MESSAGE' ||
      msg.type === 'BRUSH_ASSET_REQUEST' ||
      msg.type === 'BRUSH_PROFILE_REQUEST';
    if (this.transport && this.transport.isOpen()) {
      if (!msg.senderId && this.currentPeer) {
        msg.senderId = this.currentPeer.id;
      }
      const encoded = JSON.stringify(msg);
      this.diagnostics.recordTx(encoded.length);
      if (!isNonMutation) this.lastMutationTxAt = Date.now();
      this.transport.sendText(encoded);
      return;
    }
    if (this.ws && this.ws.readyState === WebSocket.OPEN) {
      if (!msg.senderId && this.currentPeer) {
        msg.senderId = this.currentPeer.id;
      }
      const encoded = JSON.stringify(msg);
      this.diagnostics.recordTx(encoded.length);
      if (!isNonMutation) this.lastMutationTxAt = Date.now();
      this.ws.send(encoded);
    }
  }

  public sendBinary(
    buffer: ArrayBuffer | Uint8Array,
    targetPeerId?: string | number,
    options?: CollabSendOptions
  ) {
    const byteLength = buffer.byteLength;
    const u8 = buffer instanceof Uint8Array ? buffer : new Uint8Array(buffer);
    const opcode =
      u8.byteLength >= 3 && u8[0] === BINARY_MAGIC_0 && u8[1] === BINARY_MAGIC_1 ? u8[2] : -1;
    const isNonMutation =
      opcode === CODE_CURSOR_MOVE ||
      opcode === CODE_CAMERA_SYNC ||
      opcode === CODE_PING ||
      opcode === CODE_PONG ||
      opcode === CODE_BRUSH_ASSET_REQUEST ||
      opcode === CODE_BRUSH_PROFILE_REQUEST;
    if (this.transport && this.transport.isOpen()) {
      this.diagnostics.recordTx(byteLength);
      if (!isNonMutation) this.lastMutationTxAt = Date.now();
      if (targetPeerId !== undefined && this.transport.sendBinaryTo) {
        this.transport.sendBinaryTo(targetPeerId, buffer, options);
        return;
      }
      this.transport.sendBinary(buffer, options);
      return;
    }
    if (this.ws && this.ws.readyState === WebSocket.OPEN) {
      if (options?.ephemeral && this.ws.bufferedAmount > MAX_OUTGOING_BUFFERED_BYTES) {
        this.localDroppedEphemeralCount += 1;
        return;
      }
      this.diagnostics.recordTx(byteLength);
      if (!isNonMutation) this.lastMutationTxAt = Date.now();
      this.ws.send(buffer as any);
    }
  }

  public beginPeerSnapshot(targetPeerId: string | number): number | undefined {
    if (!this.transport || !this.transport.isOpen()) return undefined;
    const res = this.transport.beginPeerSnapshot?.(targetPeerId);
    return typeof res === 'number' ? res : undefined;
  }

  public finishPeerSnapshot(targetPeerId: string | number, snapshotSeq?: number): void {
    if (!this.transport || !this.transport.isOpen()) return;
    this.transport.finishPeerSnapshot?.(targetPeerId, snapshotSeq);
  }

  public canIncrementalCatchUp(sinceSeq: number): boolean {
    if (!this.transport || !this.transport.isOpen()) return false;
    return this.transport.canIncrementalCatchUp?.(sinceSeq) ?? false;
  }

  public replayIncrementalToPeer(targetPeerId: string | number, sinceSeq: number): boolean {
    if (!this.transport || !this.transport.isOpen()) return false;
    return this.transport.replayIncrementalToPeer?.(targetPeerId, sinceSeq) ?? false;
  }

  private notifyHandlers(msg: MultiplayerMessage) {
    this.messageHandlers.forEach((handler) => handler(msg));
  }

  // --- Binary Packet Encoding & Decoding ---

  public decodeBinaryPacket(buf: ArrayBuffer): MultiplayerMessage | null {
    if (buf.byteLength < 11 || buf.byteLength > MAX_BINARY_PACKET_BYTES) return null;
    const view = new DataView(buf);

    // Verify magic
    if (view.getUint8(0) !== BINARY_MAGIC_0 || view.getUint8(1) !== BINARY_MAGIC_1) {
      return null;
    }

    const code = view.getUint8(2);
    const lamport = view.getUint32(3, true);
    this.updateLamport(lamport);

    const payloadLen = view.getUint32(7, true);
    if (payloadLen > MAX_BINARY_PACKET_BYTES || 11 + payloadLen > buf.byteLength) return null;
    const payloadBytes = new Uint8Array(buf, 11, payloadLen);
    const decoder = sharedTextDecoder;

    switch (code) {
      case CODE_STROKE_START: {
        // Compact binary slim STROKE_START v2 (first byte 0x02, never collides with JSON '{' 0x7b)
        if (payloadBytes.byteLength >= 1 && payloadBytes[0] === STROKE_START_BINARY_VERSION) {
          if (payloadBytes.byteLength < 22) return null;
          const pView = new DataView(
            payloadBytes.buffer,
            payloadBytes.byteOffset,
            payloadBytes.byteLength
          );
          const flags = payloadBytes[1];
          const profileHash = bytes16ToHex32(payloadBytes.subarray(2, 18));
          const toolCode = payloadBytes[18];
          const tool: ToolType = TOOL_TYPES_LIST[toolCode] || 'brush';

          let offset = 19;
          const layerIdLen = payloadBytes[offset++];
          if (layerIdLen === 0 || offset + layerIdLen + 2 > payloadBytes.byteLength) return null;
          const layerId = decoder.decode(payloadBytes.subarray(offset, offset + layerIdLen));
          offset += layerIdLen;

          const strokeIdLen = payloadBytes[offset++];
          if (strokeIdLen === 0 || strokeIdLen > 128 || offset + strokeIdLen + 1 > payloadBytes.byteLength) {
            return null;
          }
          const strokeId = decoder.decode(payloadBytes.subarray(offset, offset + strokeIdLen));
          offset += strokeIdLen;

          const peerIdLen = payloadBytes[offset++];
          if (peerIdLen === 0 || peerIdLen > 128 || offset + peerIdLen + 12 > payloadBytes.byteLength) {
            return null;
          }
          const peerId = decoder.decode(payloadBytes.subarray(offset, offset + peerIdLen));
          offset += peerIdLen;

          const x = pView.getFloat32(offset, true);
          const y = pView.getFloat32(offset + 4, true);
          const pressure = pView.getUint16(offset + 8, true) / 65535;
          const width = Math.max(0.1, Math.min(2000, pView.getUint16(offset + 10, true) / 16));
          offset += 12;
          if (!Number.isFinite(x) || !Number.isFinite(y)) return null;

          let tiltX = 0;
          let tiltY = 0;
          let twist = 0;
          if ((flags & STROKE_START_FLAG_HAS_TILT_TWIST) !== 0) {
            if (offset + 3 > payloadBytes.byteLength) return null;
            tiltX = pView.getInt8(offset);
            tiltY = pView.getInt8(offset + 1);
            twist = (payloadBytes[offset + 2] * 360) / 255;
            offset += 3;
          }

          let color = '#000000';
          if ((flags & STROKE_START_FLAG_COLOR_RGB24) !== 0) {
            if (offset + 3 > payloadBytes.byteLength) return null;
            color =
              '#' +
              payloadBytes[offset].toString(16).padStart(2, '0') +
              payloadBytes[offset + 1].toString(16).padStart(2, '0') +
              payloadBytes[offset + 2].toString(16).padStart(2, '0');
            offset += 3;
          } else if ((flags & STROKE_START_FLAG_COLOR_STR) !== 0) {
            if (offset + 1 > payloadBytes.byteLength) return null;
            const colorLen = payloadBytes[offset++];
            if (colorLen === 0 || colorLen > 64 || offset + colorLen > payloadBytes.byteLength) {
              return null;
            }
            color = decoder.decode(payloadBytes.subarray(offset, offset + colorLen));
            offset += colorLen;
          }

          let size = 10;
          if ((flags & STROKE_START_FLAG_HAS_SIZE) !== 0) {
            if (offset + 4 > payloadBytes.byteLength) return null;
            const rawSize = pView.getFloat32(offset, true);
            offset += 4;
            if (!Number.isFinite(rawSize)) return null;
            size = Math.max(0.5, Math.min(2000, rawSize));
          }

          let opacity = 1;
          if ((flags & STROKE_START_FLAG_HAS_OPACITY) !== 0) {
            if (offset + 2 > payloadBytes.byteLength) return null;
            const rawOp10k = pView.getUint16(offset, true);
            offset += 2;
            if (rawOp10k > 10000) return null;
            opacity = rawOp10k / 10000;
          }

          if (offset !== payloadBytes.byteLength) return null;

          const cachedProfile = this.getCachedBrushProfile(profileHash);
          const overrides: BrushProfileDynamicOverrides = { color, size, opacity };
          const resolvedSettings: BrushSettings = cachedProfile
            ? applyBrushProfileOverrides(cachedProfile.baseSettings, overrides)
            : ({
                size,
                minSizeFactor: 0.1,
                color,
                opacity,
                flow: 1,
                spacing: 0.1,
                usePressure: true,
                smoothing: true,
                stabilization: 0,
                hardness: 0.9,
              } as BrushSettings);
          const peerMeta = this.peerMetaById.get(peerId);

          return {
            type: 'STROKE_START',
            senderId: peerId,
            strokeId,
            peerId,
            peerName: peerMeta?.name || 'Peer',
            peerColor: peerMeta?.color || '#38bdf8',
            layerId,
            brushSettings: resolvedSettings,
            ...(cachedProfile?.assetRefs ? { brushAssetRefs: cachedProfile.assetRefs } : {}),
            brushProfileHash: profileHash,
            ...(cachedProfile ? {} : { brushProfileCacheMiss: true }),
            tool,
            startPoint: {
              x,
              y,
              pressure,
              width,
              ...((flags & STROKE_START_FLAG_HAS_TILT_TWIST) !== 0
                ? { tiltX, tiltY, twist }
                : {}),
              ...((flags & STROKE_START_FLAG_IS_CORNER) !== 0 ? { isCorner: true } : {}),
            },
          } as StrokeStartMessage;
        }

        // Legacy & full-profile JSON STROKE_START
        const jsonStr = decoder.decode(payloadBytes);
        const data = JSON.parse(jsonStr);
        const safeSettings = sanitizeRemoteBrushSettings(data?.brushSettings);
        if (!safeSettings || !isValidRemotePoint(data?.startPoint)) return null;
        const safeAssetRefs = sanitizeBrushAssetRefs(data.brushAssetRefs);
        const computedProfile = computeBrushProfileHash(safeSettings, safeAssetRefs);
        const effectiveProfileHash = isValidBrushAssetHash(data.brushProfileHash)
          ? data.brushProfileHash
          : computedProfile.hash;
        this.registerBrushProfile(computedProfile.hash, computedProfile.canonicalProfile);
        if (effectiveProfileHash !== computedProfile.hash) {
          this.registerBrushProfile(effectiveProfileHash, computedProfile.canonicalProfile);
        }
        const peerName = String(data.peerName || 'Peer').slice(0, 64);
        const peerColor = String(data.peerColor || '#38bdf8').slice(0, 32);
        this.recordPeerMeta(data.peerId, peerName, peerColor);

        return {
          type: 'STROKE_START',
          senderId: data.peerId,
          strokeId: String(data.strokeId || '').slice(0, 128),
          peerId: data.peerId,
          peerName,
          peerColor,
          layerId: String(data.layerId || '').slice(0, 256),
          brushSettings: safeSettings,
          brushAssetRefs: safeAssetRefs,
          brushProfileHash: effectiveProfileHash,
          tool: TOOL_TYPES_LIST.includes(data.tool) ? data.tool : 'brush',
          startPoint: {
            ...data.startPoint,
            pressure: Number.isFinite(data.startPoint.pressure)
              ? Math.max(0, Math.min(1, data.startPoint.pressure))
              : 0.5,
            width: Number.isFinite(data.startPoint.width)
              ? Math.max(0.1, Math.min(2000, data.startPoint.width))
              : safeSettings.size,
          },
        } as StrokeStartMessage;
      }

      case CODE_STROKE_CHUNK: {
        if (payloadBytes.byteLength < 6) return null;
        const pView = new DataView(payloadBytes.buffer, payloadBytes.byteOffset, payloadBytes.byteLength);
        const firstWord = pView.getUint16(0, true);
        if (firstWord === STROKE_CHUNK_V2_MARKER) {
          return decodeStrokeChunkV2Payload(payloadBytes.subarray(2));
        }

        // Legacy V1 Format: [strokeIdLen: u16, strokeId, peerIdLen: u16, peerId, pointCount: u16, points (20B each)...]
        let offset = 0;
        const sIdLen = firstWord;
        offset += 2;
        if (sIdLen > 256 || offset + sIdLen + 4 > payloadBytes.byteLength) return null;
        const strokeId = decoder.decode(payloadBytes.subarray(offset, offset + sIdLen));
        offset += sIdLen;

        const pIdLen = pView.getUint16(offset, true);
        offset += 2;
        if (pIdLen > 256 || offset + pIdLen + 2 > payloadBytes.byteLength) return null;
        const peerId = decoder.decode(payloadBytes.subarray(offset, offset + pIdLen));
        offset += pIdLen;

        const pointCount = pView.getUint16(offset, true);
        offset += 2;
        if (
          pointCount > MAX_STROKE_CHUNK_POINTS ||
          offset + pointCount * STROKE_CHUNK_POINT_STRIDE > payloadBytes.byteLength
        ) {
          return null;
        }

        const points: Point[] = [];
        for (let i = 0; i < pointCount; i++) {
          const x = pView.getFloat32(offset, true);
          const y = pView.getFloat32(offset + 4, true);
          const pressure = pView.getFloat32(offset + 8, true);
          const width = pView.getFloat32(offset + 12, true);
          const tiltX = pView.getInt8(offset + 16);
          const tiltY = pView.getInt8(offset + 17);
          const twist = (pView.getUint8(offset + 18) * 360) / 255;
          const flags = pView.getUint8(offset + 19);
          offset += STROKE_CHUNK_POINT_STRIDE;
          if (!Number.isFinite(x) || !Number.isFinite(y)) continue;
          points.push({
            x,
            y,
            pressure: Number.isFinite(pressure) ? Math.max(0, Math.min(1, pressure)) : 0.5,
            width: Number.isFinite(width) ? Math.max(0.1, Math.min(2000, width)) : 1,
            tiltX,
            tiltY,
            twist,
            isCorner: (flags & 1) !== 0,
          });
        }

        if (points.length === 0) return null;

        return {
          type: 'STROKE_CHUNK',
          senderId: peerId,
          strokeId,
          peerId,
          points,
        } as StrokeChunkMessage;
      }

      case CODE_STROKE_CHUNK_V2: {
        return decodeStrokeChunkV2Payload(payloadBytes);
      }

      case CODE_BRUSH_PROFILE_DATA: {
        // Format: [hashLen: u8 (32), hashUtf8 (32B), flags: u8, (if LZ4: rawLen: u32 LE), jsonBytes...]
        if (payloadBytes.byteLength < 35) return null;
        const hashLen = payloadBytes[0];
        if (hashLen !== 32 || 1 + hashLen + 1 >= payloadBytes.byteLength) return null;
        const hash = decoder.decode(payloadBytes.subarray(1, 33));
        if (!isValidBrushAssetHash(hash)) return null;

        const flags = payloadBytes[33];
        let jsonBytes: Uint8Array;
        if ((flags & BRUSH_PROFILE_FLAG_LZ4) !== 0) {
          if (payloadBytes.byteLength < 39) return null;
          const pView = new DataView(
            payloadBytes.buffer,
            payloadBytes.byteOffset,
            payloadBytes.byteLength
          );
          const uncompressedLen = pView.getUint32(34, true);
          if (uncompressedLen === 0 || uncompressedLen > MAX_BRUSH_PROFILE_BYTES) return null;
          const decompressed = lz4DecompressBlock(
            payloadBytes.subarray(38),
            uncompressedLen,
            MAX_BRUSH_PROFILE_BYTES
          );
          if (!decompressed) return null;
          jsonBytes = decompressed;
        } else {
          const rawLen = payloadBytes.byteLength - 34;
          if (rawLen === 0 || rawLen > MAX_BRUSH_PROFILE_BYTES) return null;
          jsonBytes = payloadBytes.subarray(34);
        }

        const parsedObj = JSON.parse(decoder.decode(jsonBytes)) as {
          settings?: unknown;
          assetRefs?: unknown;
        };
        const safeSettings = sanitizeRemoteBrushSettings(parsedObj?.settings);
        if (!safeSettings) return null;
        const safeRefs = sanitizeBrushAssetRefs(parsedObj?.assetRefs);
        const computed = computeBrushProfileHash(safeSettings, safeRefs);
        if (computed.hash !== hash) return null;

        this.registerBrushProfile(hash, computed.canonicalProfile);
        return {
          type: 'BRUSH_PROFILE_DATA',
          hash,
          brushSettings: computed.canonicalProfile.baseSettings,
          ...(computed.canonicalProfile.assetRefs
            ? { brushAssetRefs: computed.canonicalProfile.assetRefs }
            : {}),
        } as BrushProfileDataMessage;
      }

      case CODE_BRUSH_PROFILE_REQUEST: {
        const jsonStr = decoder.decode(payloadBytes);
        const data = JSON.parse(jsonStr);
        if (!isValidBrushAssetHash(data?.hash)) return null;
        const reqSenderId =
          typeof data.senderId === 'string' || typeof data.senderId === 'number'
            ? data.senderId
            : undefined;
        return {
          type: 'BRUSH_PROFILE_REQUEST',
          ...(reqSenderId !== undefined ? { senderId: reqSenderId } : {}),
          hash: data.hash,
          targetPeerId: data.targetPeerId,
        } as BrushProfileRequestMessage;
      }

      case CODE_STROKE_FINISH: {
        const jsonStr = decoder.decode(payloadBytes);
        const data = JSON.parse(jsonStr);
        const expectedTileCount =
          typeof data.expectedTileCount === 'number' &&
          Number.isInteger(data.expectedTileCount) &&
          data.expectedTileCount >= 0 &&
          data.expectedTileCount <= 65536
            ? data.expectedTileCount
            : undefined;
        const commitSeq =
          typeof data.commitSeq === 'number' &&
          Number.isSafeInteger(data.commitSeq) &&
          data.commitSeq >= 0
            ? data.commitSeq
            : undefined;
        return {
          type: 'STROKE_FINISH',
          senderId: data.peerId,
          strokeId: String(data.strokeId || '').slice(0, 128),
          peerId: data.peerId,
          layerId: String(data.layerId || '').slice(0, 256),
          endPoint: data.endPoint,
          dirtyRect: data.dirtyRect,
          vectorStroke: data.vectorStroke,
          ...(expectedTileCount !== undefined ? { expectedTileCount } : {}),
          ...(commitSeq !== undefined ? { commitSeq } : {}),
        } as StrokeFinishMessage;
      }

      case CODE_TILE_DELTA: {
        // Format: [layerIdLen: u16, layerId, serializedTilePacket (EMPTY|RAW|LZ4|SOLID|SUBRECT_LZ4)...]
        let offset = 0;
        if (payloadBytes.byteLength < 2) return null;
        const pView = new DataView(payloadBytes.buffer, payloadBytes.byteOffset, payloadBytes.byteLength);
        const layerIdLen = pView.getUint16(offset, true);
        offset += 2;
        if (layerIdLen === 0 || layerIdLen > 256 || offset + layerIdLen > payloadBytes.byteLength) {
          return null;
        }
        const layerId = decoder.decode(payloadBytes.subarray(offset, offset + layerIdLen));
        offset += layerIdLen;

        const tilePacket = payloadBytes.subarray(offset);
        if (isNativeCanvasActive()) {
          if (tilePacket.byteLength < TILE_PACKET_HEADER_BYTES) return null;
          const tView = new DataView(
            tilePacket.buffer,
            tilePacket.byteOffset,
            tilePacket.byteLength
          );
          const tileX = tView.getInt32(0, true);
          const tileY = tView.getInt32(4, true);
          const format = wireCodeToFormat(tView.getUint8(8));
          const version = tView.getUint32(9, true);
          const codec = tView.getUint8(13);
          if (
            !format ||
            tileX < 0 ||
            tileY < 0 ||
            tileX >= MAX_TILE_COORD ||
            tileY >= MAX_TILE_COORD
          ) {
            return null;
          }
          const tileKey = `${layerId}:${tileX}:${tileY}`;
          if (codec !== TILE_CODEC_EMPTY) {
            this.knownRemoteBaseTiles.add(tileKey);
          } else {
            this.knownRemoteBaseTiles.delete(tileKey);
          }
          return {
            type: 'BINARY_TILE',
            layerId,
            tileX,
            tileY,
            format,
            version,
            data: null,
            rawPacket: tilePacket.slice(),
          } as TileStreamMessage;
        }

        const decoded = deserializeWireTilePacketStrict(layerId, tilePacket);
        if (!decoded) return null;

        if (decoded.kind === 'full') {
          const tile = decoded.tile;
          if (
            tile.tileX < 0 ||
            tile.tileY < 0 ||
            tile.tileX >= MAX_TILE_COORD ||
            tile.tileY >= MAX_TILE_COORD
          ) {
            return null;
          }
          const tileKey = `${layerId}:${tile.tileX}:${tile.tileY}`;
          if (tile.data !== null) {
            this.knownRemoteBaseTiles.add(tileKey);
          } else {
            this.knownRemoteBaseTiles.delete(tileKey);
          }
          return {
            type: 'BINARY_TILE',
            layerId,
            tileX: tile.tileX,
            tileY: tile.tileY,
            format: tile.format,
            version: tile.version,
            data: tile.data,
            rawPacket: tilePacket.slice(),
          } as TileStreamMessage;
        }

        if (
          decoded.tileX < 0 ||
          decoded.tileY < 0 ||
          decoded.tileX >= MAX_TILE_COORD ||
          decoded.tileY >= MAX_TILE_COORD
        ) {
          return null;
        }
        return {
          type: 'BINARY_TILE',
          layerId,
          tileX: decoded.tileX,
          tileY: decoded.tileY,
          format: decoded.format,
          version: decoded.version,
          data: null,
          subRect: decoded.subRect,
          rawPacket: tilePacket.slice(),
        } as TileStreamMessage;
      }

      case CODE_BRUSH_ASSET_DATA: {
        // Format: [hashLen: u8, hashUtf8, mimeLen: u8, mimeUtf8, rawBytes...]
        if (payloadBytes.byteLength < 4) return null;
        let offset = 0;
        const hashLen = payloadBytes[offset++];
        if (hashLen === 0 || hashLen > 64 || offset + hashLen + 1 > payloadBytes.byteLength) {
          return null;
        }
        const hash = decoder.decode(payloadBytes.subarray(offset, offset + hashLen));
        offset += hashLen;

        const mimeLen = payloadBytes[offset++];
        if (mimeLen === 0 || mimeLen > 64 || offset + mimeLen > payloadBytes.byteLength) {
          return null;
        }
        const mime = decoder.decode(payloadBytes.subarray(offset, offset + mimeLen));
        offset += mimeLen;

        const rawLen = payloadBytes.byteLength - offset;
        if (
          !isValidBrushAssetHash(hash) ||
          !isAllowedBrushAssetMime(mime) ||
          rawLen === 0 ||
          rawLen > MAX_BRUSH_ASSET_BYTES
        ) {
          return null;
        }

        const data = new Uint8Array(rawLen);
        data.set(payloadBytes.subarray(offset));
        return {
          type: 'BRUSH_ASSET_DATA',
          hash,
          mime,
          data,
        } as BrushAssetDataMessage;
      }

      case CODE_BRUSH_ASSET_REQUEST: {
        const jsonStr = decoder.decode(payloadBytes);
        const data = JSON.parse(jsonStr);
        if (!isValidBrushAssetHash(data?.hash)) return null;
        const reqSenderId =
          typeof data.senderId === 'string' || typeof data.senderId === 'number'
            ? data.senderId
            : undefined;
        return {
          type: 'BRUSH_ASSET_REQUEST',
          ...(reqSenderId !== undefined ? { senderId: reqSenderId } : {}),
          hash: data.hash,
          targetPeerId: data.targetPeerId,
        } as BrushAssetRequestMessage;
      }

      case CODE_CURSOR_MOVE: {
        if (payloadBytes.byteLength < 12) return null;
        const pView = new DataView(payloadBytes.buffer, payloadBytes.byteOffset, payloadBytes.byteLength);
        let offset = 0;
        const pIdLen = pView.getUint16(offset, true);
        offset += 2;
        if (offset + pIdLen + 10 > payloadBytes.byteLength) return null;
        const peerId = decoder.decode(payloadBytes.subarray(offset, offset + pIdLen));
        offset += pIdLen;

        const x = pView.getFloat32(offset, true);
        const y = pView.getFloat32(offset + 4, true);
        if (!Number.isFinite(x) || !Number.isFinite(y)) return null;
        const isDrawing = pView.getUint8(offset + 8) === 1;
        const toolCode = pView.getUint8(offset + 9);
        const tool: ToolType = TOOL_TYPES_LIST[toolCode] || 'brush';

        return {
          type: 'CURSOR_MOVE',
          senderId: peerId,
          peerId,
          x,
          y,
          isDrawing,
          tool,
        } as CursorMoveMessage;
      }

      case CODE_SELECTIVE_UNDO: {
        const jsonStr = decoder.decode(payloadBytes);
        const data = JSON.parse(jsonStr);
        return {
          type: 'SELECTIVE_UNDO',
          senderId: data.peerId,
          strokeId: data.strokeId,
          peerId: data.peerId,
          lamport: data.lamport,
        } as SelectiveUndoMessage;
      }

      case CODE_LAYER_MASK_DATA: {
        // Format: [layerIdLen: u16, layerId, flags: u8, x: u32, y: u32, width: u32, height: u32, body...]
        if (payloadBytes.byteLength < 19) return null;
        const pView = new DataView(payloadBytes.buffer, payloadBytes.byteOffset, payloadBytes.byteLength);
        let offset = 0;
        const layerIdLen = pView.getUint16(offset, true);
        offset += 2;
        if (layerIdLen === 0 || layerIdLen > 256 || offset + layerIdLen + 17 > payloadBytes.byteLength) {
          return null;
        }
        const layerId = decoder.decode(payloadBytes.subarray(offset, offset + layerIdLen));
        offset += layerIdLen;

        const flags = payloadBytes[offset++];
        const x = pView.getUint32(offset, true);
        const y = pView.getUint32(offset + 4, true);
        const width = pView.getUint32(offset + 8, true);
        const height = pView.getUint32(offset + 12, true);
        offset += 16;

        if (
          x > MAX_SYNC_CANVAS_DIM ||
          y > MAX_SYNC_CANVAS_DIM ||
          width === 0 ||
          height === 0 ||
          width > MAX_SYNC_CANVAS_DIM ||
          height > MAX_SYNC_CANVAS_DIM
        ) {
          return null;
        }

        const isFullReplace = (flags & MASK_FLAG_FULL_REPLACE) !== 0;
        const isCompressed = (flags & MASK_FLAG_LZ4) !== 0;
        const isSolidFill = (flags & MASK_FLAG_SOLID_FILL) !== 0;
        const body = payloadBytes.subarray(offset);

        if (isSolidFill) {
          if (body.byteLength !== 1) return null;
          return {
            type: 'BINARY_MASK',
            layerId,
            x,
            y,
            width,
            height,
            isFullReplace,
            solidFill: body[0],
            data: null,
          } as LayerMaskDataMessage;
        }

        const expectedPixels = width * height;
        if (expectedPixels <= 0 || expectedPixels > MAX_MASK_DECODE_BYTES) return null;

        let data: Uint8Array | null;
        if (isCompressed) {
          data = lz4DecompressBlock(body, expectedPixels, MAX_MASK_DECODE_BYTES);
          if (!data) return null;
        } else {
          if (body.byteLength !== expectedPixels) return null;
          data = new Uint8Array(expectedPixels);
          data.set(body);
        }

        return {
          type: 'BINARY_MASK',
          layerId,
          x,
          y,
          width,
          height,
          isFullReplace,
          data,
        } as LayerMaskDataMessage;
      }

      case CODE_CAMERA_SYNC: {
        // Format: [peerIdLen: u16, peerIdUtf8, centerX: f32, centerY: f32, zoom: f32, rotation: f32, vw: u16, vh: u16, flags: u8]
        if (payloadBytes.byteLength < 23) return null;
        const pView = new DataView(payloadBytes.buffer, payloadBytes.byteOffset, payloadBytes.byteLength);
        let offset = 0;
        const pIdLen = pView.getUint16(offset, true);
        offset += 2;
        if (pIdLen === 0 || pIdLen > 256 || offset + pIdLen + 21 > payloadBytes.byteLength) {
          return null;
        }
        const peerId = decoder.decode(payloadBytes.subarray(offset, offset + pIdLen));
        offset += pIdLen;

        const centerX = pView.getFloat32(offset, true);
        const centerY = pView.getFloat32(offset + 4, true);
        const zoom = pView.getFloat32(offset + 8, true);
        const rotation = pView.getFloat32(offset + 12, true);
        const viewportWidth = pView.getUint16(offset + 16, true);
        const viewportHeight = pView.getUint16(offset + 18, true);
        const flags = payloadBytes[offset + 20];

        if (
          !Number.isFinite(centerX) ||
          !Number.isFinite(centerY) ||
          !Number.isFinite(zoom) ||
          zoom <= 0 ||
          !Number.isFinite(rotation)
        ) {
          return null;
        }

        return {
          type: 'CAMERA_SYNC',
          senderId: peerId,
          peerId,
          centerX,
          centerY,
          zoom: Math.max(0.01, Math.min(32, zoom)),
          rotation,
          flipX: (flags & CAMERA_FLAG_FLIP_X) !== 0,
          flipY: (flags & CAMERA_FLAG_FLIP_Y) !== 0,
          viewportWidth,
          viewportHeight,
        } as CameraSyncMessage;
      }

      default:
        return null;
    }
  }

  // --- Drawing Events via Compact Binary Packets ---

  public sendBrushAssetData(
    hash: string,
    mime: string,
    bytes: Uint8Array,
    targetPeerId?: string | number
  ) {
    if (!this.isConnected()) return;
    if (!isValidBrushAssetHash(hash) || !isAllowedBrushAssetMime(mime)) return;
    if (bytes.byteLength === 0 || bytes.byteLength > MAX_BRUSH_ASSET_BYTES) return;

    const hashBytes = sharedTextEncoder.encode(hash);
    const mimeBytes = sharedTextEncoder.encode(mime);
    const payloadSize = 1 + hashBytes.length + 1 + mimeBytes.length + bytes.byteLength;
    const packet = new Uint8Array(11 + payloadSize);
    const view = new DataView(packet.buffer);

    view.setUint8(0, BINARY_MAGIC_0);
    view.setUint8(1, BINARY_MAGIC_1);
    view.setUint8(2, CODE_BRUSH_ASSET_DATA);
    view.setUint32(3, this.getNextLamport(), true);
    view.setUint32(7, payloadSize, true);

    let offset = 11;
    packet[offset++] = hashBytes.length;
    packet.set(hashBytes, offset);
    offset += hashBytes.length;
    packet[offset++] = mimeBytes.length;
    packet.set(mimeBytes, offset);
    offset += mimeBytes.length;
    packet.set(bytes, offset);

    if (targetPeerId !== undefined) {
      const peerKey = String(targetPeerId);
      let peerSet = this.sentAssetHashesByPeer.get(peerKey);
      if (!peerSet) {
        peerSet = new Set();
        this.sentAssetHashesByPeer.set(peerKey, peerSet);
      }
      peerSet.add(hash);
    } else {
      this.sentAssetHashes.add(hash);
    }

    this.sendBinary(packet, targetPeerId);
  }

  public sendBrushAssetRequest(hash: string, targetPeerId?: string | number) {
    if (!this.isConnected() || !isValidBrushAssetHash(hash)) return;

    const payloadObj: Record<string, unknown> = { hash, targetPeerId };
    if (this.currentPeer?.id !== undefined) {
      payloadObj.senderId = this.currentPeer.id;
    }
    const payloadBytes = sharedTextEncoder.encode(JSON.stringify(payloadObj));
    const packet = new Uint8Array(11 + payloadBytes.length);
    const view = new DataView(packet.buffer);
    view.setUint8(0, BINARY_MAGIC_0);
    view.setUint8(1, BINARY_MAGIC_1);
    view.setUint8(2, CODE_BRUSH_ASSET_REQUEST);
    view.setUint32(3, this.getNextLamport(), true);
    view.setUint32(7, payloadBytes.length, true);
    packet.set(payloadBytes, 11);

    this.sendBinary(packet);
  }

  public sendBrushProfileData(hash: string, targetPeerId?: string | number): boolean {
    if (!this.isConnected() || !isValidBrushAssetHash(hash)) return false;
    const cached = this.getCachedBrushProfile(hash);
    if (!cached) return false;

    const jsonStr = JSON.stringify(
      cached.assetRefs
        ? { settings: cached.baseSettings, assetRefs: cached.assetRefs }
        : { settings: cached.baseSettings }
    );
    const rawJsonBytes = sharedTextEncoder.encode(jsonStr);
    if (rawJsonBytes.byteLength === 0 || rawJsonBytes.byteLength > MAX_BRUSH_PROFILE_BYTES) {
      return false;
    }

    const compressed = lz4CompressBlock(rawJsonBytes);
    const useLz4 = compressed.byteLength + 4 < rawJsonBytes.byteLength;
    const flags = useLz4 ? BRUSH_PROFILE_FLAG_LZ4 : 0;
    const body = useLz4 ? compressed : rawJsonBytes;

    const hashBytes = sharedTextEncoder.encode(hash);
    const payloadSize = 1 + hashBytes.length + 1 + (useLz4 ? 4 : 0) + body.byteLength;
    const packet = new Uint8Array(11 + payloadSize);
    const view = new DataView(packet.buffer);

    view.setUint8(0, BINARY_MAGIC_0);
    view.setUint8(1, BINARY_MAGIC_1);
    view.setUint8(2, CODE_BRUSH_PROFILE_DATA);
    view.setUint32(3, this.getNextLamport(), true);
    view.setUint32(7, payloadSize, true);

    let offset = 11;
    packet[offset++] = hashBytes.length;
    packet.set(hashBytes, offset);
    offset += hashBytes.length;
    packet[offset++] = flags;
    if (useLz4) {
      view.setUint32(offset, rawJsonBytes.byteLength, true);
      offset += 4;
    }
    packet.set(body, offset);

    if (targetPeerId === undefined) {
      this.sentBrushProfileHashes.add(hash);
    }
    this.sendBinary(packet, targetPeerId);
    return true;
  }

  public sendBrushProfileRequest(hash: string, targetPeerId?: string | number): void {
    if (!this.isConnected() || !isValidBrushAssetHash(hash)) return;

    const payloadObj: Record<string, unknown> = { hash };
    if (targetPeerId !== undefined) {
      payloadObj.targetPeerId = targetPeerId;
    }
    if (this.currentPeer?.id !== undefined) {
      payloadObj.senderId = this.currentPeer.id;
    }
    const payloadBytes = sharedTextEncoder.encode(JSON.stringify(payloadObj));
    const packet = new Uint8Array(11 + payloadBytes.length);
    const view = new DataView(packet.buffer);
    view.setUint8(0, BINARY_MAGIC_0);
    view.setUint8(1, BINARY_MAGIC_1);
    view.setUint8(2, CODE_BRUSH_PROFILE_REQUEST);
    view.setUint32(3, this.getNextLamport(), true);
    view.setUint32(7, payloadBytes.length, true);
    packet.set(payloadBytes, 11);

    this.sendBinary(packet);
  }

  private encodeSlimStrokeStartPacket(
    strokeId: string,
    peerId: string,
    layerId: string,
    profileHash: string,
    tool: ToolType,
    startPoint: Point,
    overrides: BrushProfileDynamicOverrides
  ): Uint8Array | null {
    const hashBytes16 = hex32ToBytes16(profileHash);
    if (!hashBytes16) return null;

    const layerIdBytes = sharedTextEncoder.encode(layerId);
    const strokeIdBytes = sharedTextEncoder.encode(strokeId);
    const peerIdBytes = sharedTextEncoder.encode(peerId);
    if (
      layerIdBytes.length === 0 ||
      layerIdBytes.length > 255 ||
      strokeIdBytes.length === 0 ||
      strokeIdBytes.length > 128 ||
      peerIdBytes.length === 0 ||
      peerIdBytes.length > 128
    ) {
      return null;
    }

    const tx = quantizeTilt(startPoint.tiltX);
    const ty = quantizeTilt(startPoint.tiltY);
    const tw = quantizeTwistByte(startPoint.twist);
    const hasTiltTwist = tx !== 0 || ty !== 0 || tw !== 0;

    let flags = 0;
    if (startPoint.isCorner) flags |= STROKE_START_FLAG_IS_CORNER;
    if (hasTiltTwist) flags |= STROKE_START_FLAG_HAS_TILT_TWIST;

    const color = typeof overrides.color === 'string' && overrides.color ? overrides.color : '#000000';
    let colorRgb: [number, number, number] | null = null;
    let colorStrBytes: Uint8Array | null = null;
    if (color !== '#000000') {
      const rgbMatch = RGB24_HEX_RE.exec(color);
      if (rgbMatch) {
        flags |= STROKE_START_FLAG_COLOR_RGB24;
        colorRgb = [
          parseInt(rgbMatch[1], 16),
          parseInt(rgbMatch[2], 16),
          parseInt(rgbMatch[3], 16),
        ];
      } else {
        const encodedColor = sharedTextEncoder.encode(color.slice(0, 64));
        if (encodedColor.length > 0 && encodedColor.length <= 64) {
          flags |= STROKE_START_FLAG_COLOR_STR;
          colorStrBytes = encodedColor;
        }
      }
    }

    const size = Number.isFinite(overrides.size)
      ? Math.max(0.5, Math.min(2000, overrides.size))
      : 10;
    const hasSize = size !== 10;
    if (hasSize) flags |= STROKE_START_FLAG_HAS_SIZE;

    const opacity = Number.isFinite(overrides.opacity)
      ? Math.max(0, Math.min(1, overrides.opacity))
      : 1;
    const opacity10k = Math.round(opacity * 10000);
    const hasOpacity = opacity10k !== 10000;
    if (hasOpacity) flags |= STROKE_START_FLAG_HAS_OPACITY;

    const payloadSize =
      1 + // version
      1 + // flags
      16 + // profileHash16
      1 + // toolCode
      1 +
      layerIdBytes.length +
      1 +
      strokeIdBytes.length +
      1 +
      peerIdBytes.length +
      12 + // startPoint (x f32, y f32, pressure u16, width u16)
      (hasTiltTwist ? 3 : 0) +
      (colorRgb ? 3 : colorStrBytes ? 1 + colorStrBytes.length : 0) +
      (hasSize ? 4 : 0) +
      (hasOpacity ? 2 : 0);

    const packet = new Uint8Array(11 + payloadSize);
    const view = new DataView(packet.buffer);
    view.setUint8(0, BINARY_MAGIC_0);
    view.setUint8(1, BINARY_MAGIC_1);
    view.setUint8(2, CODE_STROKE_START);
    view.setUint32(3, this.getNextLamport(), true);
    view.setUint32(7, payloadSize, true);

    let offset = 11;
    packet[offset++] = STROKE_START_BINARY_VERSION;
    packet[offset++] = flags;
    packet.set(hashBytes16, offset);
    offset += 16;
    const toolIdx = Math.max(0, TOOL_TYPES_LIST.indexOf(tool));
    packet[offset++] = toolIdx;

    packet[offset++] = layerIdBytes.length;
    packet.set(layerIdBytes, offset);
    offset += layerIdBytes.length;

    packet[offset++] = strokeIdBytes.length;
    packet.set(strokeIdBytes, offset);
    offset += strokeIdBytes.length;

    packet[offset++] = peerIdBytes.length;
    packet.set(peerIdBytes, offset);
    offset += peerIdBytes.length;

    view.setFloat32(offset, startPoint.x, true);
    view.setFloat32(offset + 4, startPoint.y, true);
    view.setUint16(offset + 8, quantizePressureU16(startPoint.pressure), true);
    view.setUint16(offset + 10, quantizeWidthU16(startPoint.width), true);
    offset += 12;

    if (hasTiltTwist) {
      view.setInt8(offset, tx);
      view.setInt8(offset + 1, ty);
      packet[offset + 2] = tw;
      offset += 3;
    }
    if (colorRgb) {
      packet[offset++] = colorRgb[0];
      packet[offset++] = colorRgb[1];
      packet[offset++] = colorRgb[2];
    } else if (colorStrBytes) {
      packet[offset++] = colorStrBytes.length;
      packet.set(colorStrBytes, offset);
      offset += colorStrBytes.length;
    }
    if (hasSize) {
      view.setFloat32(offset, size, true);
      offset += 4;
    }
    if (hasOpacity) {
      view.setUint16(offset, opacity10k, true);
      offset += 2;
    }

    return packet;
  }

  public sendStrokeStart(
    strokeId: string,
    layerId: string,
    brushSettings: BrushSettings,
    tool: ToolType,
    startPoint: Point
  ) {
    if (!this.isConnected() || !this.currentPeer || !this.canSendMutation()) return;

    // Suppress redundant CURSOR_MOVE packets while this stroke streams live points
    this.activeStrokeId = strokeId;
    this.activeStrokeTool = tool;
    this.lastEmittedStrokePoints.set(strokeId, startPoint);
    this.pendingCursor = null;
    if (this.cursorThrottleRaf !== null) {
      if (typeof cancelAnimationFrame === 'function') {
        cancelAnimationFrame(this.cursorThrottleRaf);
      }
      this.cursorThrottleRaf = null;
    }

    const { wireSettings, assetRefs, assets } = prepareBrushSettingsForWire(brushSettings);
    for (let i = 0; i < assets.length; i++) {
      const asset = assets[i];
      if (!this.sentAssetHashes.has(asset.hash)) {
        this.sendBrushAssetData(asset.hash, asset.mime, asset.bytes);
        this.sentAssetHashes.add(asset.hash);
      }
    }

    const { hash: profileHash, canonicalProfile } = computeBrushProfileHash(
      wireSettings,
      assetRefs
    );
    this.registerBrushProfile(profileHash, canonicalProfile);
    this.recordPeerMeta(this.currentPeer.id, this.currentPeer.name, this.currentPeer.color);

    // On subsequent strokes with an already-announced brush profile, emit slim ~60-78B binary STROKE_START
    if (this.sentBrushProfileHashes.has(profileHash)) {
      const slimPacket = this.encodeSlimStrokeStartPacket(
        strokeId,
        String(this.currentPeer.id),
        layerId,
        profileHash,
        tool,
        startPoint,
        {
          color: wireSettings.color,
          size: wireSettings.size,
          opacity: wireSettings.opacity,
        }
      );
      if (slimPacket) {
        this.sendBinary(slimPacket);
        return;
      }
    }

    // First use of this brush profile in session: inline full settings + profileHash in STROKE_START
    // so peers, Rust server, and WebRTC Host Hub all populate their profile cache in 0 extra round-trips.
    this.sentBrushProfileHashes.add(profileHash);
    const payloadStr = JSON.stringify({
      strokeId,
      peerId: this.currentPeer.id,
      peerName: this.currentPeer.name,
      peerColor: this.currentPeer.color,
      layerId,
      brushSettings: wireSettings,
      brushAssetRefs: assetRefs,
      brushProfileHash: profileHash,
      tool,
      startPoint,
    });
    const payloadBytes = sharedTextEncoder.encode(payloadStr);

    const header = new Uint8Array(11 + payloadBytes.length);
    const view = new DataView(header.buffer);
    view.setUint8(0, BINARY_MAGIC_0);
    view.setUint8(1, BINARY_MAGIC_1);
    view.setUint8(2, CODE_STROKE_START);
    view.setUint32(3, this.getNextLamport(), true);
    view.setUint32(7, payloadBytes.length, true);
    header.set(payloadBytes, 11);

    this.sendBinary(header);
  }

  public sendStrokeChunk(strokeId: string, points: Point[]) {
    if (!this.isConnected() || !this.currentPeer || !this.canSendMutation() || points.length === 0) return;

    const MAX_POINTS_PER_PACKET = 4096;
    if (points.length > MAX_POINTS_PER_PACKET) {
      for (let start = 0; start < points.length; start += MAX_POINTS_PER_PACKET) {
        this.sendStrokeChunk(strokeId, points.slice(start, start + MAX_POINTS_PER_PACKET));
      }
      return;
    }

    const prevPoint = this.lastEmittedStrokePoints.get(strokeId) ?? null;
    const thinned = thinStrokeChunkPoints(points, prevPoint);
    if (thinned.length === 0) return;
    this.lastEmittedStrokePoints.set(strokeId, thinned[thinned.length - 1]);

    // Encode compact quantized/delta V2 payload inside CODE_STROKE_CHUNK (prefixed by 0x8002 marker)
    const v2Body = encodeStrokeChunkV2Payload(strokeId, String(this.currentPeer.id), thinned);
    if (v2Body) {
      const payloadSize = 2 + v2Body.byteLength;
      const packet = new Uint8Array(11 + payloadSize);
      const view = new DataView(packet.buffer);
      view.setUint8(0, BINARY_MAGIC_0);
      view.setUint8(1, BINARY_MAGIC_1);
      view.setUint8(2, CODE_STROKE_CHUNK);
      view.setUint32(3, this.getNextLamport(), true);
      view.setUint32(7, payloadSize, true);
      view.setUint16(11, STROKE_CHUNK_V2_MARKER, true);
      packet.set(v2Body, 13);
      this.sendBinary(packet);
      return;
    }

    // Legacy V1 fallback if IDs exceed 255 bytes
    const strokeIdBytes = sharedTextEncoder.encode(strokeId);
    const peerIdBytes = sharedTextEncoder.encode(String(this.currentPeer.id));

    const payloadSize =
      6 + strokeIdBytes.length + peerIdBytes.length + thinned.length * STROKE_CHUNK_POINT_STRIDE;
    const packet = new Uint8Array(11 + payloadSize);
    const view = new DataView(packet.buffer);

    view.setUint8(0, BINARY_MAGIC_0);
    view.setUint8(1, BINARY_MAGIC_1);
    view.setUint8(2, CODE_STROKE_CHUNK);
    view.setUint32(3, this.getNextLamport(), true);
    view.setUint32(7, payloadSize, true);

    let offset = 11;
    view.setUint16(offset, strokeIdBytes.length, true);
    offset += 2;
    packet.set(strokeIdBytes, offset);
    offset += strokeIdBytes.length;

    view.setUint16(offset, peerIdBytes.length, true);
    offset += 2;
    packet.set(peerIdBytes, offset);
    offset += peerIdBytes.length;

    view.setUint16(offset, thinned.length, true);
    offset += 2;

    for (let i = 0; i < thinned.length; i++) {
      const pt = thinned[i];
      view.setFloat32(offset, pt.x, true);
      view.setFloat32(offset + 4, pt.y, true);
      view.setFloat32(offset + 8, pt.pressure, true);
      view.setFloat32(offset + 12, pt.width, true);
      const tx = quantizeTilt(pt.tiltX);
      const ty = quantizeTilt(pt.tiltY);
      const tw = quantizeTwistByte(pt.twist);
      view.setInt8(offset + 16, tx);
      view.setInt8(offset + 17, ty);
      view.setUint8(offset + 18, tw);
      view.setUint8(offset + 19, pt.isCorner ? 1 : 0);
      offset += STROKE_CHUNK_POINT_STRIDE;
    }

    this.sendBinary(packet);
  }

  public sendStrokeFinish(
    strokeId: string,
    layerId: string,
    endPoint: Point,
    dirtyRect?: DirtyRect,
    vectorStroke?: VectorStroke,
    options?: { expectedTileCount?: number; commitSeq?: number }
  ) {
    if (!this.isConnected() || !this.currentPeer || !this.canSendMutation()) return;

    this.lastEmittedStrokePoints.delete(strokeId);
    const peerId = this.currentPeer.id;
    const finishedTool = this.activeStrokeTool;
    const epoch = this.connectionEpoch;
    if (this.activeStrokeId === strokeId || this.activeStrokeId !== null) {
      this.activeStrokeId = null;
    }

    const meta = this.strokeCommitMeta.get(strokeId);
    const expectedTileCount = vectorStroke
      ? undefined
      : options?.expectedTileCount !== undefined
        ? options.expectedTileCount
        : meta?.expectedTileCount;
    const commitSeq = options?.commitSeq;

    const mustDefer =
      !vectorStroke &&
      (meta !== undefined
        ? meta.pending || this.hasPendingOutgoingTilesForStroke(strokeId)
        : this.hasPendingOutgoingTilesForLayer(layerId));

    const emitNow = () => {
      if (this.connectionEpoch !== epoch || !this.isConnected() || !this.canSendMutation()) return;
      this.strokeCommitMeta.delete(strokeId);

      const payloadObj: Record<string, unknown> = {
        strokeId,
        peerId,
        layerId,
        endPoint,
        dirtyRect,
        vectorStroke,
      };
      if (expectedTileCount !== undefined) {
        payloadObj.expectedTileCount = expectedTileCount;
      }
      if (commitSeq !== undefined) {
        payloadObj.commitSeq = commitSeq;
      }

      const payloadBytes = sharedTextEncoder.encode(JSON.stringify(payloadObj));
      const header = new Uint8Array(11 + payloadBytes.length);
      const view = new DataView(header.buffer);
      view.setUint8(0, BINARY_MAGIC_0);
      view.setUint8(1, BINARY_MAGIC_1);
      view.setUint8(2, CODE_STROKE_FINISH);
      view.setUint32(3, this.getNextLamport(), true);
      view.setUint32(7, payloadBytes.length, true);
      header.set(payloadBytes, 11);

      this.sendBinary(header);

      // Emit final non-drawing cursor update at stroke end so remote peers settle cleanly
      if (
        endPoint &&
        Number.isFinite(endPoint.x) &&
        Number.isFinite(endPoint.y) &&
        this.activeStrokeId === null
      ) {
        this.sendCursor(endPoint.x, endPoint.y, false, finishedTool, true);
      }
    };

    if (mustDefer) {
      this.outgoingTileQueue.push({
        kind: 'barrier',
        strokeId,
        run: emitNow,
      });
      this.kickOutgoingTilePump();
      return;
    }

    emitNow();
  }

  private recordSentTileVersion(layerId: string, tile: WireTilePayload): void {
    const tileKey = `${layerId}:${tile.tileX}:${tile.tileY}`;
    if (tile.data === null) {
      this.sentTileVersions.delete(tileKey);
      this.knownRemoteBaseTiles.delete(tileKey);
    } else {
      if (tile.version > 0) {
        this.sentTileVersions.set(tileKey, tile.version);
      }
      this.knownRemoteBaseTiles.add(tileKey);
    }
  }

  private sendSerializedTilePacket(
    layerId: string,
    tile: WireTilePayload | null,
    tileBytes: Uint8Array,
    targetPeerId?: string | number,
    skipVersionRecord: boolean = false
  ): void {
    if (!this.isConnected() || !this.canSendMutation()) return;
    if (tile && targetPeerId === undefined && !skipVersionRecord) {
      this.recordSentTileVersion(layerId, tile);
    }

    const layerIdBytes = sharedTextEncoder.encode(layerId);
    const payloadSize = 2 + layerIdBytes.length + tileBytes.length;
    const packet = new Uint8Array(11 + payloadSize);
    const view = new DataView(packet.buffer);

    view.setUint8(0, BINARY_MAGIC_0);
    view.setUint8(1, BINARY_MAGIC_1);
    view.setUint8(2, CODE_TILE_DELTA);
    view.setUint32(3, this.getNextLamport(), true);
    view.setUint32(7, payloadSize, true);

    let offset = 11;
    view.setUint16(offset, layerIdBytes.length, true);
    offset += 2;
    packet.set(layerIdBytes, offset);
    offset += layerIdBytes.length;

    packet.set(tileBytes, offset);
    this.sendBinary(packet, targetPeerId);
  }

  /**
   * Stream a single LZ4-compressed binary tile (or 14-byte deletion tombstone when tile.data === null).
   * Preserves FIFO ordering behind any active async outgoing tile batch.
   */
  public sendTileDelta(layerId: string, tile: WireTilePayload, targetPeerId?: string | number) {
    if (!this.isConnected() || !this.canSendMutation()) return;

    if (this.outgoingTileFlushInFlight || this.outgoingTileQueue.length > 0) {
      if (targetPeerId === undefined) {
        this.recordSentTileVersion(layerId, tile);
      }
      this.outgoingTileQueue.push({
        kind: 'tiles',
        entries: [{ layerId, tile: cloneTileBufferForAsyncSend(tile) }],
        cursor: 0,
        targetPeerId,
      });
      this.kickOutgoingTilePump();
      return;
    }

    const tileBytes = serializeWireTilePacket(tile);
    this.sendSerializedTilePacket(layerId, tile, tileBytes, targetPeerId);
  }

  /**
   * Adaptive tile batch streaming pipeline with strict FIFO ordering and transport backpressure pacing.
   */
  public streamTileEntries(
    entries: OutgoingTileEntry[],
    targetPeerId?: string | number,
    options?: { strokeId?: string; onFlushed?: () => void }
  ): SendTileDeltasResult {
    if (!this.isConnected() || !this.canSendMutation() || entries.length === 0) {
      if (options?.strokeId) {
        this.markStrokeTileCommit(options.strokeId, 0);
      }
      options?.onFlushed?.();
      return { tileCount: 0, pending: false };
    }

    if (targetPeerId === undefined) {
      for (let i = 0; i < entries.length; i++) {
        this.recordSentTileVersion(entries[i].layerId, entries[i].tile);
      }
    }

    const canFlushSync =
      !this.outgoingTileFlushInFlight &&
      this.outgoingTileQueue.length === 0 &&
      entries.length <= SYNC_TILE_CODEC_THRESHOLD &&
      this.getBufferedAmount() <= MAX_OUTGOING_BUFFERED_BYTES;

    if (canFlushSync) {
      for (let i = 0; i < entries.length; i++) {
        const entry = entries[i];
        const tileBytes = entry.encodedPacket ?? serializeWireTilePacket(entry.tile);
        this.sendSerializedTilePacket(entry.layerId, entry.tile, tileBytes, targetPeerId, true);
      }
      if (options?.strokeId) {
        this.strokeCommitMeta.set(options.strokeId, {
          expectedTileCount: entries.length,
          pending: false,
          layerId: entries[0]?.layerId,
        });
      }
      options?.onFlushed?.();
      return { tileCount: entries.length, pending: false };
    }

    const clonedEntries: OutgoingTileEntry[] = new Array(entries.length);
    for (let i = 0; i < entries.length; i++) {
      clonedEntries[i] = {
        layerId: entries[i].layerId,
        tile: cloneTileBufferForAsyncSend(entries[i].tile),
        ...(entries[i].encodedPacket ? { encodedPacket: entries[i].encodedPacket } : {}),
      };
    }

    if (options?.strokeId) {
      this.strokeCommitMeta.set(options.strokeId, {
        expectedTileCount: clonedEntries.length,
        pending: true,
        layerId: clonedEntries[0]?.layerId,
      });
    }

    this.outgoingTileQueue.push({
      kind: 'tiles',
      entries: clonedEntries,
      cursor: 0,
      targetPeerId,
      strokeId: options?.strokeId,
      onFlushed: options?.onFlushed,
    });
    this.kickOutgoingTilePump();
    return { tileCount: clonedEntries.length, pending: true };
  }

  private kickOutgoingTilePump(): void {
    if (this.outgoingTileFlushInFlight || this.outgoingTileTimer !== null) return;
    if (this.outgoingTileQueue.length === 0 || !this.isConnected()) return;
    const epoch = this.connectionEpoch;
    void this.pumpOutgoingTileQueue(epoch);
  }

  private async pumpOutgoingTileQueue(epoch: number): Promise<void> {
    if (this.outgoingTileFlushInFlight) return;
    this.outgoingTileFlushInFlight = true;
    try {
      while (
        this.outgoingTileQueue.length > 0 &&
        this.connectionEpoch === epoch &&
        this.isConnected()
      ) {
        const head = this.outgoingTileQueue[0];
        if (head.kind === 'barrier') {
          this.outgoingTileQueue.shift();
          try {
            head.run();
          } catch (err) {
            console.error('[Multiplayer] Outgoing tile barrier error:', err);
          }
          continue;
        }

        if (this.getBufferedAmount() > MAX_OUTGOING_BUFFERED_BYTES) {
          this.outgoingTileTimer = setTimeout(() => {
            this.outgoingTileTimer = null;
            if (this.connectionEpoch === epoch) {
              this.kickOutgoingTilePump();
            }
          }, 20);
          return;
        }

        const end = Math.min(head.cursor + OUTGOING_TILE_BATCH_SIZE, head.entries.length);
        const slice = head.entries.slice(head.cursor, end);
        head.cursor = end;

        for (let i = 0; i < slice.length; i++) {
          const entry = slice[i];
          const pkt = entry.encodedPacket ?? serializeWireTilePacket(entry.tile);
          this.sendSerializedTilePacket(
            entry.layerId,
            entry.tile,
            pkt,
            head.targetPeerId,
            true
          );
        }

        if (head.cursor >= head.entries.length) {
          this.outgoingTileQueue.shift();
          if (head.strokeId) {
            const meta = this.strokeCommitMeta.get(head.strokeId);
            if (meta) {
              meta.pending = false;
            }
          }
          if (head.onFlushed) {
            try {
              head.onFlushed();
            } catch (err) {
              console.error('[Multiplayer] Outgoing tile onFlushed error:', err);
            }
          }
          continue;
        }

        // Pace multi-chunk tile bursts gently so WS/server buffers and UI input stay responsive
        this.outgoingTileTimer = setTimeout(() => {
          this.outgoingTileTimer = null;
          if (this.connectionEpoch === epoch) {
            this.kickOutgoingTilePump();
          }
        }, 4);
        return;
      }
    } catch (err) {
      console.error('[Multiplayer] Outgoing tile pump failed:', err);
    } finally {
      if (this.connectionEpoch === epoch) {
        this.outgoingTileFlushInFlight = false;
        if (
          this.outgoingTileQueue.length > 0 &&
          this.outgoingTileTimer === null &&
          this.isConnected()
        ) {
          this.kickOutgoingTilePump();
        }
      }
    }
  }

  /**
   * Direct Rust-to-wire tile streaming: asks `ink-engine` (`native_collab_encode_tiles`)
   * to LZ4-encode the requested tiles (or all populated tiles of `layerId`) and transmits
   * the resulting binary packets straight over WS/WebRTC with zero JS pixel decoding!
   */
  public streamNativeLayerTiles(
    layerId: string,
    options?: {
      coords?: { tx: number; ty: number }[];
      targetPeerId?: string | number;
      strokeId?: string;
      docId?: string | null;
      onFlushed?: () => void;
    }
  ): void {
    if (!this.isConnected() || !this.canSendMutation() || !layerId) {
      if (options?.strokeId) {
        this.markStrokeTileCommit(options.strokeId, 0);
      }
      options?.onFlushed?.();
      return;
    }

    const epoch = this.connectionEpoch;
    void nativeCollabEncodeTiles(layerId, options?.coords ?? null, options?.docId ?? null)
      .then((packets) => {
        if (this.connectionEpoch !== epoch || !this.isConnected()) {
          options?.onFlushed?.();
          return;
        }
        if (packets.length === 0) {
          if (options?.strokeId) {
            this.markStrokeTileCommit(options.strokeId, 0);
          }
          options?.onFlushed?.();
          return;
        }
        const entries: OutgoingTileEntry[] = [];
        for (let i = 0; i < packets.length; i++) {
          const pkt = packets[i];
          if (pkt.byteLength < TILE_PACKET_HEADER_BYTES) continue;
          const v = new DataView(pkt.buffer, pkt.byteOffset, pkt.byteLength);
          const tileX = v.getInt32(0, true);
          const tileY = v.getInt32(4, true);
          const format = wireCodeToFormat(v.getUint8(8)) ?? 'color-32bit';
          const version = v.getUint32(9, true);
          const codec = v.getUint8(13);
          entries.push({
            layerId,
            tile: {
              layerId,
              tileX,
              tileY,
              format,
              version,
              data: codec === TILE_CODEC_EMPTY ? null : new Uint8Array(0),
            },
            encodedPacket: pkt,
          });
        }
        this.streamTileEntries(entries, options?.targetPeerId, {
          strokeId: options?.strokeId,
          onFlushed: options?.onFlushed,
        });
      })
      .catch(() => {
        options?.onFlushed?.();
      });
  }

  /**
   * Streams all tiles touching a canvas dirty rectangle straight from Rust `ink-engine`.
   */
  public streamNativeDirtyRectTiles(
    layerId: string,
    rect: DirtyRect | null | undefined,
    options?: {
      targetPeerId?: string | number;
      strokeId?: string;
      docId?: string | null;
      onFlushed?: () => void;
    }
  ): void {
    if (!rect || rect.width <= 0 || rect.height <= 0) {
      this.streamNativeLayerTiles(layerId, options);
      return;
    }
    const minTx = Math.max(0, Math.floor(rect.x / 256));
    const minTy = Math.max(0, Math.floor(rect.y / 256));
    const maxTx = Math.max(minTx, Math.floor((rect.x + rect.width - 1) / 256));
    const maxTy = Math.max(minTy, Math.floor((rect.y + rect.height - 1) / 256));
    const coords: { tx: number; ty: number }[] = [];
    for (let ty = minTy; ty <= maxTy; ty++) {
      for (let tx = minTx; tx <= maxTx; tx++) {
        coords.push({ tx, ty });
      }
    }
    this.streamNativeLayerTiles(layerId, { ...options, coords });
  }

  /**
   * Broadcast a selective collaborative undo command (undoing a stroke without reverting peer strokes).
   */
  public sendSelectiveUndo(strokeId: string) {
    if (!this.isConnected() || !this.currentPeer || !this.canSendMutation()) return;

    const payloadStr = JSON.stringify({
      strokeId,
      peerId: this.currentPeer.id,
      lamport: this.getNextLamport(),
    });
    const payloadBytes = sharedTextEncoder.encode(payloadStr);

    const packet = new Uint8Array(11 + payloadBytes.length);
    const view = new DataView(packet.buffer);
    view.setUint8(0, BINARY_MAGIC_0);
    view.setUint8(1, BINARY_MAGIC_1);
    view.setUint8(2, CODE_SELECTIVE_UNDO);
    view.setUint32(3, this.lamportClock, true);
    view.setUint32(7, payloadBytes.length, true);
    packet.set(payloadBytes, 11);

    this.sendBinary(packet);
  }

  // --- Real-time Cursor Throttling (30-60 Hz) ---

  public sendCursor(
    x: number,
    y: number,
    isDrawing: boolean,
    tool: ToolType,
    immediate: boolean = false
  ) {
    if (!this.isConnected() || !this.currentPeer) return;

    // Suppress redundant outgoing CURSOR_MOVE packets while actively drawing a stroke:
    // remote peers derive live cursor coordinates directly from STROKE_START / STROKE_CHUNK.
    if (isDrawing && this.activeStrokeId !== null) {
      return;
    }
    if (!isDrawing && this.activeStrokeId !== null) {
      this.activeStrokeId = null;
    }

    this.pendingCursor = { x, y, isDrawing, tool };
    const now =
      typeof performance !== 'undefined' && typeof performance.now === 'function'
        ? performance.now()
        : Date.now();

    if (immediate || now - this.lastCursorSendTime >= 24) {
      if (this.cursorThrottleRaf !== null) {
        if (typeof cancelAnimationFrame === 'function') {
          cancelAnimationFrame(this.cursorThrottleRaf);
        }
        this.cursorThrottleRaf = null;
      }
      this.flushCursor();
    } else if (this.cursorThrottleRaf === null) {
      if (typeof requestAnimationFrame === 'function') {
        this.cursorThrottleRaf = requestAnimationFrame(() => {
          this.cursorThrottleRaf = null;
          this.flushCursor();
        });
      } else {
        this.flushCursor();
      }
    }
  }

  private flushCursor() {
    if (!this.pendingCursor || !this.currentPeer || !this.isConnected()) return;

    this.lastCursorSendTime =
      typeof performance !== 'undefined' && typeof performance.now === 'function'
        ? performance.now()
        : Date.now();
    const peerIdBytes = sharedTextEncoder.encode(String(this.currentPeer.id));

    const payloadSize = 2 + peerIdBytes.length + 10;
    const packet = new Uint8Array(11 + payloadSize);
    const view = new DataView(packet.buffer);

    view.setUint8(0, BINARY_MAGIC_0);
    view.setUint8(1, BINARY_MAGIC_1);
    view.setUint8(2, CODE_CURSOR_MOVE);
    view.setUint32(3, this.getNextLamport(), true);
    view.setUint32(7, payloadSize, true);

    let offset = 11;
    view.setUint16(offset, peerIdBytes.length, true);
    offset += 2;
    packet.set(peerIdBytes, offset);
    offset += peerIdBytes.length;

    const toolIdx = Math.max(0, TOOL_TYPES_LIST.indexOf(this.pendingCursor.tool));
    view.setFloat32(offset, this.pendingCursor.x, true);
    view.setFloat32(offset + 4, this.pendingCursor.y, true);
    view.setUint8(offset + 8, this.pendingCursor.isDrawing ? 1 : 0);
    view.setUint8(offset + 9, toolIdx);

    this.sendBinary(packet, undefined, { ephemeral: true });
    this.pendingCursor = null;
  }

  // --- Layer & Document State Synchronization ---

  public sendLayerAdd(layerItem: LayerItem | WireLayerItem, insertIndex?: number) {
    if (!this.isConnected() || !this.canSendMutation()) return;
    const wireLayer = serializeLayerForWire(layerItem as LayerItem);
    const msg: LayerActionMessage = {
      type: 'LAYER_ADD',
      layerId: wireLayer.id,
      layerItem: wireLayer,
      ...(insertIndex !== undefined ? { insertIndex } : {}),
    };
    this.sendMessage(msg);
  }

  public sendLayerDelete(layerId: string) {
    if (!this.isConnected() || !this.canSendMutation()) return;
    this.clearLayerPropThrottlesForLayer(layerId);
    this.pruneKnownBaseTilesForLayer(layerId);
    const msg: LayerActionMessage = {
      type: 'LAYER_DELETE',
      layerId,
    };
    this.sendMessage(msg);
  }

  public sendLayerClear(layerId: string) {
    if (!this.isConnected() || !this.canSendMutation()) return;
    this.pruneKnownBaseTilesForLayer(layerId);
    const msg: LayerActionMessage = {
      type: 'LAYER_CLEAR',
      layerId,
    };
    this.sendMessage(msg);
  }

  public sendLayerRename(layerId: string, newName: string) {
    if (!this.isConnected() || !this.canSendMutation()) return;
    const msg: LayerActionMessage = {
      type: 'LAYER_RENAME',
      layerId,
      newName,
    };
    this.sendMessage(msg);
  }

  public sendLayerVisibility(layerId: string, visible: boolean) {
    if (!this.isConnected() || !this.canSendMutation()) return;
    const msg: LayerActionMessage = {
      type: 'LAYER_VISIBILITY',
      layerId,
      visible,
    };
    this.sendMessage(msg);
  }

  public sendLayerOpacity(layerId: string, opacity: number, immediate = false) {
    if (!this.isConnected() || !this.canSendMutation() || !layerId) return;
    const clamped = Number.isFinite(opacity) ? Math.max(0, Math.min(1, opacity)) : 1;
    this.pendingLayerOpacities.set(layerId, clamped);

    const flush = () => {
      this.layerOpacityThrottleTimers.delete(layerId);
      if (!this.isConnected() || !this.canSendMutation()) {
        this.pendingLayerOpacities.delete(layerId);
        return;
      }
      const value = this.pendingLayerOpacities.get(layerId);
      if (value === undefined) return;
      this.pendingLayerOpacities.delete(layerId);
      const msg: LayerActionMessage = {
        type: 'LAYER_OPACITY',
        layerId,
        opacity: value,
      };
      this.sendMessage(msg);
    };

    if (immediate) {
      const existingTimer = this.layerOpacityThrottleTimers.get(layerId);
      if (existingTimer !== undefined) {
        clearTimeout(existingTimer);
        this.layerOpacityThrottleTimers.delete(layerId);
      }
      flush();
    } else if (!this.layerOpacityThrottleTimers.has(layerId)) {
      this.layerOpacityThrottleTimers.set(layerId, setTimeout(flush, LAYER_PROP_THROTTLE_MS));
    }
  }

  public sendLayerUpdate(
    layerId: string,
    patch: Partial<WireLayerItem>,
    clearedFields?: LayerClearableField[],
    options?: { immediate?: boolean; throttle?: boolean }
  ) {
    if (!this.isConnected() || !this.canSendMutation() || !layerId) return;
    const safePatch = sanitizeWireLayerPatch(patch);
    const safeCleared =
      clearedFields && clearedFields.length > 0 ? sanitizeClearedFields(clearedFields) : [];
    const patchKeys = Object.keys(safePatch);
    if (patchKeys.length === 0 && safeCleared.length === 0) return;

    // If patch explicitly carries opacity, supersede any queued standalone LAYER_OPACITY for this layer
    if (safePatch.opacity !== undefined) {
      const opTimer = this.layerOpacityThrottleTimers.get(layerId);
      if (opTimer !== undefined) {
        clearTimeout(opTimer);
        this.layerOpacityThrottleTimers.delete(layerId);
      }
      this.pendingLayerOpacities.delete(layerId);
    }

    const isContinuousOnly =
      safeCleared.length === 0 &&
      patchKeys.length > 0 &&
      patchKeys.every((k) => CONTINUOUS_LAYER_UPDATE_KEYS.has(k));
    const shouldThrottle =
      !options?.immediate && (options?.throttle === true || isContinuousOnly);

    if (shouldThrottle) {
      const existingPending = this.pendingLayerUpdates.get(layerId);
      this.pendingLayerUpdates.set(
        layerId,
        existingPending ? { ...existingPending, ...safePatch } : { ...safePatch }
      );
      if (!this.layerUpdateThrottleTimers.has(layerId)) {
        const timer = setTimeout(() => {
          this.layerUpdateThrottleTimers.delete(layerId);
          if (!this.isConnected() || !this.canSendMutation()) {
            this.pendingLayerUpdates.delete(layerId);
            return;
          }
          const mergedPatch = this.pendingLayerUpdates.get(layerId);
          if (!mergedPatch) return;
          this.pendingLayerUpdates.delete(layerId);
          const msg: LayerUpdateMessage = {
            type: 'LAYER_UPDATE',
            layerId,
            patch: mergedPatch,
            lamport: this.getNextLamport(),
          };
          this.sendMessage(msg);
        }, LAYER_PROP_THROTTLE_MS);
        this.layerUpdateThrottleTimers.set(layerId, timer);
      }
      return;
    }

    // Immediate/discrete update: fold any pending throttled continuous patch underneath so ordering never regresses
    let finalPatch = safePatch;
    const pendingTimer = this.layerUpdateThrottleTimers.get(layerId);
    if (pendingTimer !== undefined) {
      clearTimeout(pendingTimer);
      this.layerUpdateThrottleTimers.delete(layerId);
    }
    const pendingPatch = this.pendingLayerUpdates.get(layerId);
    if (pendingPatch) {
      this.pendingLayerUpdates.delete(layerId);
      finalPatch = { ...pendingPatch, ...safePatch };
      for (let i = 0; i < safeCleared.length; i++) {
        delete (finalPatch as Record<string, unknown>)[safeCleared[i]];
      }
    }

    const msg: LayerUpdateMessage = {
      type: 'LAYER_UPDATE',
      layerId,
      patch: finalPatch,
      ...(safeCleared.length > 0 ? { clearedFields: safeCleared } : {}),
      lamport: this.getNextLamport(),
    };
    this.sendMessage(msg);
  }

  public sendLayerTreeSync(
    layers: Array<LayerItem | WireLayerItem>,
    options?: { dirtyTileLayerIds?: string[]; removedLayerIds?: string[] }
  ) {
    if (!this.isConnected() || !this.canSendMutation() || layers.length === 0) return;
    // Full tree sync carries authoritative latest properties for every layer; drop older queued slider timers
    this.clearAllLayerPropThrottles();
    const wireLayers = layers.map((l) => serializeLayerForWire(l as LayerItem));
    const msg: LayerTreeSyncMessage = {
      type: 'LAYER_TREE_SYNC',
      layers: wireLayers,
      lamport: this.getNextLamport(),
      ...(options?.dirtyTileLayerIds && options.dirtyTileLayerIds.length > 0
        ? { dirtyTileLayerIds: options.dirtyTileLayerIds }
        : {}),
      ...(options?.removedLayerIds && options.removedLayerIds.length > 0
        ? { removedLayerIds: options.removedLayerIds }
        : {}),
    };
    this.sendMessage(msg);
  }

  // --- Binary Layer Mask Synchronization (LZ4 / 1-byte solid fill, auto-chunked <= 1024x1024) ---

  private sendMaskPacket(
    layerId: string,
    x: number,
    y: number,
    width: number,
    height: number,
    isFullReplace: boolean,
    solidValue: number | null,
    pixels: Uint8Array | null,
    targetPeerId?: string | number
  ) {
    if (!this.isConnected() || !this.canSendMutation() || !layerId || width <= 0 || height <= 0) return;

    const layerIdBytes = sharedTextEncoder.encode(layerId);
    if (layerIdBytes.length === 0 || layerIdBytes.length > 256) return;

    let flags = isFullReplace ? MASK_FLAG_FULL_REPLACE : 0;
    let body: Uint8Array;

    if (solidValue !== null) {
      flags |= MASK_FLAG_SOLID_FILL;
      body = new Uint8Array([Math.max(0, Math.min(255, Math.round(solidValue)))]);
    } else if (pixels) {
      const compressed = lz4CompressBlock(pixels);
      if (compressed.byteLength < pixels.byteLength) {
        flags |= MASK_FLAG_LZ4;
        body = compressed;
      } else {
        body = pixels;
      }
    } else {
      return;
    }

    const payloadSize = 2 + layerIdBytes.length + 1 + 16 + body.byteLength;
    const packet = new Uint8Array(11 + payloadSize);
    const view = new DataView(packet.buffer);

    view.setUint8(0, BINARY_MAGIC_0);
    view.setUint8(1, BINARY_MAGIC_1);
    view.setUint8(2, CODE_LAYER_MASK_DATA);
    view.setUint32(3, this.getNextLamport(), true);
    view.setUint32(7, payloadSize, true);

    let offset = 11;
    view.setUint16(offset, layerIdBytes.length, true);
    offset += 2;
    packet.set(layerIdBytes, offset);
    offset += layerIdBytes.length;

    packet[offset++] = flags;
    view.setUint32(offset, x, true);
    view.setUint32(offset + 4, y, true);
    view.setUint32(offset + 8, width, true);
    view.setUint32(offset + 12, height, true);
    offset += 16;

    packet.set(body, offset);
    this.sendBinary(packet, targetPeerId);
  }

  public sendLayerMaskSolid(
    layerId: string,
    width: number,
    height: number,
    value: number = 255,
    isFullReplace: boolean = true,
    targetPeerId?: string | number
  ) {
    if (!this.isConnected() || width <= 0 || height <= 0) return;
    this.sendMaskPacket(layerId, 0, 0, width, height, isFullReplace, value, null, targetPeerId);
  }

  /**
   * Streams a layer's non-destructive 8-bit mask directly from Rust `ink-engine`
   * (`native_collab_encode_mask`) over `CODE_LAYER_MASK_DATA` without any `<canvas>`.
   */
  public sendNativeLayerMask(
    layerId: string,
    targetPeerId?: string | number,
    onFlushed?: () => void,
    docId?: string | null
  ): void {
    if (!this.isConnected() || !this.canSendMutation() || !layerId) {
      onFlushed?.();
      return;
    }
    const epoch = this.connectionEpoch;
    void nativeCollabEncodeMask(layerId, docId ?? null)
      .then((packet) => {
        if (this.connectionEpoch !== epoch || !this.isConnected() || !packet || packet.byteLength < 10) {
          onFlushed?.();
          return;
        }
        const pView = new DataView(packet.buffer, packet.byteOffset, packet.byteLength);
        const width = pView.getUint32(1, true);
        const height = pView.getUint32(5, true);
        const lz4Body = packet.subarray(10);
        if (width <= 0 || height <= 0) {
          onFlushed?.();
          return;
        }

        const layerIdBytes = sharedTextEncoder.encode(layerId);
        if (layerIdBytes.length === 0 || layerIdBytes.length > 256) {
          onFlushed?.();
          return;
        }
        const flags = MASK_FLAG_FULL_REPLACE | MASK_FLAG_LZ4;
        const payloadSize = 2 + layerIdBytes.length + 1 + 16 + lz4Body.byteLength;
        const frame = new Uint8Array(11 + payloadSize);
        const view = new DataView(frame.buffer);
        view.setUint8(0, BINARY_MAGIC_0);
        view.setUint8(1, BINARY_MAGIC_1);
        view.setUint8(2, CODE_LAYER_MASK_DATA);
        view.setUint32(3, this.getNextLamport(), true);
        view.setUint32(7, payloadSize, true);
        let offset = 11;
        view.setUint16(offset, layerIdBytes.length, true);
        offset += 2;
        frame.set(layerIdBytes, offset);
        offset += layerIdBytes.length;
        frame[offset++] = flags;
        view.setUint32(offset, 0, true);
        view.setUint32(offset + 4, 0, true);
        view.setUint32(offset + 8, width, true);
        view.setUint32(offset + 12, height, true);
        offset += 16;
        frame.set(lz4Body, offset);
        this.sendBinary(frame, targetPeerId);
        onFlushed?.();
      })
      .catch(() => {
        onFlushed?.();
      });
  }

  // --- Perspective Ruler, Straight Ruler, Animation & Canvas Resize Sync ---

  public sendPerspectiveRulerSync(perspectiveRuler: PerspectiveRuler | null, immediate = false) {
    if (!this.isConnected() || !this.canSendMutation()) return;
    this.pendingPerspectiveRuler = perspectiveRuler;
    const flush = () => {
      this.perspectiveThrottleTimer = null;
      if (!this.isConnected() || !this.canSendMutation() || this.pendingPerspectiveRuler === undefined) return;
      const value = this.pendingPerspectiveRuler;
      this.pendingPerspectiveRuler = undefined;
      const msg: PerspectiveRulerSyncMessage = {
        type: 'PERSPECTIVE_RULER_SYNC',
        perspectiveRuler: value,
        lamport: this.getNextLamport(),
      };
      this.sendMessage(msg);
    };
    if (immediate) {
      if (this.perspectiveThrottleTimer) clearTimeout(this.perspectiveThrottleTimer);
      flush();
    } else if (!this.perspectiveThrottleTimer) {
      this.perspectiveThrottleTimer = setTimeout(flush, STATE_SYNC_THROTTLE_MS);
    }
  }

  public sendStraightRulerSync(straightRuler: StraightRuler | null, immediate = false) {
    if (!this.isConnected() || !this.canSendMutation()) return;
    this.pendingStraightRuler = straightRuler;
    const flush = () => {
      this.straightThrottleTimer = null;
      if (!this.isConnected() || !this.canSendMutation() || this.pendingStraightRuler === undefined) return;
      const value = this.pendingStraightRuler;
      this.pendingStraightRuler = undefined;
      const msg: StraightRulerSyncMessage = {
        type: 'STRAIGHT_RULER_SYNC',
        straightRuler: value,
        lamport: this.getNextLamport(),
      };
      this.sendMessage(msg);
    };
    if (immediate) {
      if (this.straightThrottleTimer) clearTimeout(this.straightThrottleTimer);
      flush();
    } else if (!this.straightThrottleTimer) {
      this.straightThrottleTimer = setTimeout(flush, STATE_SYNC_THROTTLE_MS);
    }
  }

  public sendAnimationSync(animationTimeline: AnimationTimeline | null, immediate = false) {
    if (!this.isConnected() || !this.canSendMutation()) return;
    const wireTimeline: AnimationTimeline | null = animationTimeline
      ? { ...animationTimeline, isPlaying: false }
      : null;
    this.pendingAnimationTimeline = wireTimeline;
    const flush = () => {
      this.animationThrottleTimer = null;
      if (!this.isConnected() || !this.canSendMutation() || this.pendingAnimationTimeline === undefined) return;
      const value = this.pendingAnimationTimeline;
      this.pendingAnimationTimeline = undefined;
      const msg: AnimationSyncMessage = {
        type: 'ANIMATION_SYNC',
        animationTimeline: value,
        lamport: this.getNextLamport(),
      };
      this.sendMessage(msg);
    };
    if (immediate) {
      if (this.animationThrottleTimer) clearTimeout(this.animationThrottleTimer);
      flush();
    } else if (!this.animationThrottleTimer) {
      this.animationThrottleTimer = setTimeout(flush, STATE_SYNC_THROTTLE_MS);
    }
  }

  public sendCanvasResize(dimensions: CanvasDimensions, options: ResizeCanvasOptions) {
    if (!this.isConnected() || !this.canSendMutation()) return;
    this.knownRemoteBaseTiles.clear();
    const msg: CanvasResizeMessage = {
      type: 'CANVAS_RESIZE',
      dimensions,
      options,
      lamport: this.getNextLamport(),
    };
    this.sendMessage(msg);
  }

  // --- Periodic State Integrity Checksum Audit & Targeted Tile Self-Healing ---

  public sendStateChecksumAudit(
    auditSeq: number,
    docHash: number,
    layers: LayerChecksumEntry[],
    targetPeerId?: string | number
  ): void {
    if (!this.isConnected() || !this.currentPeer || this.localRole !== 'host') return;
    const msg: StateChecksumAuditMessage = {
      type: 'STATE_CHECKSUM_AUDIT',
      auditSeq,
      docHash: docHash >>> 0,
      layers,
      ...(targetPeerId !== undefined ? { targetPeerId } : {}),
    };
    this.sendMessage(msg);
  }

  public sendTileResyncRequest(params: {
    tileKeys?: string[];
    layerIds?: string[];
    targetPeerId?: string | number;
  }): void {
    if (!this.isConnected() || !this.currentPeer) return;
    const tileKeys = params.tileKeys?.slice(0, 256);
    const layerIds = params.layerIds?.slice(0, 32);
    if ((!tileKeys || tileKeys.length === 0) && (!layerIds || layerIds.length === 0)) return;
    const msg: TileResyncRequestMessage = {
      type: 'TILE_RESYNC_REQUEST',
      ...(params.targetPeerId !== undefined ? { targetPeerId: params.targetPeerId } : {}),
      ...(tileKeys && tileKeys.length > 0 ? { tileKeys } : {}),
      ...(layerIds && layerIds.length > 0 ? { layerIds } : {}),
    };
    this.sendMessage(msg);
  }

  // --- Room Roles & Moderation (Host-authoritative) ---

  public sendPeerRoleUpdate(targetPeerId: string | number, role: CollabRole) {
    if (!this.isConnected() || this.localRole !== 'host') return;
    const msg: PeerRoleUpdateMessage = {
      type: 'PEER_ROLE_UPDATE',
      targetPeerId,
      role,
    };
    this.sendMessage(msg);
  }

  public sendPeerKick(targetPeerId: string | number, reason?: string) {
    if (!this.isConnected() || this.localRole !== 'host') return;
    const msg: PeerKickMessage = {
      type: 'PEER_KICK',
      targetPeerId,
      ...(reason ? { reason } : {}),
    };
    this.sendMessage(msg);
  }

  public sendPeerBan(targetPeerId: string | number, reason?: string) {
    if (!this.isConnected() || this.localRole !== 'host') return;
    const msg: PeerBanMessage = {
      type: 'PEER_BAN',
      targetPeerId,
      ...(reason ? { reason } : {}),
    };
    this.sendMessage(msg);
  }

  public sendPeerUnban(targetPeerId: string | number) {
    if (!this.isConnected() || this.localRole !== 'host') return;
    const msg: PeerUnbanMessage = {
      type: 'PEER_UNBAN',
      targetPeerId,
    };
    this.sendMessage(msg);
  }

  public sendAccessDenied(
    code: AccessDeniedCode,
    reason: string,
    targetPeerId?: string | number
  ) {
    if (!this.isConnected()) return;
    const msg: AccessDeniedMessage = {
      type: 'ACCESS_DENIED',
      code,
      reason,
      ...(targetPeerId !== undefined ? { targetPeerId } : {}),
    };
    this.sendMessage(msg);
  }

  // --- Radar Ping ---

  public sendPing(x: number, y: number) {
    if (!this.isConnected() || !this.currentPeer) return;

    const msg: CanvasPingMessage = {
      type: 'CANVAS_PING',
      sender: this.currentPeer,
      x,
      y,
      timestamp: Date.now(),
    };
    this.sendMessage(msg);
    this.notifyHandlers(msg);
  }

  // --- Built-in Room Text Chat ---

  public sendChatMessage(rawText: string): ChatMessage | null {
    if (!this.isConnected() || !this.currentPeer) return null;
    const text = rawText.replace(/\r\n/g, '\n').trim().slice(0, MAX_CHAT_TEXT_LEN);
    if (!text) return null;

    const msg: ChatMessage = {
      type: 'CHAT_MESSAGE',
      senderId: this.currentPeer.id,
      id: `chat-${Date.now()}-${Math.random().toString(36).slice(2, 7)}`,
      senderName: this.currentPeer.name,
      senderColor: this.currentPeer.color,
      text,
      timestamp: Date.now(),
    };
    this.sendMessage(msg);
    return msg;
  }

  // --- Follow Camera Real-Time Viewport Sync (Compact Binary, ~20Hz) ---

  public sendCameraSync(camera: Omit<CollabPeerCamera, 'updatedAt'>, immediate = false): void {
    if (!this.isConnected() || !this.currentPeer) return;
    this.pendingCamera = camera;

    const flush = () => {
      if (this.cameraThrottleTimer !== null) {
        clearTimeout(this.cameraThrottleTimer);
        this.cameraThrottleTimer = null;
      }
      if (!this.pendingCamera || !this.currentPeer || !this.isConnected()) return;
      const cam = this.pendingCamera;
      this.pendingCamera = null;
      this.lastCameraSendTime =
        typeof performance !== 'undefined' ? performance.now() : Date.now();

      const peerIdBytes = sharedTextEncoder.encode(String(this.currentPeer.id));
      const payloadSize = 2 + peerIdBytes.length + 21;
      const packet = new Uint8Array(11 + payloadSize);
      const view = new DataView(packet.buffer);

      view.setUint8(0, BINARY_MAGIC_0);
      view.setUint8(1, BINARY_MAGIC_1);
      view.setUint8(2, CODE_CAMERA_SYNC);
      view.setUint32(3, this.getNextLamport(), true);
      view.setUint32(7, payloadSize, true);

      let offset = 11;
      view.setUint16(offset, peerIdBytes.length, true);
      offset += 2;
      packet.set(peerIdBytes, offset);
      offset += peerIdBytes.length;

      view.setFloat32(offset, cam.centerX, true);
      view.setFloat32(offset + 4, cam.centerY, true);
      view.setFloat32(offset + 8, Math.max(0.01, Math.min(32, cam.zoom)), true);
      view.setFloat32(offset + 12, cam.rotation, true);
      view.setUint16(offset + 16, Math.max(0, Math.min(65535, Math.round(cam.viewportWidth))), true);
      view.setUint16(offset + 18, Math.max(0, Math.min(65535, Math.round(cam.viewportHeight))), true);
      const flags =
        (cam.flipX ? CAMERA_FLAG_FLIP_X : 0) | (cam.flipY ? CAMERA_FLAG_FLIP_Y : 0);
      packet[offset + 20] = flags;

      this.sendBinary(packet, undefined, { ephemeral: true });
    };

    const now = typeof performance !== 'undefined' ? performance.now() : Date.now();
    if (immediate || now - this.lastCameraSendTime >= CAMERA_SYNC_THROTTLE_MS) {
      flush();
    } else if (this.cameraThrottleTimer === null) {
      const remaining = Math.max(8, CAMERA_SYNC_THROTTLE_MS - (now - this.lastCameraSendTime));
      this.cameraThrottleTimer = setTimeout(flush, remaining);
    }
  }

  public sendCameraSyncRequest(targetPeerId: string | number): void {
    if (!this.isConnected() || !this.currentPeer) return;
    const msg: CameraSyncRequestMessage = {
      type: 'CAMERA_SYNC_REQUEST',
      targetPeerId,
    };
    this.sendMessage(msg);
  }

  // --- "Grab an Artist's Brush" (Share / Request Brush in 1 Click via BRUSH_ASSET_DATA) ---

  public sendBrushRequest(targetPeerId: string | number): void {
    if (!this.isConnected() || !this.currentPeer) return;
    const msg: BrushRequestMessage = {
      type: 'BRUSH_REQUEST',
      targetPeerId,
    };
    this.sendMessage(msg);
  }

  public sendBrushShare(
    brushSettings: BrushSettings,
    tool: 'brush' | 'decoration',
    brushName: string,
    options?: { targetPeerId?: string | number; explicit?: boolean; forceAssets?: boolean }
  ): BrushShareMessage | null {
    if (!this.isConnected() || !this.currentPeer) return null;

    const { wireSettings, assetRefs, assets } = prepareBrushSettingsForWire(brushSettings);
    const forceAssets = options?.forceAssets ?? true;
    const targetPeerId = options?.targetPeerId;
    for (let i = 0; i < assets.length; i++) {
      const asset = assets[i];
      const alreadySent =
        targetPeerId !== undefined
          ? this.hasSentAssetToPeer(targetPeerId, asset.hash)
          : this.sentAssetHashes.has(asset.hash);
      if (forceAssets || !alreadySent) {
        this.sendBrushAssetData(asset.hash, asset.mime, asset.bytes, targetPeerId);
      }
    }

    const cleanName = (brushName || wireSettings.brushName || 'Brush').trim().slice(0, 80) || 'Brush';
    const msg: BrushShareMessage = {
      type: 'BRUSH_SHARE',
      senderId: this.currentPeer.id,
      peerId: this.currentPeer.id,
      peerName: this.currentPeer.name,
      brushName: cleanName,
      tool,
      brushSettings: wireSettings,
      ...(assetRefs ? { brushAssetRefs: assetRefs } : {}),
      ...(options?.targetPeerId !== undefined ? { targetPeerId: options.targetPeerId } : {}),
      ...(options?.explicit ? { explicit: true } : {}),
    };
    this.sendMessage(msg);
    return msg;
  }
}

export const multiplayerService = new MultiplayerService();