Skip to content

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

102 KB
Raw Blame
import type {
  BlendMode,
  BrushSettings,
  CanvasColorMode,
  CanvasDimensions,
  ExpressionColor,
  HistoryItemMeta,
  LayerColorLabel,
  LayerItem,
  LayerType,
  ToolType,
} from '../types/editor';
import type { PerspectiveRuler, StraightRuler } from '../types/perspective';
import type { PressureCurveSettings } from '../types/settings';
import { resolveDualBrushConfig } from './dualBrushConfig';
import { isBuiltinSurfaceTextureUrl } from './proceduralBrushTips';

type ToneDotShape = NonNullable<LayerItem['toneDotShape']>;
type ToneDensityType = NonNullable<LayerItem['toneDensityType']>;

export interface NativeViewportRect {
  xPx: number;
  yPx: number;
  widthPx: number;
  heightPx: number;
  dpr: number;
  visible: boolean;
}

export interface NativeUiRect {
  x: number;
  y: number;
  width: number;
  height: number;
}

export interface NativeCameraState {
  panX: number;
  panY: number;
  zoom: number;
  rotation: number;
  flipX: boolean;
  flipY: boolean;
}

export interface NativeCameraEvent extends NativeCameraState {
  commit: boolean;
}

export interface NativeCursorConfig {
  size: number;
  thicknessRatio: number;
  thicknessVertical: boolean;
  tipAngleDeg: number;
  isSquare: boolean;
  visible: boolean;
}

export interface NativeBrushParams {
  size: number;
  opacity: number;
  hardness: number;
  spacing: number;
  minSizeRatio: number;
  usePressureSize: boolean;
  usePressureOpacity: boolean;
  color: [number, number, number, number];
  isEraser: boolean;
}

export type NativeToolKind =
  | 'brush'
  | 'decoration'
  | 'eraser'
  | 'select-pen'
  | 'select-eraser'
  | 'liquify'
  | 'retouch'
  | 'other';
export type NativeWheelNavMode = 'zoom' | 'scroll' | 'brush-size';

export interface NativeInteractionPolicy {
  activeTool: NativeToolKind;
  nativeStrokeEnabled: boolean;
  wheelMode: NativeWheelNavMode;
  isWebtoonMode: boolean;
  textInputFocused: boolean;
  workspaceInteracting: boolean;
  modalOpen: boolean;
}

export interface NativeEngineDiagnostics {
  ready: boolean;
  adapterName: string;
  backend: string;
  presentMode: string;
  fps: number;
  frameTimeMs: number;
  inputToPresentMs: number;
  swapchainWidth: number;
  swapchainHeight: number;
  docWidth: number;
  docHeight: number;
  activeStrokeDabs: number;
  totalFramesRendered: number;
  deviceLostRecoveries: number;
  maxFrameLatency: number;
  compositionMode: string;
  gpuVramUsedBytes?: number;
  gpuVramBudgetBytes?: number;
  gpuTilesResident?: number;
  gpuTilesCapacity?: number;
  stackCacheHits?: number;
  stackCacheRebuilds?: number;
  isIdle?: boolean;
}

export interface NativeSoftProofConfig {
  enabled: boolean;
  standard: 'japan-color-2001' | 'us-web-coated-swop' | 'iso-coated-v2';
  gamutWarning: boolean;
  gamutWarningColor: string;
}

export interface NativeOnionSkinFrame {
  layerId: string;
  tint: [number, number, number];
  opacity: number;
}

export interface NativeCompositorDisplayConfig {
  showCheckerboard: boolean;
  matteColor: [number, number, number, number];
  softProof: NativeSoftProofConfig;
  valueCheckEnabled: boolean;
  showPixelGrid: boolean;
  onionSkinFrames: NativeOnionSkinFrame[];
  celVisibilityOverrides: Record<string, boolean>;
  layerStackCaching: boolean;
}

export interface NativeFlattenOptions {
  maxDim?: number;
  region?: { x: number; y: number; width: number; height: number };
  fillWhiteBackground?: boolean;
  showCheckerboard?: boolean;
  applySoftProof?: boolean;
  softProof?: NativeSoftProofConfig;
  applyValueCheck?: boolean;
  celVisibilityOverrides?: Record<string, boolean>;
  onionSkinFrames?: NativeOnionSkinFrame[];
}

export interface NativeFlattenedImage {
  width: number;
  height: number;
  rgba: Uint8ClampedArray<ArrayBuffer>;
}

export interface NativePointerStatEvent {
  docX: number | null;
  docY: number | null;
  pressure: number;
}

// ---------------------------------------------------------------------------
// Phase 2: Rust Document Store, Layer Tree, CoW History & Tiered Memory Types
// ---------------------------------------------------------------------------

export interface NativeLayerNodeMeta {
  id: string;
  name: string;
  type: LayerType;
  visible: boolean;
  opacity: number;
  blendMode: BlendMode;
  locked: boolean;
  alphaLocked?: boolean;
  clipped?: boolean;
  collapsed?: boolean;
  parentId: string | null;
  isReference?: boolean;
  colorLabel?: LayerColorLabel;
  thumbnailUrl?: string;
  isToneLayer?: boolean;
  toneEnabled?: boolean;
  toneFrequency?: number;
  toneAngle?: number;
  toneDotShape?: ToneDotShape;
  toneDensity?: number;
  toneDensityType?: ToneDensityType;
  layerColorEnabled?: boolean;
  layerColor?: string;
  layerSubColor?: string;
  expressionColor?: ExpressionColor;
  monoThreshold?: number;
  monoExpressBlack?: boolean;
  monoExpressWhite?: boolean;
  hasMask?: boolean;
  maskEnabled?: boolean;
  maskLinked?: boolean;
  maskThumbnailUrl?: string;
  maskVersion?: number;
  adjustmentData?: unknown;
  styles?: unknown;
  comicFrames?: unknown;
  textData?: unknown;
  balloonData?: unknown;
  vectorStrokes?: unknown;
}

export interface NativeLayerPropsPatch {
  name?: string;
  visible?: boolean;
  opacity?: number;
  blendMode?: BlendMode;
  locked?: boolean;
  alphaLocked?: boolean;
  clipped?: boolean;
  collapsed?: boolean;
  parentId?: string | null;
  isReference?: boolean;
  colorLabel?: LayerColorLabel;
  isToneLayer?: boolean;
  toneEnabled?: boolean;
  toneFrequency?: number;
  toneAngle?: number;
  toneDotShape?: ToneDotShape;
  toneDensity?: number;
  toneDensityType?: ToneDensityType;
  layerColorEnabled?: boolean;
  layerColor?: string;
  layerSubColor?: string;
  expressionColor?: ExpressionColor;
  monoThreshold?: number;
  monoExpressBlack?: boolean;
  monoExpressWhite?: boolean;
  maskEnabled?: boolean;
  maskLinked?: boolean;
  adjustmentData?: unknown;
  styles?: unknown;
  comicFrames?: unknown;
  textData?: unknown;
  balloonData?: unknown;
  vectorStrokes?: unknown;
  recordHistory?: boolean;
  historyLabel?: string;
  coalesceKey?: string;
}

export interface NativeHistoryStateSnapshot {
  entries: HistoryItemMeta[];
  /** Legacy alias kept optional for mocks/backward compatibility. */
  items?: HistoryItemMeta[];
  index: number;
  canUndo: boolean;
  canRedo: boolean;
}

/**
 * Safely extracts the ordered history entry list from a Rust `HistoryStateSnapshot`
 * (which serializes `entries`, while older TS mocks may supply `items`).
 */
export function getHistorySnapshotEntries(
  snap: NativeHistoryStateSnapshot | null | undefined
): HistoryItemMeta[] {
  if (!snap) return [];
  if (Array.isArray(snap.entries)) return snap.entries;
  if (Array.isArray(snap.items)) return snap.items;
  return [];
}

export interface NativeDocumentMetaSnapshot {
  id: string;
  name: string;
  dimensions: CanvasDimensions;
  colorMode: CanvasColorMode;
  defaultToneFrequency: number;
  layers: NativeLayerNodeMeta[];
  activeLayerId: string | null;
  history: NativeHistoryStateSnapshot;
  workTimeMs: number;
  previewDataUrl?: string | null;
  perspectiveRuler?: unknown;
  straightRuler?: unknown;
  animationTimeline?: unknown;
  timelapse?: unknown;
}

export interface NativeOpenDocumentResult {
  doc: NativeDocumentMetaSnapshot;
  previewDataUrl: string | null;
  sourceFormat: string;
}

export interface NativeSaveInkResult {
  path: string | null;
  bytesWritten: number;
  previewDataUrl: string | null;
  tileCount: number;
  maskCount: number;
}

export interface NativeSelectiveUndoOutcome {
  applied: boolean;
  strokeId?: string | null;
  layerId?: string | null;
  contestedTileCount: number;
  preservedPeerEdits: boolean;
  history: NativeHistoryStateSnapshot;
}

export interface NativeHistoryMutationResult {
  doc: NativeDocumentMetaSnapshot;
  dimensionsChanged: boolean;
  layersChanged: boolean;
  changedLayerIds: string[];
  documentStateDelta?: unknown;
  selectiveOutcome?: NativeSelectiveUndoOutcome;
}

export interface NativeMemoryStats {
  ramRawBytes: number;
  ramLz4Bytes: number;
  ramTotalBytes: number;
  ramBudgetBytes: number;
  diskPagedTiles: number;
  diskPagedLogicalBytes: number;
  vramUsedBytes: number;
  vramBudgetBytes: number;
  vramSlotsUsed: number;
  vramSlotsCapacity: number;
  solidTileCount: number;
  rawTileCount: number;
  lz4TileCount: number;
  totalTileCount: number;
  historyEntryCount: number;
  openDocumentCount: number;
}

export interface NativeMemoryBudgetInput {
  ramBudgetMb?: number;
  vramBudgetMb?: number;
  maxHistorySteps?: number;
  offloadInactiveTabs?: boolean;
}

export interface NativeThumbnailUpdate {
  layerId: string;
  thumbnailUrl?: string;
  maskThumbnailUrl?: string;
}

export interface NativeHistoryEvent {
  docId: string;
  history: NativeHistoryStateSnapshot;
}

export interface NativeThumbnailsEvent {
  docId: string;
  updates: NativeThumbnailUpdate[];
}

export interface NativeCommittedStrokePoint {
  x: number;
  y: number;
  pressure: number;
  width: number;
  tiltX: number;
  tiltY: number;
  twist: number;
  timestampMs: number;
  isCorner?: boolean;
}

export interface NativeStrokeCommittedEvent {
  docId: string;
  layerId: string;
  entryId: string;
  dirtyRect: { x: number; y: number; width: number; height: number };
  history: NativeHistoryStateSnapshot;
  points: NativeCommittedStrokePoint[];
}

export interface NativeTimelapseCaptureResult {
  width: number;
  height: number;
  bytes: number;
  frameIndex: number;
}

export interface NativeRecoveryCheckpointResult {
  snapshotBytes: number;
  thumbnailBytes: number;
}

const EVENT_CAMERA = 'native-engine://camera';
const EVENT_DIAGNOSTICS = 'native-engine://diagnostics';
const EVENT_POINTER_STAT = 'native-engine://pointer-stat';
const EVENT_HISTORY = 'native-engine://history';
const EVENT_THUMBNAILS = 'native-engine://thumbnails';
const EVENT_STROKE_COMMITTED = 'native-engine://stroke-committed';
const EVENT_SELECTION_CHANGED = 'native-engine://selection-changed';
const EVENT_VIEWPORT_INVALIDATED = 'native-engine://viewport-invalidated';

type TauriInvokeFn = typeof import('@tauri-apps/api/core').invoke;
type TauriListenFn = typeof import('@tauri-apps/api/event').listen;

let cachedNativeActive = false;
let initPromise: Promise<boolean> | null = null;
const activeListeners = new Set<(active: boolean) => void>();

let cachedTauriInvoke: TauriInvokeFn | null = null;
let tauriInvokePromise: Promise<TauriInvokeFn> | null = null;
let cachedTauriListen: TauriListenFn | null = null;
let tauriListenPromise: Promise<TauriListenFn> | null = null;

async function getTauriInvoke(): Promise<TauriInvokeFn> {
  if (cachedTauriInvoke) return cachedTauriInvoke;
  if (!tauriInvokePromise) {
    tauriInvokePromise = import('@tauri-apps/api/core')
      .then((m) => {
        cachedTauriInvoke = m.invoke;
        return m.invoke;
      })
      .catch((err) => {
        tauriInvokePromise = null;
        throw err;
      });
  }
  return tauriInvokePromise;
}

async function getTauriListen(): Promise<TauriListenFn> {
  if (cachedTauriListen) return cachedTauriListen;
  if (!tauriListenPromise) {
    tauriListenPromise = import('@tauri-apps/api/event')
      .then((m) => {
        cachedTauriListen = m.listen;
        return m.listen;
      })
      .catch((err) => {
        tauriListenPromise = null;
        throw err;
      });
  }
  return tauriListenPromise;
}

export function isTauriDesktopRuntime(): boolean {
  if (typeof window === 'undefined') return false;
  const w = window as unknown as Record<string, unknown>;
  return Boolean(w.__TAURI_INTERNALS__ || w.__TAURI__);
}

/**
 * Synchronous check used on hot input paths (pointer handlers, cursor ring, document ops)
 * to determine whether the native Windows DX12 DirectComposition engine is currently active.
 * Always returns `false` in web/Vitest environments.
 */
export function isNativeCanvasActive(): boolean {
  return cachedNativeActive;
}

/**
 * Returns true if the given tool is natively handled on the zero-IPC Rust stroke path.
 */
export function isNativeStrokeTool(tool: ToolType | string): boolean {
  return (
    tool === 'brush' ||
    tool === 'decoration' ||
    tool === 'eraser' ||
    tool === 'select-pen' ||
    tool === 'select-eraser'
  );
}

export function classifyNativeTool(tool: ToolType | string): NativeToolKind {
  if (tool === 'brush') return 'brush';
  if (tool === 'decoration') return 'decoration';
  if (tool === 'eraser') return 'eraser';
  if (tool === 'select-pen') return 'select-pen';
  if (tool === 'select-eraser') return 'select-eraser';
  if (tool === 'liquify') return 'liquify';
  if (
    tool === 'retouch' ||
    tool === 'smudge' ||
    tool === 'blur' ||
    tool === 'dodge' ||
    tool === 'burn' ||
    tool === 'sponge' ||
    tool === 'clone-stamp' ||
    tool === 'heal'
  ) {
    return 'retouch';
  }
  return 'other';
}

/**
 * Phase 5/6 native capability check:
 * **100% of brush presets** and selection pen/eraser execute exclusively in native Rust DX12
 * `ink-engine` for raster layers, layer masks, and the sparse selection mask.
 */
export function canNativeEngineHandleBrush(
  tool: ToolType | string,
  bs: BrushSettings | null | undefined,
  activeLayer?: Pick<LayerItem, 'type' | 'locked' | 'visible'> | null,
  _isMaskMode: boolean = false
): boolean {
  if (tool === 'select-pen' || tool === 'select-eraser') return true;
  if (!isNativeStrokeTool(tool) || !bs) return false;
  if (activeLayer && activeLayer.type !== 'raster') return false;
  return true;
}

/**
 * Maps `performanceManager`'s `gpuTexturePoolPreset` string to an L1 DX12 VRAM tile budget (MB).
 */
export function vramBudgetMbFromPreset(preset?: string): number {
  switch (preset) {
    case 'low':
      return 128;
    case 'balanced':
    case 'medium':
      return 256;
    case 'high':
      return 512;
    case 'ultra':
      return 1024;
    default:
      return 256;
  }
}

/**
 * Converts a React `LayerItem` into a compact JSON-serializable `NativeLayerNodeMeta`
 * (stripping DOM canvas references while preserving all layer properties and mask flags).
 */
export function toNativeLayerNodeMeta(layer: LayerItem): NativeLayerNodeMeta {
  const { maskCanvas, ...rest } = layer;
  const anyLayer = layer as LayerItem & { hasMask?: boolean };
  return {
    ...rest,
    hasMask: Boolean(maskCanvas || anyLayer.hasMask),
  } as NativeLayerNodeMeta;
}

/**
 * Hydrates a compact Rust `NativeLayerNodeMeta` into a React `LayerItem` without allocating
 * any full-resolution JS pixel buffers or DOM canvases.
 */
export function fromNativeLayerNodeMeta(meta: NativeLayerNodeMeta): LayerItem {
  return {
    ...(meta as unknown as LayerItem),
    thumbnailUrl: meta.thumbnailUrl ?? '',
  };
}

export function subscribeNativeCanvasActive(listener: (active: boolean) => void): () => void {
  activeListeners.add(listener);
  return () => {
    activeListeners.delete(listener);
  };
}

function setCachedNativeActive(active: boolean) {
  if (cachedNativeActive === active) return;
  cachedNativeActive = active;
  for (const cb of activeListeners) {
    try {
      cb(active);
    } catch {
      // Ignore subscriber errors
    }
  }
}

/**
 * Queries the Tauri host once to verify whether `ink-engine` initialized its Windows DX12
 * DirectComposition swapchain cleanly. Safe to call repeatedly.
 */
export async function initNativeEngineBridge(): Promise<boolean> {
  if (!isTauriDesktopRuntime()) {
    setCachedNativeActive(false);
    return false;
  }
  if (initPromise) return initPromise;

  initPromise = (async () => {
    try {
      const invoke = await getTauriInvoke();
      const active = await invoke<boolean>('native_engine_is_active');
      const resolved = Boolean(active);
      setCachedNativeActive(resolved);
      return resolved;
    } catch {
      setCachedNativeActive(false);
      return false;
    }
  })();

  return initPromise;
}

/**
 * Parses a CSS hex (`#rgb`, `#rrggbb`, `#rrggbbaa`) or `rgb()/rgba()` color string into
 * normalized `[r, g, b, a]` in `0.0..=1.0`.
 */
export function parseCssColorToRgba(
  cssColor: string | null | undefined,
  fallback: [number, number, number, number] = [0.086, 0.086, 0.086, 1.0]
): [number, number, number, number] {
  const safeFallback: [number, number, number, number] =
    Array.isArray(fallback) && fallback.length >= 4
      ? [
          Number.isFinite(fallback[0]) ? fallback[0] : 0.086,
          Number.isFinite(fallback[1]) ? fallback[1] : 0.086,
          Number.isFinite(fallback[2]) ? fallback[2] : 0.086,
          Number.isFinite(fallback[3]) ? fallback[3] : 1.0,
        ]
      : [0.086, 0.086, 0.086, 1.0];
  if (typeof cssColor !== 'string') return safeFallback;
  const raw = cssColor.trim();
  if (!raw) return safeFallback;
  if (raw.startsWith('#')) {
    const hex = raw.slice(1);
    if (hex.length === 3) {
      const r = parseInt(hex[0] + hex[0], 16);
      const g = parseInt(hex[1] + hex[1], 16);
      const b = parseInt(hex[2] + hex[2], 16);
      if (!Number.isNaN(r) && !Number.isNaN(g) && !Number.isNaN(b)) {
        return [r / 255, g / 255, b / 255, 1.0];
      }
    } else if (hex.length === 6 || hex.length === 8) {
      const r = parseInt(hex.slice(0, 2), 16);
      const g = parseInt(hex.slice(2, 4), 16);
      const b = parseInt(hex.slice(4, 6), 16);
      const a = hex.length === 8 ? parseInt(hex.slice(6, 8), 16) : 255;
      if (!Number.isNaN(r) && !Number.isNaN(g) && !Number.isNaN(b) && !Number.isNaN(a)) {
        return [r / 255, g / 255, b / 255, a / 255];
      }
    }
    return safeFallback;
  }

  const match = raw.match(
    /rgba?\(\s*([\d.]+)\s*[,\s]\s*([\d.]+)\s*[,\s]\s*([\d.]+)(?:\s*[,/]\s*([\d.]+))?\s*\)/i
  );
  if (match) {
    const r = Math.max(0, Math.min(255, Number(match[1]))) / 255;
    const g = Math.max(0, Math.min(255, Number(match[2]))) / 255;
    const b = Math.max(0, Math.min(255, Number(match[3]))) / 255;
    const a = match[4] !== undefined ? Math.max(0, Math.min(1, Number(match[4]))) : 1.0;
    if (Number.isFinite(r) && Number.isFinite(g) && Number.isFinite(b) && Number.isFinite(a)) {
      return [r, g, b, a];
    }
  }
  return safeFallback;
}

async function invokeFireAndForget(cmd: string, args?: Record<string, unknown>): Promise<void> {
  if (!cachedNativeActive || !isTauriDesktopRuntime()) return;
  try {
    const invoke = await getTauriInvoke();
    await invoke(cmd, args);
  } catch {
    // Ignore transient IPC errors during window teardown
  }
}

async function invokeNative<T>(cmd: string, args?: Record<string, unknown>): Promise<T> {
  const invoke = await getTauriInvoke();
  return invoke<T>(cmd, args);
}

// ---------------------------------------------------------------------------
// Phase 1: Viewport, Camera, Brush, Cursor & Policy Commands
// ---------------------------------------------------------------------------

export function setNativeViewport(rect: NativeViewportRect): Promise<void> {
  return invokeFireAndForget('native_engine_set_viewport', {
    xPx: Math.round(rect.xPx),
    yPx: Math.round(rect.yPx),
    widthPx: Math.max(0, Math.round(rect.widthPx)),
    heightPx: Math.max(0, Math.round(rect.heightPx)),
    dpr: rect.dpr,
    visible: rect.visible,
  });
}

export function setNativeOccludedRects(rects: NativeUiRect[]): Promise<void> {
  return invokeFireAndForget('native_engine_set_occluded_rects', { rects });
}

export function setNativeDocument(
  width: number,
  height: number,
  showCheckerboard: boolean
): Promise<void> {
  return invokeFireAndForget('native_engine_set_document', {
    width: Math.max(1, Math.round(width)),
    height: Math.max(1, Math.round(height)),
    showCheckerboard,
  });
}

export function setNativeAppearance(
  matteRgba: [number, number, number, number],
  showCheckerboard: boolean
): Promise<void> {
  return invokeFireAndForget('native_engine_set_appearance', {
    matteRgba,
    showCheckerboard,
  });
}

export function setNativeDisplayConfig(config: NativeCompositorDisplayConfig): Promise<void> {
  return invokeFireAndForget('native_engine_set_display_config', { config });
}

export function invalidateNativeCompositorCache(): Promise<void> {
  return invokeFireAndForget('native_engine_invalidate_compositor_cache');
}

export function flushNativeGpuPool(): Promise<void> {
  return invokeFireAndForget('native_engine_flush_gpu_pool');
}

function decodePackedRgbaResponse(raw: unknown): NativeFlattenedImage | null {
  let bytes: Uint8Array | null = null;
  if (raw instanceof ArrayBuffer) {
    bytes = new Uint8Array(raw);
  } else if (ArrayBuffer.isView(raw)) {
    bytes = new Uint8Array(raw.buffer, raw.byteOffset, raw.byteLength);
  } else if (Array.isArray(raw)) {
    bytes = Uint8Array.from(raw);
  }
  if (!bytes || bytes.byteLength < 8) return null;
  const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
  const width = view.getUint32(0, true);
  const height = view.getUint32(4, true);
  const expected = width * height * 4;
  if (width === 0 || height === 0 || bytes.byteLength < 8 + expected) return null;
  const rgba = new Uint8ClampedArray(new ArrayBuffer(expected));
  rgba.set(bytes.subarray(8, 8 + expected));
  return { width, height, rgba };
}

/**
 * Renders the document (full-res or downscaled / sub-region) directly on the native DX12 GPU
 * via `WgpuCompositor::render_document_flattened`.
 */
export async function flattenNativeDocument(
  docId?: string | null,
  options?: NativeFlattenOptions
): Promise<NativeFlattenedImage | null> {
  if (!cachedNativeActive || !isTauriDesktopRuntime()) return null;
  try {
    const raw = await invokeNative<ArrayBuffer | Uint8Array>('native_engine_flatten_document', {
      docId: docId ?? null,
      options: options ?? null,
    });
    return decodePackedRgbaResponse(raw);
  } catch {
    return null;
  }
}

/**
 * Renders a GPU-accelerated Navigator preview image directly on DX12 via `ink-engine`.
 */
export async function renderNativeNavigatorPreview(params: {
  docId?: string | null;
  maxDim?: number;
  showCheckerboard?: boolean;
  applySoftProof?: boolean;
  softProof?: NativeSoftProofConfig;
  applyValueCheck?: boolean;
}): Promise<NativeFlattenedImage | null> {
  if (!cachedNativeActive || !isTauriDesktopRuntime()) return null;
  try {
    const raw = await invokeNative<ArrayBuffer | Uint8Array>(
      'native_engine_render_navigator_preview',
      {
        docId: params.docId ?? null,
        maxDim: params.maxDim ?? 256,
        showCheckerboard: params.showCheckerboard ?? false,
        applySoftProof: params.applySoftProof ?? false,
        softProof: params.softProof ?? null,
        applyValueCheck: params.applyValueCheck ?? false,
      }
    );
    return decodePackedRgbaResponse(raw);
  } catch {
    return null;
  }
}

export function setNativeCamera(camera: NativeCameraState): Promise<void> {
  return invokeFireAndForget('native_engine_set_camera', { camera });
}

export function setNativeCursor(config: NativeCursorConfig): Promise<void> {
  return invokeFireAndForget('native_engine_set_cursor', { config });
}

export function setNativeBrush(params: NativeBrushParams): Promise<void> {
  return invokeFireAndForget('native_engine_set_brush', { params });
}

// ---------------------------------------------------------------------------
// Phase 4: Full CSP Brush Config, Global Pressure Curve, Rulers & Texture Cache
// ---------------------------------------------------------------------------

const uploadedBrushTextureHashes = new Set<string>();

function fnv1aHashHex(input: string): string {
  let h1 = 0x811c9dc5;
  let h2 = 0x01000193;
  for (let i = 0; i < input.length; i++) {
    const ch = input.charCodeAt(i);
    h1 ^= ch & 0xff;
    h1 = Math.imul(h1, 0x01000193) >>> 0;
    h2 ^= (ch >>> 8) ^ (i & 0xff);
    h2 = Math.imul(h2, 0x85ebca6b) >>> 0;
  }
  return `${h1.toString(16).padStart(8, '0')}${h2.toString(16).padStart(8, '0')}_${input.length}`;
}

function decodeBase64ToBytes(b64: string): Uint8Array | null {
  try {
    const bin = atob(b64);
    const out = new Uint8Array(bin.length);
    for (let i = 0; i < bin.length; i++) {
      out[i] = bin.charCodeAt(i);
    }
    return out;
  } catch {
    return null;
  }
}

async function decodeImageDataUrlToRgba8(
  dataUrl: string
): Promise<{ width: number; height: number; rgba: Uint8Array } | null> {
  if (typeof document === 'undefined' || typeof Image === 'undefined') return null;
  return new Promise((resolve) => {
    const img = new Image();
    img.onload = () => {
      try {
        const w = Math.max(1, Math.min(2048, img.naturalWidth || img.width || 64));
        const h = Math.max(1, Math.min(2048, img.naturalHeight || img.height || 64));
        const canvas = document.createElement('canvas');
        canvas.width = w;
        canvas.height = h;
        const ctx = canvas.getContext('2d');
        if (!ctx) {
          resolve(null);
          return;
        }
        ctx.drawImage(img, 0, 0, w, h);
        const imgData = ctx.getImageData(0, 0, w, h);
        resolve({ width: w, height: h, rgba: new Uint8Array(imgData.data.buffer) });
      } catch {
        resolve(null);
      }
    };
    img.onerror = () => resolve(null);
    img.src = dataUrl;
  });
}

/**
 * Content-hashed one-time binary upload of a brush tip or paper texture into `ink-engine`.
 * Uploads at most once per unique content hash; subsequent brush switches hit GPU cache directly!
 */
export async function ensureNativeTextureUploaded(
  dataUrl: string | undefined | null,
  kind: 'tip' | 'paper'
): Promise<string | null> {
  if (!dataUrl || typeof dataUrl !== 'string' || !cachedNativeActive || !isTauriDesktopRuntime()) {
    return null;
  }
  const hash = `${kind}:${fnv1aHashHex(dataUrl)}`;
  if (uploadedBrushTextureHashes.has(hash)) {
    return hash;
  }

  try {
    const invoke = await getTauriInvoke();
    const pngPrefix = 'data:image/png;base64,';
    if (dataUrl.startsWith(pngPrefix)) {
      const pngBytes = decodeBase64ToBytes(dataUrl.slice(pngPrefix.length));
      if (!pngBytes || pngBytes.byteLength < 16) return null;
      await invoke('native_engine_upload_brush_texture', pngBytes, {
        headers: {
          'x-hash': hash,
          'x-kind': kind,
          'x-format': 'png',
          'x-width': '0',
          'x-height': '0',
        },
      });
      uploadedBrushTextureHashes.add(hash);
      return hash;
    }

    // Non-PNG data URL (e.g. WebP/JPEG): decode once to RGBA8 and upload
    const decoded = await decodeImageDataUrlToRgba8(dataUrl);
    if (!decoded) return null;
    await invoke('native_engine_upload_brush_texture', decoded.rgba, {
      headers: {
        'x-hash': hash,
        'x-kind': kind,
        'x-format': 'rgba8',
        'x-width': String(decoded.width),
        'x-height': String(decoded.height),
      },
    });
    uploadedBrushTextureHashes.add(hash);
    return hash;
  } catch {
    return null;
  }
}

export function setNativeFullBrush(config: Record<string, unknown>): Promise<void> {
  return invokeFireAndForget('native_engine_set_full_brush', { config });
}

/**
 * Resets persistent dirty GPU brush pigment reservoirs (`autoClean: false`).
 * Omit `presetKey` to clean all presets.
 */
export function cleanNativeDirtyBrush(presetKey?: string): Promise<void> {
  return invokeFireAndForget('native_engine_clean_dirty_brush', {
    presetKey: presetKey ?? null,
  });
}

/**
 * Toggles whether active native DX12 brush strokes paint onto the active layer's
 * 8-bit non-destructive mask tiles instead of its raster tiles.
 */
export function setNativeMaskMode(enabled: boolean): Promise<void> {
  return invokeFireAndForget('native_engine_set_mask_mode', { enabled: Boolean(enabled) });
}

/**
 * Enables or disables embedding the full `points` array on `native-engine://stroke-committed`
 * events. Keep disabled during solo sketching to avoid per-stroke cloning & JSON serialization.
 */
export function setNativeCollabPointsEnabled(enabled: boolean): Promise<void> {
  return invokeFireAndForget('native_engine_set_collab_points_enabled', {
    enabled: Boolean(enabled),
  });
}

export interface NativeScratchpadStrokePoint {
  x: number;
  y: number;
  pressure: number;
  tiltX: number;
  tiltY: number;
  twist: number;
  timestampMs: number;
}

export interface NativeScratchpadStrokeInput {
  points: NativeScratchpadStrokePoint[];
  color: [number, number, number];
  seed: number;
}

/**
 * Renders a GPU-accelerated S-curve brush preview directly on DX12 via `ink-engine`.
 */
export async function renderNativeBrushPreview(
  tool: ToolType,
  bs: BrushSettings,
  primaryColor: string,
  secondaryColor: string,
  width: number,
  height: number
): Promise<NativeFlattenedImage | null> {
  if (!cachedNativeActive || !isTauriDesktopRuntime()) return null;
  try {
    const config = await buildNativeBrushConfigPayload(tool, bs, primaryColor, secondaryColor, false);
    const raw = await invokeNative<ArrayBuffer | Uint8Array>('native_engine_render_brush_preview', {
      brush: config,
      width: Math.max(32, Math.min(1024, Math.round(width))),
      height: Math.max(16, Math.min(512, Math.round(height))),
    });
    return decodePackedRgbaResponse(raw);
  } catch {
    return null;
  }
}

/**
 * Re-renders Brush Studio scratchpad strokes directly on DX12 via `ink-engine`
 * with the live-edited BrushSettings so every parameter change updates in real time.
 */
export async function renderNativeScratchpadPreview(
  tool: ToolType,
  bs: BrushSettings,
  primaryColor: string,
  secondaryColor: string,
  strokes: NativeScratchpadStrokeInput[],
  width: number,
  height: number
): Promise<NativeFlattenedImage | null> {
  if (!cachedNativeActive || !isTauriDesktopRuntime()) return null;
  try {
    const config = await buildNativeBrushConfigPayload(tool, bs, primaryColor, secondaryColor, false);
    const raw = await invokeNative<ArrayBuffer | Uint8Array>(
      'native_engine_render_scratchpad_preview',
      {
        brush: config,
        strokes,
        width: Math.max(32, Math.min(1024, Math.round(width))),
        height: Math.max(32, Math.min(1024, Math.round(height))),
      }
    );
    return decodePackedRgbaResponse(raw);
  } catch {
    return null;
  }
}

function sanitizeOptionalCurveForNative(curve: unknown): [number, number][] | null {
  if (!Array.isArray(curve) || curve.length === 0) return null;
  const valid: [number, number][] = [];
  for (const pt of curve) {
    if (
      Array.isArray(pt) &&
      pt.length >= 2 &&
      typeof pt[0] === 'number' &&
      typeof pt[1] === 'number' &&
      Number.isFinite(pt[0]) &&
      Number.isFinite(pt[1])
    ) {
      valid.push([Math.max(0, Math.min(1, pt[0])), Math.max(0, Math.min(1, pt[1]))]);
    }
  }
  return valid.length > 0 ? valid : null;
}

export function setNativePressureCurve(curve: PressureCurveSettings | null | undefined): Promise<void> {
  const validPoints = sanitizeOptionalCurveForNative(curve?.points);
  const payload =
    curve && typeof curve === 'object'
      ? {
          enabled: Boolean(curve.enabled),
          points: validPoints && validPoints.length >= 2 ? validPoints : [[0, 0], [1, 1]],
          gamma: 1.0,
        }
      : {
          enabled: false,
          points: [
            [0, 0],
            [1, 1],
          ],
          gamma: 1.0,
        };
  return invokeFireAndForget('native_engine_set_pressure_curve', { curve: payload });
}

export function setNativeRulers(
  straight: StraightRuler | null | undefined,
  perspective: PerspectiveRuler | null | undefined
): Promise<void> {
  const straightPayload = straight
    ? {
        enabled: Boolean(straight.enabled),
        visible: Boolean(straight.enabled),
        snapEnabled: Boolean(straight.snapEnabled),
        x: straight.x,
        y: straight.y,
        angle: straight.angle,
        length: 600,
        locked: Boolean(straight.locked),
      }
    : null;

  const perspPayload = perspective
    ? {
        enabled: Boolean(perspective.enabled),
        visible: Boolean(perspective.enabled),
        snapEnabled: Boolean(perspective.snapEnabled),
        mode: perspective.type,
        horizonAngle: perspective.horizonAngle ?? 0,
        vanishingPoints: (perspective.vps || []).map((vp) => ({
          id: vp.id,
          x: vp.x,
          y: vp.y,
          enabled: true,
        })),
      }
    : null;

  return invokeFireAndForget('native_engine_set_rulers', {
    straight: straightPayload,
    perspective: perspPayload,
  });
}

function mapSensorToNative(sensor: BrushSettings['sizeSensor']): Record<string, unknown> | null {
  if (!sensor || typeof sensor !== 'object') return null;
  return {
    usePressure: Boolean(sensor.usePressure),
    pressureMin: sensor.pressureMin ?? 0,
    pressureCurve: sanitizeOptionalCurveForNative(sensor.pressureCurve),
    useTilt: Boolean(sensor.useTilt),
    tiltMin: sensor.tiltMin ?? 0,
    tiltMax: sensor.tiltMax ?? 1.0,
    tiltCurve: sanitizeOptionalCurveForNative(sensor.tiltCurve),
    useVelocity: Boolean(sensor.useVelocity),
    velocityMin: sensor.velocityMin ?? 0,
    velocityInvert: Boolean(sensor.invertVelocity),
    velocityCurve: sanitizeOptionalCurveForNative(sensor.velocityCurve),
    useRandom: Boolean(sensor.useRandom),
    randomMin: sensor.randomMin ?? 0,
    useDistance: Boolean(sensor.useDistance),
    distanceMin: sensor.distanceMin ?? 0,
    distanceMaxPx: sensor.distanceMaxPx ?? 300,
    distanceInvert: false,
  };
}

function mapDynamicsToNative(dyn: BrushSettings['dynamics']): Record<string, unknown> {
  return {
    sizeJitter: dyn?.sizeJitter ?? 0,
    angleJitter: dyn?.angleJitter ?? 0,
    roundnessJitter: dyn?.roundnessJitter ?? 0,
    scatter: dyn?.scatter ?? 0,
    scatterBothAxes: Boolean(dyn?.scatterBothAxes),
    count: Math.max(1, Math.min(10, Math.round(dyn?.count ?? 1))),
    flowJitter: dyn?.flowJitter ?? 0,
    colorJitterEnabled: Boolean(dyn?.colorJitterEnabled),
    colorJitterPerDab: dyn?.colorJitterPerStroke !== true,
    hueJitter: dyn?.hueJitter ?? 0,
    saturationJitter: dyn?.saturationJitter ?? 0,
    luminanceJitter: dyn?.brightnessJitter ?? 0,
    fgBgJitter: dyn?.foregroundBackgroundJitter ?? 0,
    temperatureJitter: dyn?.temperatureJitter ?? 0,
  };
}

function mapSprayToNative(spray: BrushSettings['spray']): Record<string, unknown> | null {
  if (!spray || !spray.enabled) return null;
  return {
    enabled: true,
    particleSize: spray.particleSize ?? 6,
    linkSize: spray.linkSize !== false,
    density: spray.density ?? 3,
    deviation: spray.deviation ?? 0,
    direction: spray.direction ?? 0,
    directionDynamics: spray.directionDynamics ?? 'random',
    sizeSensor: mapSensorToNative(spray.sizeSensor),
    densitySensor: mapSensorToNative(spray.densitySensor),
  };
}

/**
 * Uploads any uncached custom tips / sub-tips / dual-tips / paper texture once by content hash,
 * and constructs the full Phase 4 + Phase 5 CSP-compatible `NativeBrushConfig` payload.
 */
export async function buildNativeBrushConfigPayload(
  tool: ToolType,
  bs: BrushSettings | Partial<BrushSettings> | null | undefined,
  primaryColor: string,
  secondaryColor: string,
  isBgEraser = false
): Promise<Record<string, unknown>> {
  const safeBs = (bs && typeof bs === 'object' ? bs : {}) as Partial<BrushSettings>;
  const fg = parseCssColorToRgba(primaryColor, [0.05, 0.05, 0.05, 1.0]);
  const bg = parseCssColorToRgba(secondaryColor, [1.0, 1.0, 1.0, 1.0]);

  const primaryTipDataUrl = safeBs.customTipDataUrl || safeBs.customTipImage?.src;
  const tipKey = await ensureNativeTextureUploaded(primaryTipDataUrl, 'tip');

  const subTipKeys: string[] = [];
  if (Array.isArray(safeBs.subTips) && safeBs.subTips.length > 0) {
    for (const st of safeBs.subTips) {
      if (!st || typeof st !== 'object') continue;
      const k = await ensureNativeTextureUploaded(st.dataUrl, 'tip');
      if (k) subTipKeys.push(k);
    }
  } else if (Array.isArray(safeBs.subTipImages) && safeBs.subTipImages.length > 0) {
    for (const img of safeBs.subTipImages) {
      const k = await ensureNativeTextureUploaded(img?.src, 'tip');
      if (k) subTipKeys.push(k);
    }
  }

  const isBuiltinSurfacePaper = Boolean(
    safeBs.surfaceTextureId && (!safeBs.paperTexture || isBuiltinSurfaceTextureUrl(safeBs.paperTexture))
  );
  const paperKey = isBuiltinSurfacePaper
    ? null
    : await ensureNativeTextureUploaded(safeBs.paperTexture, 'paper');

  // Dual brush secondary tip(s)
  const dualCfg = resolveDualBrushConfig(safeBs as BrushSettings);
  let dualPayload: Record<string, unknown> | null = null;
  if (dualCfg && dualCfg.enabled) {
    const dualTipDataUrl = dualCfg.tipDataUrl || dualCfg.tipImage?.src;
    const dualTipKey = await ensureNativeTextureUploaded(dualTipDataUrl, 'tip');
    const dualSubTipKeys: string[] = [];
    if (Array.isArray(dualCfg.subTips) && dualCfg.subTips.length > 0) {
      for (const st of dualCfg.subTips) {
        if (!st || typeof st !== 'object') continue;
        const k = await ensureNativeTextureUploaded(st.dataUrl, 'tip');
        if (k) dualSubTipKeys.push(k);
      }
    } else if (Array.isArray(dualCfg.subTipImages) && dualCfg.subTipImages.length > 0) {
      for (const img of dualCfg.subTipImages) {
        const k = await ensureNativeTextureUploaded(img?.src, 'tip');
        if (k) dualSubTipKeys.push(k);
      }
    }
    dualPayload = {
      enabled: true,
      combineMode: dualCfg.compositeMode ?? 'multiply',
      size: dualCfg.size ?? safeBs.size ?? 12,
      linkSize: dualCfg.linkSizeWithMain !== false,
      sizeRatio: dualCfg.sizeRatio ?? safeBs.dualScale ?? 1.0,
      spacing: dualCfg.spacing ?? safeBs.spacing ?? 0.15,
      hardness: dualCfg.hardness ?? safeBs.hardness ?? 0.8,
      thickness: dualCfg.thickness ?? 1.0,
      thicknessVertical: Boolean(dualCfg.thicknessVertical),
      angle: dualCfg.angle ?? 0,
      angleDynamics: dualCfg.angleDynamics ?? 'none',
      rotationRandomScale: 0,
      flipH: dualCfg.flipH ?? 'none',
      flipV: dualCfg.flipV ?? 'none',
      density: dualCfg.density ?? 1.0,
      adjustDensityByGap: false,
      subTipOrder: dualCfg.subTipOrder ?? 'sequential',
      isRibbon: Boolean(dualCfg.isRibbon),
      ribbonRepeatMode: 'repeat',
      tipKey: dualTipKey,
      subTipKeys: dualSubTipKeys,
      sizeSensor: null,
      densitySensor: null,
      thicknessSensor: null,
      dynamics:
        (dualCfg.scatter ?? 0) > 0.001
          ? mapDynamicsToNative({ scatter: dualCfg.scatter, scatterBothAxes: true } as BrushSettings['dynamics'])
          : null,
      spray: mapSprayToNative(dualCfg.spray),
    };
  }

  const taperPayload = safeBs.taper
    ? {
        useIn: Boolean(safeBs.taper.useIn),
        inLength: safeBs.taper.inLength ?? 0,
        inRatio: safeBs.taper.inRatio ?? 0,
        useOut: Boolean(safeBs.taper.useOut),
        outLength: safeBs.taper.outLength ?? 0,
        outRatio: safeBs.taper.outRatio ?? 0,
        inOutType: safeBs.taper.inOutType ?? 2,
        inOutBySpeed: Boolean(safeBs.taper.inOutBySpeed),
        startingSharpness: safeBs.taper.startingSharpness ?? 0.5,
        endingSharpness: safeBs.taper.endingSharpness ?? 0.5,
        affectSize: safeBs.taper.affectSize !== false,
        minSizeRatio: safeBs.taper.minSizeRatio ?? 0,
        affectOpacity: Boolean(safeBs.taper.affectOpacity),
        affectDensity: Boolean(safeBs.taper.affectDensity),
        minDensityRatio: safeBs.taper.minDensityRatio ?? 0,
        affectAmountOfPaint: Boolean(safeBs.taper.affectAmountOfPaint),
        minAmountRatio: safeBs.taper.minAmountRatio ?? 0,
        affectDensityOfPaint: Boolean(safeBs.taper.affectDensityOfPaint),
        minPaintDensityRatio: safeBs.taper.minPaintDensityRatio ?? 0,
        affectLoad: Boolean(safeBs.taper.affectLoad),
      }
    : null;

  const isEraser = tool === 'eraser' || Boolean(safeBs.isTransparentInk);

  return {
    fgColor: [fg?.[0] ?? 0.05, fg?.[1] ?? 0.05, fg?.[2] ?? 0.05],
    bgColor: [bg?.[0] ?? 1.0, bg?.[1] ?? 1.0, bg?.[2] ?? 1.0],
    size: Math.max(0.5, Number.isFinite(safeBs.size) ? (safeBs.size as number) : 12),
    minSizeFactor: Math.max(0, Math.min(1, safeBs.minSizeFactor ?? 0.05)),
    opacity: Math.max(0.01, Math.min(1, safeBs.opacity ?? 1.0)),
    flow: Math.max(0.01, Math.min(1, safeBs.flow ?? 1.0)),
    brushDensity: Math.max(0.01, Math.min(1, safeBs.brushDensity ?? 1.0)),
    adjustDensityByGap: Boolean(safeBs.adjustDensityByGap),
    hardness: Math.max(0, Math.min(1, safeBs.hardness ?? 0.9)),
    antiAlias: Math.max(0, Math.min(3, Math.round(safeBs.antiAlias ?? 2))),
    spacing: Math.max(0.02, Math.min(4.0, safeBs.spacing || 0.1)),
    stabilization: Math.max(0, Math.min(50, safeBs.stabilization ?? 0)),
    sharpCorners: Boolean(safeBs.sharpCorners),
    postCorrection: Math.max(0, Math.min(5, Math.round(safeBs.postCorrection ?? 0))),
    smoothing: safeBs.smoothing !== false,
    usePressure: Boolean(safeBs.sizeSensor?.usePressure ?? safeBs.usePressure ?? true),
    useTilt: Boolean(safeBs.useTilt),
    tiltScale: safeBs.tiltScale ?? 1.0,
    pressureCurveGamma: safeBs.pressureCurveGamma ?? 1.0,
    pressureCurve: sanitizeOptionalCurveForNative(safeBs.pressureCurve),
    isEraser,
    isTransparentInk: Boolean(safeBs.isTransparentInk),
    isBgEraser: Boolean(isBgEraser),
    enableFlickTaper: Boolean(safeBs.sharpCorners && (safeBs.taper?.useOut || safeBs.taper?.inOutBySpeed)),
    tipKey,
    subTipKeys,
    subTipOrder: safeBs.subTipOrder ?? 'sequential',
    isColorTip: Boolean(safeBs.isColorTip),
    isDualToneTip: Boolean(safeBs.isDualToneTip),
    thickness: Math.max(0.1, Math.min(1.0, safeBs.thickness ?? 1.0)),
    thicknessVertical: Boolean(safeBs.thicknessVertical),
    customTipAngle: safeBs.customTipAngle ?? 0,
    customTipAngleDynamics: safeBs.customTipAngleDynamics ?? 'none',
    customTipRotationRandomScale: safeBs.customTipRotationRandomScale ?? 0,
    flipH: safeBs.flipH ?? 'none',
    flipV: safeBs.flipV ?? 'none',
    blendTipsMode: safeBs.blendTipsMode ?? 'normal',
    brushCombineMode: safeBs.brushCombineMode ?? 'normal',
    paperTextureKey: paperKey,
    surfaceTextureId: safeBs.surfaceTextureId ?? null,
    grain: safeBs.grain ?? 0,
    textureDensity: safeBs.textureDensity ?? 0,
    paperTextureMode: safeBs.paperTextureMode ?? 'subtract',
    grainMappingMode: safeBs.grainMappingMode ?? 'canvas-locked',
    paperTextureScale: safeBs.paperTextureScale ?? 1.0,
    paperTextureRotate: safeBs.paperTextureRotate ?? 0,
    paperTextureOffsetX: safeBs.paperTextureOffsetX ?? 0,
    paperTextureOffsetY: safeBs.paperTextureOffsetY ?? 0,
    paperTextureBrightness: safeBs.paperTextureBrightness ?? 0,
    paperTextureContrast: safeBs.paperTextureContrast ?? 0,
    paperTextureInvert: Boolean(safeBs.paperTextureInverted),
    paperTextureApplyEachPlot: safeBs.paperTextureApplyEachPlot !== false,
    emphasizeDensity: Boolean(safeBs.paperTextureEmphasizeDensity),
    wetEdge: safeBs.wetEdge ?? 0,
    wetEdgeRadius: safeBs.wetEdgeRadius ?? 3.0,
    wetEdgeAlphaPower: safeBs.wetEdgeAlphaPower ?? 1.0,
    wetEdgeValuePower: safeBs.wetEdgeValuePower ?? 1.0,
    sizeSensor: mapSensorToNative(safeBs.sizeSensor),
    opacitySensor: mapSensorToNative(safeBs.opacitySensor),
    densitySensor: mapSensorToNative(safeBs.densitySensor),
    thicknessSensor: mapSensorToNative(safeBs.thicknessSensor),
    intervalSensor: mapSensorToNative(safeBs.intervalSensor),
    textureDensitySensor: mapSensorToNative(safeBs.textureDensitySensor),
    dynamics: mapDynamicsToNative(safeBs.dynamics),
    spray: mapSprayToNative(safeBs.spray),
    taper: taperPayload,
    dualBrush: Boolean(dualPayload),
    dualBrushConfig: dualPayload,
    // Phase 5: Natural Paint, Pigment Mixing, Bristle Ribbon, Continuous Ribbon & Impasto
    presetKey: safeBs.preset ?? safeBs.brushName ?? null,
    renderMode: safeBs.renderMode ?? 'stamp',
    isRibbon: Boolean(safeBs.isRibbon),
    ribbonRepeatMode: safeBs.ribbonRepeatMode ?? 'repeat',
    colorMixing: Boolean(safeBs.colorMixing),
    perceptualMixing: safeBs.perceptualMixing !== false,
    amountOfPaint: safeBs.amountOfPaint ?? 0.75,
    densityOfPaint: safeBs.densityOfPaint ?? 0.85,
    colorStretch: safeBs.colorStretch ?? 0.5,
    mixGroundColor: Boolean(safeBs.mixGroundColor),
    useBlur: Boolean(safeBs.useBlur),
    blurStrength: safeBs.blurStrength ?? 0.35,
    mixingMode: safeBs.mixingMode ?? 'blend',
    amountOfPaintSensor: mapSensorToNative(safeBs.amountOfPaintSensor),
    densityOfPaintSensor: mapSensorToNative(safeBs.densityOfPaintSensor),
    colorStretchSensor: mapSensorToNative(safeBs.colorStretchSensor),
    bristleSplaySensor: mapSensorToNative(safeBs.bristleSplaySensor),
    paintLoadSensor: mapSensorToNative(safeBs.paintLoadSensor),
    grainPenetrationSensor: mapSensorToNative(safeBs.grainPenetrationSensor),
    dualSurfaceTextureId: safeBs.dualSurfaceTextureId ?? null,
    dualGrainDepth: safeBs.dualGrainDepth ?? 0.0,
    bristle: safeBs.bristle
      ? {
          profile: safeBs.bristle.profile ?? 'filbert',
          count: Math.max(4, Math.min(64, Math.round(safeBs.bristle.count ?? 24))),
          clumping: safeBs.bristle.clumping ?? 0.35,
          stiffness: safeBs.bristle.stiffness ?? 0.55,
          length: safeBs.bristle.length ?? 1.0,
          splay: safeBs.bristle.splay ?? 0.4,
          irregularity: safeBs.bristle.irregularity ?? 0.3,
          edgeRidge: safeBs.bristle.edgeRidge ?? 0.45,
        }
      : null,
    naturalPaint: safeBs.naturalPaint
      ? {
          enabled: Boolean(safeBs.naturalPaint.enabled),
          spatialMixing: safeBs.naturalPaint.spatialMixing !== false,
          pigmentMixingStrength: safeBs.naturalPaint.pigmentMixingStrength ?? 0.85,
          paintLoad: safeBs.naturalPaint.paintLoad ?? 0.85,
          depletionRate: safeBs.naturalPaint.depletionRate ?? 0.25,
          wetness: safeBs.naturalPaint.wetness ?? 0.45,
          viscosity: safeBs.naturalPaint.viscosity ?? 0.5,
          autoClean: safeBs.naturalPaint.autoClean !== false,
          chargePerPressure: safeBs.naturalPaint.chargePerPressure ?? 0.5,
          dryBrush: safeBs.naturalPaint.dryBrush ?? 0.0,
          granulation: safeBs.naturalPaint.granulation ?? 0.0,
          penetrationCurve:
            typeof safeBs.naturalPaint.penetrationCurve === 'number' &&
            Number.isFinite(safeBs.naturalPaint.penetrationCurve)
              ? safeBs.naturalPaint.penetrationCurve
              : Array.isArray(safeBs.naturalPaint.penetrationCurve) &&
                  safeBs.naturalPaint.penetrationCurve.length > 0
                ? (() => {
                    const pts = safeBs.naturalPaint.penetrationCurve as [number, number][];
                    const mid = pts[Math.floor(pts.length / 2)];
                    const my = Array.isArray(mid) && typeof mid[1] === 'number' ? mid[1] : 0.5;
                    const clampedY = Math.max(0.05, Math.min(0.95, my));
                    return Math.max(0.25, Math.min(4.0, Math.log(clampedY) / Math.log(0.5)));
                  })()
                : 1.0,
        }
      : null,
    impasto: safeBs.impasto
      ? {
          enabled: Boolean(safeBs.impasto.enabled),
          depth: safeBs.impasto.depth ?? 0.72,
          bristleRelief: safeBs.impasto.bristleRelief ?? 0.78,
          gloss: safeBs.impasto.gloss ?? 0.42,
          reliefContrast: safeBs.impasto.reliefContrast ?? 1.15,
          lightAzimuth: safeBs.impasto.lightAzimuth ?? 315,
          lightElevation: safeBs.impasto.lightElevation ?? 50,
        }
      : null,
  };
}

/**
 * Uploads any uncached custom tips / sub-tips / dual-tips / paper texture once by content hash,
 * then syncs the full CSP-compatible `NativeBrushConfig` to `ink-engine`.
 */
export async function syncNativeFullBrushConfig(
  tool: ToolType,
  bs: BrushSettings | Partial<BrushSettings> | null | undefined,
  primaryColor: string,
  secondaryColor: string,
  isBgEraser = false
): Promise<void> {
  if (!cachedNativeActive || !isTauriDesktopRuntime() || !bs) return;
  try {
    const payload = await buildNativeBrushConfigPayload(
      tool,
      bs,
      primaryColor,
      secondaryColor,
      isBgEraser
    );
    await setNativeFullBrush(payload);
  } catch {
    // Ignore transient IPC / malformed brush config errors during sync
  }
}

export function setNativePolicy(policy: NativeInteractionPolicy): Promise<void> {
  return invokeFireAndForget('native_engine_set_policy', { policy });
}

export function clearNativeCanvas(): Promise<void> {
  return invokeFireAndForget('native_engine_clear_canvas');
}

export async function getNativeDiagnostics(): Promise<NativeEngineDiagnostics | null> {
  if (!cachedNativeActive || !isTauriDesktopRuntime()) return null;
  try {
    return await invokeNative<NativeEngineDiagnostics>('native_engine_get_diagnostics');
  } catch {
    return null;
  }
}

// ---------------------------------------------------------------------------
// Phase 2: Document Lifecycle & Zero-Copy File I/O Commands
// ---------------------------------------------------------------------------

export async function createNativeDocument(params: {
  docId: string;
  name: string;
  dimensions: CanvasDimensions;
  colorMode?: CanvasColorMode;
  backgroundHex?: string;
  defaultToneFrequency?: number;
}): Promise<NativeDocumentMetaSnapshot | null> {
  if (!cachedNativeActive || !isTauriDesktopRuntime() || !params || typeof params !== 'object') {
    return null;
  }
  try {
    const safeDims: CanvasDimensions = {
      width:
        typeof params.dimensions?.width === 'number' &&
        Number.isFinite(params.dimensions.width) &&
        params.dimensions.width >= 1
          ? Math.round(params.dimensions.width)
          : 1920,
      height:
        typeof params.dimensions?.height === 'number' &&
        Number.isFinite(params.dimensions.height) &&
        params.dimensions.height >= 1
          ? Math.round(params.dimensions.height)
          : 1080,
      dpi:
        typeof params.dimensions?.dpi === 'number' &&
        Number.isFinite(params.dimensions.dpi) &&
        params.dimensions.dpi >= 1
          ? Math.round(params.dimensions.dpi)
          : 300,
    };
    const snap = await invokeNative<NativeDocumentMetaSnapshot | null | undefined>(
      'native_engine_create_document',
      {
        docId: typeof params.docId === 'string' && params.docId ? params.docId : `doc-${Date.now()}`,
        name: typeof params.name === 'string' && params.name ? params.name : 'Untitled*',
        dimensions: safeDims,
        colorMode: params.colorMode ?? 'color',
        backgroundHex:
          typeof params.backgroundHex === 'string' && params.backgroundHex.trim().length > 0
            ? params.backgroundHex
            : '#ffffff',
        defaultToneFrequency:
          typeof params.defaultToneFrequency === 'number' &&
          Number.isFinite(params.defaultToneFrequency)
            ? params.defaultToneFrequency
            : 60,
      }
    );
    if (!snap || typeof snap !== 'object') return null;
    return {
      ...snap,
      layers: Array.isArray(snap.layers) ? snap.layers : [],
    };
  } catch {
    return null;
  }
}

export async function openNativeDocumentFromPath(
  docId: string,
  path: string
): Promise<NativeOpenDocumentResult> {
  return invokeNative<NativeOpenDocumentResult>('native_engine_open_file', {
    docId,
    path,
  });
}

export async function openNativeDocumentBytes(
  docId: string,
  fileName: string,
  bytes: Uint8Array
): Promise<NativeOpenDocumentResult> {
  const invoke = await getTauriInvoke();
  const payload =
    bytes.byteOffset === 0 && bytes.byteLength === bytes.buffer.byteLength
      ? bytes
      : bytes.slice();
  return invoke<NativeOpenDocumentResult>('native_engine_open_file_bytes', payload, {
    headers: {
      'x-doc-id': encodeURIComponent(docId),
      'x-file-name': encodeURIComponent(fileName),
    },
  });
}

export async function saveNativeInkDocument(
  docId: string,
  path: string
): Promise<NativeSaveInkResult> {
  return invokeNative<NativeSaveInkResult>('native_engine_save_ink', {
    docId,
    path,
  });
}

export async function saveNativeInkDocumentWithDialog(
  docId: string,
  suggestedName: string,
  initialDir?: string
): Promise<NativeSaveInkResult> {
  return invokeNative<NativeSaveInkResult>('native_engine_save_ink_with_dialog', {
    docId,
    suggestedName,
    initialDir: initialDir ?? null,
  });
}

export async function switchNativeDocument(
  docId: string
): Promise<NativeDocumentMetaSnapshot | null> {
  if (!cachedNativeActive || !isTauriDesktopRuntime()) return null;
  try {
    return await invokeNative<NativeDocumentMetaSnapshot>('native_engine_switch_document', {
      docId,
    });
  } catch {
    return null;
  }
}

export async function closeNativeDocument(docId: string): Promise<boolean> {
  if (!cachedNativeActive || !isTauriDesktopRuntime()) return false;
  try {
    return await invokeNative<boolean>('native_engine_close_document', { docId });
  } catch {
    return false;
  }
}

export async function getNativeDocumentState(
  docId?: string
): Promise<NativeDocumentMetaSnapshot | null> {
  if (!cachedNativeActive || !isTauriDesktopRuntime()) return null;
  try {
    return await invokeNative<NativeDocumentMetaSnapshot | null>(
      'native_engine_get_document_state',
      { docId: docId ?? null }
    );
  } catch {
    return null;
  }
}

// ---------------------------------------------------------------------------
// Phase 2: Layer Tree CRUD, Properties, Masks & Dirty-Rect Raster Ingestion
// ---------------------------------------------------------------------------

export async function addNativeLayer(
  docId: string,
  layer: LayerItem,
  insertIndex?: number,
  recordHistory: boolean = true
): Promise<NativeDocumentMetaSnapshot | null> {
  if (!cachedNativeActive || !isTauriDesktopRuntime()) return null;
  return invokeNative<NativeDocumentMetaSnapshot>('native_engine_add_layer', {
    docId,
    layer: toNativeLayerNodeMeta(layer),
    insertIndex: insertIndex ?? null,
    recordHistory,
  });
}

export async function deleteNativeLayer(
  docId: string,
  layerId: string,
  recordHistory: boolean = true
): Promise<NativeDocumentMetaSnapshot | null> {
  if (!cachedNativeActive || !isTauriDesktopRuntime()) return null;
  return invokeNative<NativeDocumentMetaSnapshot>('native_engine_delete_layer', {
    docId,
    layerId,
    recordHistory,
  });
}

export async function duplicateNativeLayer(
  docId: string,
  sourceLayerId: string,
  newLayerId: string,
  recordHistory: boolean = true
): Promise<NativeDocumentMetaSnapshot | null> {
  if (!cachedNativeActive || !isTauriDesktopRuntime()) return null;
  return invokeNative<NativeDocumentMetaSnapshot>('native_engine_duplicate_layer', {
    docId,
    sourceLayerId,
    newLayerId,
    recordHistory,
  });
}

export async function reorderNativeLayers(
  docId: string,
  orderedIds: string[],
  parentOverrides?: Record<string, string | null>,
  recordHistory: boolean = true
): Promise<NativeDocumentMetaSnapshot | null> {
  if (!cachedNativeActive || !isTauriDesktopRuntime()) return null;
  return invokeNative<NativeDocumentMetaSnapshot>('native_engine_reorder_layers', {
    docId,
    orderedIds,
    parentOverrides: parentOverrides ?? null,
    recordHistory,
  });
}

export async function updateNativeLayer(
  docId: string,
  layerId: string,
  patch: NativeLayerPropsPatch
): Promise<NativeDocumentMetaSnapshot | null> {
  if (!cachedNativeActive || !isTauriDesktopRuntime()) return null;
  return invokeNative<NativeDocumentMetaSnapshot>('native_engine_update_layer', {
    docId,
    layerId,
    patch,
  });
}

export async function syncNativeLayers(
  docId: string,
  layers: LayerItem[],
  activeLayerId?: string | null,
  options?: { recordHistory?: boolean; historyLabel?: string }
): Promise<NativeDocumentMetaSnapshot | null> {
  if (!cachedNativeActive || !isTauriDesktopRuntime()) return null;
  return invokeNative<NativeDocumentMetaSnapshot>('native_engine_sync_layers', {
    docId,
    layers: layers.map(toNativeLayerNodeMeta),
    activeLayerId: activeLayerId ?? null,
    recordHistory: options?.recordHistory ?? false,
    historyLabel: options?.historyLabel ?? null,
  });
}

export function setNativeActiveLayer(
  docId: string,
  layerId: string | null
): Promise<void> {
  if (!cachedNativeActive || !isTauriDesktopRuntime() || !docId) return Promise.resolve();
  return invokeFireAndForget('native_engine_set_active_layer', {
    docId,
    layerId: layerId ?? null,
  });
}

export async function syncNativeDocumentMeta(
  docId: string,
  meta: {
    name?: string;
    perspectiveRuler?: unknown;
    straightRuler?: unknown;
    animationTimeline?: unknown;
    timelapse?: unknown;
    workTimeMs?: number;
  }
): Promise<void> {
  if (!cachedNativeActive || !isTauriDesktopRuntime() || !docId) return;
  await invokeNative<void>('native_engine_sync_document_meta', {
    docId,
    name: meta.name ?? null,
    perspectiveRuler: meta.perspectiveRuler === undefined ? null : meta.perspectiveRuler,
    straightRuler: meta.straightRuler === undefined ? null : meta.straightRuler,
    animationTimeline: meta.animationTimeline === undefined ? null : meta.animationTimeline,
    timelapse: meta.timelapse === undefined ? null : meta.timelapse,
    workTimeMs: typeof meta.workTimeMs === 'number' && Number.isFinite(meta.workTimeMs)
      ? Math.max(0, Math.round(meta.workTimeMs))
      : null,
  });
}

export async function clearNativeLayer(
  docId: string,
  layerId: string,
  recordHistory: boolean = true
): Promise<NativeDocumentMetaSnapshot | null> {
  if (!cachedNativeActive || !isTauriDesktopRuntime()) return null;
  return invokeNative<NativeDocumentMetaSnapshot>('native_engine_clear_layer', {
    docId,
    layerId,
    recordHistory,
  });
}

export async function mergeNativeDown(
  docId: string,
  srcLayerId: string
): Promise<NativeDocumentMetaSnapshot | null> {
  if (!cachedNativeActive || !isTauriDesktopRuntime()) return null;
  return invokeNative<NativeDocumentMetaSnapshot>('native_engine_merge_down', {
    docId,
    srcLayerId,
  });
}

export async function mergeNativeFolder(
  docId: string,
  folderId: string,
  newLayerId: string
): Promise<NativeDocumentMetaSnapshot | null> {
  if (!cachedNativeActive || !isTauriDesktopRuntime()) return null;
  return invokeNative<NativeDocumentMetaSnapshot>('native_engine_merge_folder', {
    docId,
    folderId,
    newLayerId,
  });
}

export async function addNativeLayerMask(
  docId: string,
  layerId: string,
  defaultValue: number = 255,
  recordHistory: boolean = true
): Promise<NativeDocumentMetaSnapshot | null> {
  if (!cachedNativeActive || !isTauriDesktopRuntime()) return null;
  return invokeNative<NativeDocumentMetaSnapshot>('native_engine_add_mask', {
    docId,
    layerId,
    defaultValue,
    recordHistory,
  });
}

export async function removeNativeLayerMask(
  docId: string,
  layerId: string,
  applyToRaster: boolean = false,
  recordHistory: boolean = true
): Promise<NativeDocumentMetaSnapshot | null> {
  if (!cachedNativeActive || !isTauriDesktopRuntime()) return null;
  return invokeNative<NativeDocumentMetaSnapshot>('native_engine_remove_mask', {
    docId,
    layerId,
    applyToRaster,
    recordHistory,
  });
}

export async function resizeNativeCanvas(params: {
  docId: string;
  dimensions: CanvasDimensions;
  offsetX?: number;
  offsetY?: number;
  scaleContent?: boolean;
  bgHex?: string;
  recordHistory?: boolean;
}): Promise<NativeDocumentMetaSnapshot | null> {
  if (!cachedNativeActive || !isTauriDesktopRuntime()) return null;
  return invokeNative<NativeDocumentMetaSnapshot>('native_engine_resize_canvas', {
    docId: params.docId,
    dimensions: params.dimensions,
    offsetX: Math.round(params.offsetX ?? 0),
    offsetY: Math.round(params.offsetY ?? 0),
    scaleContent: Boolean(params.scaleContent),
    bgHex: params.bgHex ?? '#ffffff',
    recordHistory: params.recordHistory ?? true,
  });
}

/**
 * Raw binary IPC ingestion of a dirty rectangle (RGBA8 or 8-bit mask) into Rust's sparse
 * tile grid — used when UI-edited layers (text, speech balloons, 3D bakes, image paste) commit.
 */
export async function ingestNativeDirtyRect(params: {
  docId: string;
  layerId: string;
  x: number;
  y: number;
  width: number;
  height: number;
  bytes: Uint8Array;
  isMask?: boolean;
  recordHistory?: boolean;
  actionType?: string;
  label?: string;
  peerId?: string;
  strokeId?: string;
}): Promise<NativeDocumentMetaSnapshot | null> {
  if (!cachedNativeActive || !isTauriDesktopRuntime()) return null;
  const invoke = await getTauriInvoke();
  const payload =
    params.bytes.byteOffset === 0 && params.bytes.byteLength === params.bytes.buffer.byteLength
      ? params.bytes
      : params.bytes.slice();
  const headers: Record<string, string> = {
    'x-doc-id': encodeURIComponent(params.docId),
    'x-layer-id': encodeURIComponent(params.layerId),
    'x-x': String(Math.round(params.x)),
    'x-y': String(Math.round(params.y)),
    'x-width': String(Math.max(1, Math.round(params.width))),
    'x-height': String(Math.max(1, Math.round(params.height))),
    'x-is-mask': params.isMask ? '1' : '0',
    'x-record-history': params.recordHistory === false ? '0' : '1',
    'x-action-type': encodeURIComponent(params.actionType ?? 'raster'),
    'x-label': encodeURIComponent(params.label ?? 'Edit Layer'),
  };
  if (params.peerId) headers['x-peer-id'] = encodeURIComponent(params.peerId);
  if (params.strokeId) headers['x-stroke-id'] = encodeURIComponent(params.strokeId);
  return invoke<NativeDocumentMetaSnapshot>('native_engine_ingest_dirty_rect', payload, {
    headers,
  });
}

// ---------------------------------------------------------------------------
// Phase 2: Rust CoW Undo / Redo & Collaborative Selective Undo Commands
// ---------------------------------------------------------------------------

export async function nativeUndo(docId: string): Promise<NativeHistoryMutationResult | null> {
  if (!cachedNativeActive || !isTauriDesktopRuntime()) return null;
  return invokeNative<NativeHistoryMutationResult>('native_engine_undo', { docId });
}

export async function nativeRedo(docId: string): Promise<NativeHistoryMutationResult | null> {
  if (!cachedNativeActive || !isTauriDesktopRuntime()) return null;
  return invokeNative<NativeHistoryMutationResult>('native_engine_redo', { docId });
}

export async function nativeJumpHistory(
  docId: string,
  targetIndex: number
): Promise<NativeHistoryMutationResult | null> {
  if (!cachedNativeActive || !isTauriDesktopRuntime()) return null;
  return invokeNative<NativeHistoryMutationResult>('native_engine_jump_history', {
    docId,
    targetIndex,
  });
}

export async function nativeSelectiveUndo(
  docId: string,
  peerId?: string | number | null,
  strokeId?: string | null
): Promise<NativeHistoryMutationResult | null> {
  if (!cachedNativeActive || !isTauriDesktopRuntime()) return null;
  return invokeNative<NativeHistoryMutationResult>('native_engine_selective_undo', {
    docId,
    peerId: peerId !== undefined && peerId !== null ? String(peerId) : null,
    strokeId: strokeId ?? null,
  });
}

export async function nativeSelectiveRedo(
  docId: string,
  peerId?: string | number | null
): Promise<NativeHistoryMutationResult | null> {
  if (!cachedNativeActive || !isTauriDesktopRuntime()) return null;
  return invokeNative<NativeHistoryMutationResult>('native_engine_selective_redo', {
    docId,
    peerId: peerId !== undefined && peerId !== null ? String(peerId) : null,
  });
}

export async function nativePushHistoryMeta(params: {
  docId: string;
  actionType: string;
  label: string;
  layerId?: string | null;
  documentStateDelta?: unknown;
  coalesceKey?: string;
}): Promise<NativeHistoryStateSnapshot | null> {
  if (!cachedNativeActive || !isTauriDesktopRuntime()) return null;
  return invokeNative<NativeHistoryStateSnapshot>('native_engine_push_history_meta', {
    docId: params.docId,
    actionType: params.actionType,
    label: params.label,
    layerId: params.layerId ?? null,
    documentStateDelta: params.documentStateDelta ?? null,
    coalesceKey: params.coalesceKey ?? null,
  });
}

export async function nativeGetHistory(docId: string): Promise<NativeHistoryStateSnapshot | null> {
  if (!cachedNativeActive || !isTauriDesktopRuntime()) return null;
  try {
    return await invokeNative<NativeHistoryStateSnapshot>('native_engine_get_history', { docId });
  } catch {
    return null;
  }
}

export async function nativeResetHistory(
  docId: string,
  label?: string
): Promise<NativeHistoryStateSnapshot | null> {
  if (!cachedNativeActive || !isTauriDesktopRuntime()) return null;
  try {
    return await invokeNative<NativeHistoryStateSnapshot>('native_engine_reset_history', {
      docId,
      label: label ?? null,
    });
  } catch {
    return null;
  }
}

// ---------------------------------------------------------------------------
// Phase 2: Tiered Memory, Async Thumbnails, Timelapse & Crash Recovery
// ---------------------------------------------------------------------------

export async function getNativeMemoryStats(): Promise<NativeMemoryStats | null> {
  if (!cachedNativeActive || !isTauriDesktopRuntime()) return null;
  try {
    return await invokeNative<NativeMemoryStats>('native_engine_get_memory_stats');
  } catch {
    return null;
  }
}

export async function setNativeMemoryBudget(
  input: NativeMemoryBudgetInput
): Promise<NativeMemoryStats | null> {
  if (!cachedNativeActive || !isTauriDesktopRuntime()) return null;
  try {
    return await invokeNative<NativeMemoryStats>('native_engine_set_memory_budget', { input });
  } catch {
    return null;
  }
}

export async function purgeNativeMemory(): Promise<NativeMemoryStats | null> {
  if (!cachedNativeActive || !isTauriDesktopRuntime()) return null;
  try {
    return await invokeNative<NativeMemoryStats>('native_engine_purge_memory');
  } catch {
    return null;
  }
}

export function requestNativeThumbnails(docId: string, layerIds?: string[]): Promise<void> {
  return invokeFireAndForget('native_engine_request_thumbnails', {
    docId,
    layerIds: layerIds ?? null,
  });
}

export async function captureNativeTimelapseFrame(params: {
  docId: string;
  sessionId: string;
  frameIndex: number;
  maxDim?: number;
  captureArea?: string;
}): Promise<NativeTimelapseCaptureResult | null> {
  if (!cachedNativeActive || !isTauriDesktopRuntime()) return null;
  return invokeNative<NativeTimelapseCaptureResult>('native_engine_capture_timelapse_frame', {
    docId: params.docId,
    sessionId: params.sessionId,
    frameIndex: params.frameIndex,
    maxDim: params.maxDim ?? 1920,
    captureArea: params.captureArea ?? null,
  });
}

export async function nativeRecoveryCheckpoint(
  docId: string,
  sessionId: string,
  manifestJson?: string
): Promise<NativeRecoveryCheckpointResult | null> {
  if (!cachedNativeActive || !isTauriDesktopRuntime()) return null;
  return invokeNative<NativeRecoveryCheckpointResult>('native_engine_recovery_checkpoint', {
    docId,
    sessionId,
    manifestJson: manifestJson ?? null,
  });
}

export async function nativeRecoveryRestore(
  sessionId: string,
  docId: string
): Promise<NativeDocumentMetaSnapshot> {
  return invokeNative<NativeDocumentMetaSnapshot>('native_engine_recovery_restore', {
    sessionId,
    docId,
  });
}

// ---------------------------------------------------------------------------
// Event Subscriptions (Rust -> React)
// ---------------------------------------------------------------------------

function subscribeTauriEvent<T>(eventName: string, handler: (payload: T) => void): () => void {
  if (!isTauriDesktopRuntime()) return () => {};
  let unlistenFn: (() => void) | null = null;
  let disposed = false;

  void getTauriListen()
    .then((listen) =>
      listen<T>(eventName, (event) => {
        if (!disposed) {
          handler(event.payload);
        }
      })
    )
    .then((unlisten) => {
      if (disposed) {
        unlisten();
      } else {
        unlistenFn = unlisten;
      }
    })
    .catch(() => {
      // Ignore outside Tauri
    });

  return () => {
    disposed = true;
    unlistenFn?.();
    unlistenFn = null;
  };
}

export function subscribeNativeCamera(cb: (ev: NativeCameraEvent) => void): () => void {
  return subscribeTauriEvent<NativeCameraEvent>(EVENT_CAMERA, cb);
}

export function subscribeNativeDiagnostics(cb: (diag: NativeEngineDiagnostics) => void): () => void {
  return subscribeTauriEvent<NativeEngineDiagnostics>(EVENT_DIAGNOSTICS, cb);
}

export function subscribeNativePointerStat(
  cb: (stat: NativePointerStatEvent) => void
): () => void {
  return subscribeTauriEvent<NativePointerStatEvent>(EVENT_POINTER_STAT, cb);
}

export function subscribeNativeHistory(cb: (ev: NativeHistoryEvent) => void): () => void {
  return subscribeTauriEvent<NativeHistoryEvent>(EVENT_HISTORY, cb);
}

export function subscribeNativeThumbnails(cb: (ev: NativeThumbnailsEvent) => void): () => void {
  return subscribeTauriEvent<NativeThumbnailsEvent>(EVENT_THUMBNAILS, cb);
}

export function subscribeNativeStrokeCommitted(
  cb: (ev: NativeStrokeCommittedEvent) => void
): () => void {
  return subscribeTauriEvent<NativeStrokeCommittedEvent>(EVENT_STROKE_COMMITTED, cb);
}

export function subscribeNativeViewportInvalidated(cb: () => void): () => void {
  return subscribeTauriEvent<unknown>(EVENT_VIEWPORT_INVALIDATED, () => cb());
}

// ---------------------------------------------------------------------------
// Phase 6: Native Selection, GPU Liquify, Fill/Eyedropper, 5-Mode Transform,
// Retouch, Gradients, Shapes, Live Filters/Tonal, Vector, Collab & Zero-Canvas IO
// ---------------------------------------------------------------------------

export interface NativeRectI32 {
  x: number;
  y: number;
  width: number;
  height: number;
}

export type NativeSelectionCombineMode = 'replace' | 'add' | 'subtract' | 'intersect';
export type NativeWandReferMode = 'active' | 'all' | 'reference';

export interface NativeSelectionMetaSnapshot {
  active: boolean;
  bounds: NativeRectI32;
  version: number;
  hasFloating: boolean;
  floatingX?: number;
  floatingY?: number;
  floatingWidth?: number;
  floatingHeight?: number;
  floatingLayerId?: string;
}

export interface NativeSelectionChangedEvent {
  docId: string;
  selection: NativeSelectionMetaSnapshot;
}

export interface NativeSelectionFillResult {
  modified: boolean;
  dirtyRect: NativeRectI32;
}

export function subscribeNativeSelectionChanged(
  cb: (ev: NativeSelectionChangedEvent) => void
): () => void {
  return subscribeTauriEvent<NativeSelectionChangedEvent>(EVENT_SELECTION_CHANGED, cb);
}

export async function nativeSelectRect(params: {
  docId?: string | null;
  x: number;
  y: number;
  width: number;
  height: number;
  mode?: NativeSelectionCombineMode;
}): Promise<NativeSelectionMetaSnapshot | null> {
  if (!isTauriDesktopRuntime()) return null;
  return invokeNative<NativeSelectionMetaSnapshot>('native_select_rect', {
    docId: params.docId ?? null,
    x: Math.round(params.x),
    y: Math.round(params.y),
    width: Math.max(0, Math.round(params.width)),
    height: Math.max(0, Math.round(params.height)),
    mode: params.mode ?? 'replace',
  });
}

export async function nativeSelectLasso(params: {
  docId?: string | null;
  points: [number, number][];
  antiAlias?: boolean;
  mode?: NativeSelectionCombineMode;
}): Promise<NativeSelectionMetaSnapshot | null> {
  if (!isTauriDesktopRuntime()) return null;
  return invokeNative<NativeSelectionMetaSnapshot>('native_select_lasso', {
    docId: params.docId ?? null,
    points: params.points,
    antiAlias: params.antiAlias ?? true,
    mode: params.mode ?? 'replace',
  });
}

export async function nativeSelectMagicWand(params: {
  docId?: string | null;
  x: number;
  y: number;
  tolerance?: number;
  contiguous?: boolean;
  antiAlias?: boolean;
  referMode?: NativeWandReferMode;
  mode?: NativeSelectionCombineMode;
}): Promise<NativeSelectionMetaSnapshot | null> {
  if (!isTauriDesktopRuntime()) return null;
  return invokeNative<NativeSelectionMetaSnapshot>('native_select_magic_wand', {
    docId: params.docId ?? null,
    x: Math.round(params.x),
    y: Math.round(params.y),
    tolerance: params.tolerance ?? 32,
    contiguous: params.contiguous ?? true,
    antiAlias: params.antiAlias ?? true,
    referMode: params.referMode ?? 'active',
    mode: params.mode ?? 'replace',
  });
}

export async function nativeSelectAll(
  docId?: string | null
): Promise<NativeSelectionMetaSnapshot | null> {
  if (!isTauriDesktopRuntime()) return null;
  return invokeNative<NativeSelectionMetaSnapshot>('native_select_all', { docId: docId ?? null });
}

export async function nativeDeselect(
  docId?: string | null
): Promise<NativeSelectionMetaSnapshot | null> {
  if (!isTauriDesktopRuntime()) return null;
  return invokeNative<NativeSelectionMetaSnapshot>('native_deselect', { docId: docId ?? null });
}

export async function nativeSelectionInvert(
  docId?: string | null
): Promise<NativeSelectionMetaSnapshot | null> {
  if (!isTauriDesktopRuntime()) return null;
  return invokeNative<NativeSelectionMetaSnapshot>('native_selection_invert', {
    docId: docId ?? null,
  });
}

export async function nativeSelectionExpand(
  pixels: number,
  docId?: string | null
): Promise<NativeSelectionMetaSnapshot | null> {
  if (!isTauriDesktopRuntime()) return null;
  return invokeNative<NativeSelectionMetaSnapshot>('native_selection_expand', {
    docId: docId ?? null,
    pixels: Math.round(pixels),
  });
}

export async function nativeSelectionFeather(
  radius: number,
  docId?: string | null
): Promise<NativeSelectionMetaSnapshot | null> {
  if (!isTauriDesktopRuntime()) return null;
  return invokeNative<NativeSelectionMetaSnapshot>('native_selection_feather', {
    docId: docId ?? null,
    radius,
  });
}

export async function nativeSelectionClearPixels(
  layerId?: string | null,
  docId?: string | null
): Promise<NativeSelectionFillResult | null> {
  if (!isTauriDesktopRuntime()) return null;
  return invokeNative<NativeSelectionFillResult>('native_selection_clear_pixels', {
    docId: docId ?? null,
    layerId: layerId ?? null,
  });
}

export async function nativeSelectionClearOutside(
  layerId?: string | null,
  docId?: string | null
): Promise<NativeSelectionFillResult | null> {
  if (!isTauriDesktopRuntime()) return null;
  return invokeNative<NativeSelectionFillResult>('native_selection_clear_outside', {
    docId: docId ?? null,
    layerId: layerId ?? null,
  });
}

export async function nativeSelectionFillColor(params: {
  color: string;
  opacity?: number;
  layerId?: string | null;
  docId?: string | null;
}): Promise<NativeSelectionFillResult | null> {
  if (!isTauriDesktopRuntime()) return null;
  return invokeNative<NativeSelectionFillResult>('native_selection_fill_color', {
    docId: params.docId ?? null,
    layerId: params.layerId ?? null,
    color: params.color,
    opacity: params.opacity ?? 1.0,
  });
}

export async function nativeSelectionCopy(
  layerId?: string | null,
  docId?: string | null
): Promise<boolean> {
  if (!isTauriDesktopRuntime()) return false;
  return invokeNative<boolean>('native_selection_copy', {
    docId: docId ?? null,
    layerId: layerId ?? null,
  });
}

export async function nativeSelectionCut(
  layerId?: string | null,
  docId?: string | null
): Promise<boolean> {
  if (!isTauriDesktopRuntime()) return false;
  return invokeNative<boolean>('native_selection_cut', {
    docId: docId ?? null,
    layerId: layerId ?? null,
  });
}

export async function nativeSelectionPaste(
  newLayerId: string,
  docId?: string | null
): Promise<NativeDocumentMetaSnapshot | null> {
  if (!isTauriDesktopRuntime()) return null;
  return invokeNative<NativeDocumentMetaSnapshot | null>('native_selection_paste', {
    docId: docId ?? null,
    newLayerId,
  });
}

export async function nativeSelectionMoveToNewLayer(
  newLayerId: string,
  srcLayerId?: string | null,
  docId?: string | null
): Promise<NativeDocumentMetaSnapshot | null> {
  if (!isTauriDesktopRuntime()) return null;
  return invokeNative<NativeDocumentMetaSnapshot | null>('native_selection_move_to_new_layer', {
    docId: docId ?? null,
    srcLayerId: srcLayerId ?? null,
    newLayerId,
  });
}

export async function nativeSelectionLiftFloating(
  layerId?: string | null,
  docId?: string | null
): Promise<NativeSelectionMetaSnapshot | null> {
  if (!isTauriDesktopRuntime()) return null;
  return invokeNative<NativeSelectionMetaSnapshot>('native_selection_lift_floating', {
    docId: docId ?? null,
    layerId: layerId ?? null,
  });
}

export async function nativeSelectionMoveFloating(
  x: number,
  y: number,
  docId?: string | null
): Promise<NativeSelectionMetaSnapshot | null> {
  if (!isTauriDesktopRuntime()) return null;
  return invokeNative<NativeSelectionMetaSnapshot>('native_selection_move_floating', {
    docId: docId ?? null,
    x: Math.round(x),
    y: Math.round(y),
  });
}

export async function nativeSelectionCommitFloating(
  docId?: string | null
): Promise<NativeSelectionMetaSnapshot | null> {
  if (!isTauriDesktopRuntime()) return null;
  return invokeNative<NativeSelectionMetaSnapshot>('native_selection_commit_floating', {
    docId: docId ?? null,
  });
}

export async function nativeSelectionGetState(
  docId?: string | null
): Promise<NativeSelectionMetaSnapshot | null> {
  if (!isTauriDesktopRuntime()) return null;
  return invokeNative<NativeSelectionMetaSnapshot>('native_selection_get_state', {
    docId: docId ?? null,
  });
}

// --- 2. Interactive DX12 GPU Liquify ---

export type NativeLiquifyMode =
  | 'push'
  | 'expand'
  | 'pinch'
  | 'push-left'
  | 'push-right'
  | 'twirl-cw'
  | 'twirl-ccw'
  | 'reconstruct';

export interface NativeLiquifySettings {
  mode: NativeLiquifyMode;
  size: number;
  strength: number;
  hardness: number;
  usePressure: boolean;
  multiLayer?: boolean;
}

export interface NativeLiquifyStepParams {
  fromX: number;
  fromY: number;
  toX: number;
  toY: number;
  pressure: number;
  settings: NativeLiquifySettings;
}

export async function nativeLiquifyBegin(
  multiLayer: boolean = false,
  layerIds?: string[] | null
): Promise<string[]> {
  if (!isTauriDesktopRuntime()) return [];
  return invokeNative<string[]>('native_liquify_begin', {
    multiLayer,
    layerIds: layerIds ?? null,
  });
}

export async function nativeLiquifyStepGpu(
  step: NativeLiquifyStepParams
): Promise<NativeRectI32 | null> {
  if (!isTauriDesktopRuntime()) return null;
  return invokeNative<NativeRectI32>('native_liquify_step_gpu', { step });
}

export async function nativeLiquifyCommit(
  docId?: string | null
): Promise<{ layerIds: string[]; dirtyRect: NativeRectI32 } | null> {
  if (!isTauriDesktopRuntime()) return null;
  return invokeNative<{ layerIds: string[]; dirtyRect: NativeRectI32 }>('native_liquify_commit', {
    docId: docId ?? null,
  });
}

export function nativeLiquifyCancel(): Promise<void> {
  return invokeFireAndForget('native_liquify_cancel');
}

// --- 3. Direct Rust Flood Fill, Lasso Fill, Smart Line Fill & Eyedropper ---

export type NativeFillReferMode = 'refer-all' | 'refer-active' | 'refer-reference';
export type NativeEncloseTarget = 'all-enclosed' | 'unfilled-only';

export interface NativeFillOutcome {
  modified: boolean;
  layerId: string;
  dirtyRect: NativeRectI32;
}

export interface NativePickedColor {
  hex: string;
  r: number;
  g: number;
  b: number;
  a: number;
}

export async function nativeFloodFillDoc(
  params: {
    x: number;
    y: number;
    color: string;
    tolerance?: number;
    closeGap?: number;
    areaScale?: number;
    antiAlias?: boolean;
    opacity?: number;
    referMode?: NativeFillReferMode;
    layerId?: string | null;
  },
  docId?: string | null
): Promise<NativeFillOutcome | null> {
  if (!isTauriDesktopRuntime()) return null;
  return invokeNative<NativeFillOutcome>('native_flood_fill_doc', {
    docId: docId ?? null,
    params: {
      x: Math.round(params.x),
      y: Math.round(params.y),
      color: params.color,
      tolerance: Math.round(params.tolerance ?? 32),
      closeGap: Math.max(0, Math.round(params.closeGap ?? 0)),
      areaScale: Math.round(params.areaScale ?? 0),
      antiAlias: params.antiAlias ?? true,
      opacity: params.opacity ?? 1.0,
      referMode: params.referMode ?? 'refer-all',
      layerId: params.layerId ?? null,
    },
  });
}

export async function nativeLassoFillDoc(
  params: {
    points: [number, number][];
    color: string;
    opacity?: number;
    antiAlias?: boolean;
    layerId?: string | null;
  },
  docId?: string | null
): Promise<NativeFillOutcome | null> {
  if (!isTauriDesktopRuntime()) return null;
  return invokeNative<NativeFillOutcome>('native_lasso_fill_doc', {
    docId: docId ?? null,
    params: {
      points: params.points,
      color: params.color,
      opacity: params.opacity ?? 1.0,
      antiAlias: params.antiAlias ?? true,
      layerId: params.layerId ?? null,
    },
  });
}

export async function nativeEncloseFillDoc(
  params: {
    points: [number, number][];
    color: string;
    tolerance?: number;
    closeGap?: number;
    areaScale?: number;
    antiAlias?: boolean;
    opacity?: number;
    referMode?: NativeFillReferMode;
    encloseTarget?: NativeEncloseTarget;
    layerId?: string | null;
  },
  docId?: string | null
): Promise<NativeFillOutcome | null> {
  if (!isTauriDesktopRuntime()) return null;
  return invokeNative<NativeFillOutcome>('native_enclose_fill_doc', {
    docId: docId ?? null,
    params: {
      points: params.points,
      color: params.color,
      tolerance: Math.round(params.tolerance ?? 32),
      closeGap: Math.max(0, Math.round(params.closeGap ?? 4)),
      areaScale: Math.round(params.areaScale ?? 0),
      antiAlias: params.antiAlias ?? true,
      opacity: params.opacity ?? 1.0,
      referMode: params.referMode ?? 'refer-all',
      encloseTarget: params.encloseTarget ?? 'all-enclosed',
      layerId: params.layerId ?? null,
    },
  });
}

export async function nativePaintUnfilledDoc(
  params: {
    points: [number, number][];
    brushRadius: number;
    color: string;
    tolerance?: number;
    closeGap?: number;
    areaScale?: number;
    antiAlias?: boolean;
    opacity?: number;
    referMode?: NativeFillReferMode;
    layerId?: string | null;
  },
  docId?: string | null
): Promise<NativeFillOutcome | null> {
  if (!isTauriDesktopRuntime()) return null;
  return invokeNative<NativeFillOutcome>('native_paint_unfilled_doc', {
    docId: docId ?? null,
    params: {
      points: params.points,
      brushRadius: params.brushRadius,
      color: params.color,
      tolerance: Math.round(params.tolerance ?? 32),
      closeGap: Math.max(0, Math.round(params.closeGap ?? 4)),
      areaScale: Math.round(params.areaScale ?? 0),
      antiAlias: params.antiAlias ?? true,
      opacity: params.opacity ?? 1.0,
      referMode: params.referMode ?? 'refer-all',
      layerId: params.layerId ?? null,
    },
  });
}

export async function nativePickColor(params: {
  x: number;
  y: number;
  sampleAllLayers?: boolean;
  layerId?: string | null;
  docId?: string | null;
}): Promise<NativePickedColor | null> {
  if (!isTauriDesktopRuntime()) return null;
  return invokeNative<NativePickedColor>('native_pick_color', {
    docId: params.docId ?? null,
    x: Math.round(params.x),
    y: Math.round(params.y),
    sampleAllLayers: params.sampleAllLayers ?? true,
    layerId: params.layerId ?? null,
  });
}

// --- 4. Interactive 5-Mode GPU Transform & Warp ---

export type NativeTransformMode = 'affine' | 'perspective' | 'mesh' | 'puppet' | 'cage';

export interface NativePoint2D {
  x: number;
  y: number;
}

export interface NativeAffineState {
  x: number;
  y: number;
  width: number;
  height: number;
  rotation: number;
  skewX: number;
  skewY: number;
  flipX: boolean;
  flipY: boolean;
}

export interface NativeMeshState {
  cols: number;
  rows: number;
  points: NativePoint2D[];
}

export interface NativePuppetPin {
  id: string;
  restX: number;
  restY: number;
  x: number;
  y: number;
  rotation: number;
  depth: number;
}

export interface NativePuppetState {
  pins: NativePuppetPin[];
  meshVertices: NativePoint2D[];
  meshTriangles: [number, number, number][];
}

export interface NativeCageState {
  restPoints: NativePoint2D[];
  points: NativePoint2D[];
  closed: boolean;
}

export interface NativeTransformSessionSnapshot {
  active: boolean;
  docId: string;
  mode: NativeTransformMode;
  targetLayerIds: string[];
  sourceBounds: NativeRectI32;
  affine: NativeAffineState;
  corners: [NativePoint2D, NativePoint2D, NativePoint2D, NativePoint2D];
  mesh: NativeMeshState;
  puppet: NativePuppetState;
  cage: NativeCageState;
  showMesh: boolean;
}

export interface NativeTransformUpdatePayload {
  mode: NativeTransformMode;
  affine?: NativeAffineState;
  corners?: [NativePoint2D, NativePoint2D, NativePoint2D, NativePoint2D];
  mesh?: NativeMeshState;
  puppetPins?: NativePuppetPin[];
  cage?: NativeCageState;
}

export interface NativeTransformCommitResult {
  modified: boolean;
  layerIds: string[];
  dirtyRect: NativeRectI32;
}

export async function nativeTransformBegin(
  mode: NativeTransformMode,
  layerIds?: string[] | null
): Promise<NativeTransformSessionSnapshot | null> {
  if (!isTauriDesktopRuntime()) return null;
  return invokeNative<NativeTransformSessionSnapshot>('native_transform_begin', {
    mode,
    layerIds: layerIds ?? null,
  });
}

export async function nativeTransformUpdate(
  payload: NativeTransformUpdatePayload
): Promise<NativeTransformSessionSnapshot | null> {
  if (!isTauriDesktopRuntime()) return null;
  return invokeNative<NativeTransformSessionSnapshot>('native_transform_update', { payload });
}

export async function nativeTransformSwitchMode(
  nextMode: NativeTransformMode
): Promise<NativeTransformSessionSnapshot | null> {
  if (!isTauriDesktopRuntime()) return null;
  return invokeNative<NativeTransformSessionSnapshot>('native_transform_switch_mode', {
    nextMode,
  });
}

export async function nativeTransformCommit(
  docId?: string | null
): Promise<NativeTransformCommitResult | null> {
  if (!isTauriDesktopRuntime()) return null;
  return invokeNative<NativeTransformCommitResult>('native_transform_commit', {
    docId: docId ?? null,
  });
}

export function nativeTransformCancel(): Promise<void> {
  return invokeFireAndForget('native_transform_cancel');
}

// --- 5. Direct Rust Retouch ---

export type NativeRetouchKind =
  | 'smudge'
  | 'blur'
  | 'dodge'
  | 'burn'
  | 'sponge'
  | 'clone-stamp'
  | 'heal';

export interface NativeRetouchStepParams {
  x: number;
  y: number;
  pressure: number;
  cloneSource?: [number, number] | null;
  settings: {
    kind: NativeRetouchKind;
    size: number;
    hardness: number;
    strength: number;
    usePressure: boolean;
    smudgeFingerPainting?: boolean;
    fgColor?: string;
    pigmentBlending?: boolean;
    pigmentStrength?: number;
    tonalRange?: 'shadows' | 'midtones' | 'highlights';
    protectTones?: boolean;
    spongeMode?: 'saturate' | 'desaturate';
    cloneAligned?: boolean;
    cloneSampleMode?: 'active' | 'all-visible';
  };
}

export async function nativeRetouchStep(
  params: NativeRetouchStepParams,
  docId?: string | null
): Promise<NativeRectI32 | null> {
  if (!isTauriDesktopRuntime()) return null;
  return invokeNative<NativeRectI32>('native_retouch_step', {
    docId: docId ?? null,
    params,
  });
}

export async function nativeRetouchCommit(
  docId?: string | null
): Promise<{ modified: boolean; layerId: string; dirtyRect: NativeRectI32 } | null> {
  if (!isTauriDesktopRuntime()) return null;
  return invokeNative<{ modified: boolean; layerId: string; dirtyRect: NativeRectI32 }>(
    'native_retouch_commit',
    { docId: docId ?? null }
  );
}

export function nativeRetouchCancel(docId?: string | null): Promise<void> {
  return invokeFireAndForget('native_retouch_cancel', { docId: docId ?? null });
}

// --- 6. Gradients, Shapes & QuickShape ---

export interface NativeGradientParams {
  gradientType: 'linear' | 'radial' | 'conical' | 'diamond' | 'mesh';
  stops: { position: number; color: string; opacity: number }[];
  start: [number, number];
  end: [number, number];
  repeat?: 'clamp' | 'repeat' | 'reflect';
  blendMode?: 'normal' | 'multiply' | 'screen' | 'overlay';
  opacity?: number;
  dither?: boolean;
  reverse?: boolean;
  pigmentBlending?: boolean;
  mesh?: {
    cols: number;
    rows: number;
    x: number;
    y: number;
    width: number;
    height: number;
    rotation: number;
    nodes: { u: number; v: number; color: string; opacity: number }[];
  } | null;
  layerId?: string | null;
}

export async function nativeGradientPreview(
  params: NativeGradientParams,
  docId?: string | null
): Promise<NativeRectI32 | null> {
  if (!isTauriDesktopRuntime()) return null;
  return invokeNative<NativeRectI32>('native_gradient_preview', {
    docId: docId ?? null,
    params,
  });
}

export async function nativeGradientCommit(
  params: NativeGradientParams,
  docId?: string | null
): Promise<{ modified: boolean; layerId: string; dirtyRect: NativeRectI32 } | null> {
  if (!isTauriDesktopRuntime()) return null;
  return invokeNative<{ modified: boolean; layerId: string; dirtyRect: NativeRectI32 }>(
    'native_gradient_commit',
    { docId: docId ?? null, params }
  );
}

export interface NativeShapeParams {
  kind:
    | 'line'
    | 'rectangle'
    | 'rounded-rect'
    | 'ellipse'
    | 'triangle'
    | 'polygon'
    | 'star'
    | 'arrow';
  start: [number, number];
  end: [number, number];
  mode: 'stroke' | 'fill' | 'both';
  strokeColor: string;
  fillColor: string;
  strokeWidth: number;
  opacity?: number;
  dashed?: boolean;
  dashLength?: number;
  dashGap?: number;
  cornerRadius?: number;
  polygonSides?: number;
  starInnerRatio?: number;
  antiAlias?: boolean;
  layerId?: string | null;
}

export async function nativeShapePreview(
  params: NativeShapeParams,
  docId?: string | null
): Promise<NativeRectI32 | null> {
  if (!isTauriDesktopRuntime()) return null;
  return invokeNative<NativeRectI32>('native_shape_preview', {
    docId: docId ?? null,
    params,
  });
}

export async function nativeShapeCommit(
  params: NativeShapeParams,
  docId?: string | null
): Promise<{ modified: boolean; layerId: string; dirtyRect: NativeRectI32 } | null> {
  if (!isTauriDesktopRuntime()) return null;
  return invokeNative<{ modified: boolean; layerId: string; dirtyRect: NativeRectI32 }>(
    'native_shape_commit',
    { docId: docId ?? null, params }
  );
}

export interface NativeQuickShapeResult {
  recognized: boolean;
  kind?: 'line' | 'arc' | 'circle' | 'ellipse' | 'triangle' | 'rectangle';
  snappedPoints: [number, number][];
  closed: boolean;
}

export async function nativeRecognizeQuickShape(
  points: [number, number][]
): Promise<NativeQuickShapeResult | null> {
  if (!isTauriDesktopRuntime()) return null;
  return invokeNative<NativeQuickShapeResult>('native_recognize_quick_shape', { points });
}

export function nativeClearToolPreview(): Promise<void> {
  return invokeFireAndForget('native_clear_tool_preview');
}

// --- 7. Live GPU Filters, Tonal Corrections & Layer Histogram ---

export type NativeFilterSpec =
  | { kind: 'gaussian-blur'; radius: number }
  | { kind: 'motion-blur'; distance: number; angle: number }
  | { kind: 'unsharp-mask'; amount: number; radius: number; threshold: number }
  | { kind: 'film-grain'; intensity: number; size: number; monochrome: boolean; seed: number };

export type NativeTonalSpec =
  | { kind: 'brightness-contrast'; brightness: number; contrast: number }
  | { kind: 'binarization'; threshold: number }
  | { kind: 'hue-saturation'; hue: number; saturation: number; luminosity: number }
  | { kind: 'posterization'; levels: number }
  | {
      kind: 'level-correction';
      inBlack: number;
      inWhite: number;
      gamma: number;
      outBlack: number;
      outWhite: number;
    }
  | { kind: 'reverse-gradient' }
  | {
      kind: 'curves';
      rgb: { x: number; y: number }[];
      r: { x: number; y: number }[];
      g: { x: number; y: number }[];
      b: { x: number; y: number }[];
    }
  | { kind: 'gradient-map'; stops: { position: number; color: string }[] }
  | {
      kind: 'color-balance';
      shadows: [number, number, number];
      midtones: [number, number, number];
      highlights: [number, number, number];
      preserveLuminosity: boolean;
    };

export type NativeImageOpSpec =
  | { category: 'filter'; filter: NativeFilterSpec }
  | { category: 'tonal'; tonal: NativeTonalSpec };

export interface NativeLayerHistogram {
  rgb: number[];
  /** Compatibility alias populated from `rgb` so legacy callers reading `.luminance` still work. */
  luminance: number[];
  r: number[];
  g: number[];
  b: number[];
  totalOpaquePixels: number;
  /** Compatibility alias populated from `totalOpaquePixels`. */
  pixelCount: number;
}

export async function nativeImageOpPreview(
  op: NativeImageOpSpec,
  layerId?: string | null,
  docId?: string | null
): Promise<NativeRectI32 | null> {
  if (!isTauriDesktopRuntime()) return null;
  return invokeNative<NativeRectI32>('native_image_op_preview', {
    docId: docId ?? null,
    layerId: layerId ?? null,
    op,
  });
}

export async function nativeImageOpApply(
  op: NativeImageOpSpec,
  layerId?: string | null,
  docId?: string | null
): Promise<{ modified: boolean; layerId: string; dirtyRect: NativeRectI32 } | null> {
  if (!isTauriDesktopRuntime()) return null;
  return invokeNative<{ modified: boolean; layerId: string; dirtyRect: NativeRectI32 }>(
    'native_image_op_apply',
    {
      docId: docId ?? null,
      layerId: layerId ?? null,
      op,
    }
  );
}

export async function nativeLayerHistogram(
  layerId?: string | null,
  docId?: string | null
): Promise<NativeLayerHistogram | null> {
  if (!isTauriDesktopRuntime()) return null;
  const raw = await invokeNative<Partial<NativeLayerHistogram>>('native_layer_histogram', {
    docId: docId ?? null,
    layerId: layerId ?? null,
  });
  if (!raw) return null;
  const rgb = Array.isArray(raw.rgb)
    ? raw.rgb
    : Array.isArray(raw.luminance)
      ? raw.luminance
      : new Array<number>(256).fill(0);
  const totalOpaquePixels =
    typeof raw.totalOpaquePixels === 'number'
      ? raw.totalOpaquePixels
      : typeof raw.pixelCount === 'number'
        ? raw.pixelCount
        : 0;
  return {
    rgb,
    luminance: rgb,
    r: Array.isArray(raw.r) ? raw.r : new Array<number>(256).fill(0),
    g: Array.isArray(raw.g) ? raw.g : new Array<number>(256).fill(0),
    b: Array.isArray(raw.b) ? raw.b : new Array<number>(256).fill(0),
    totalOpaquePixels,
    pixelCount: totalOpaquePixels,
  };
}

// --- 8. Vector Layer & Bézier Pen Fast Rasterization ---

export interface NativeVectorStrokePath {
  id: string;
  points: { x: number; y: number; pressure: number; width?: number }[];
  color: string;
  size: number;
  opacity?: number;
  hardness?: number;
  closed?: boolean;
}

export async function nativeRasterizeVectorLayer(
  layerId: string,
  strokes: NativeVectorStrokePath[],
  recordHistory: boolean = true,
  docId?: string | null
): Promise<{ modified: boolean; layerId: string; dirtyRect: NativeRectI32 } | null> {
  if (!isTauriDesktopRuntime()) return null;
  return invokeNative<{ modified: boolean; layerId: string; dirtyRect: NativeRectI32 }>(
    'native_rasterize_vector_layer',
    {
      docId: docId ?? null,
      layerId,
      strokes,
      recordHistory,
    }
  );
}

export async function nativeRasterizeBezier(
  params: {
    anchors: { x: number; y: number; handleIn?: [number, number] | null; handleOut?: [number, number] | null }[];
    closed?: boolean;
    strokeColor?: string;
    fillColor?: string | null;
    strokeWidth?: number;
    opacity?: number;
    stroke?: boolean;
    fill?: boolean;
    antiAlias?: boolean;
    layerId?: string | null;
  },
  docId?: string | null
): Promise<{ modified: boolean; layerId: string; dirtyRect: NativeRectI32 } | null> {
  if (!isTauriDesktopRuntime()) return null;
  return invokeNative<{ modified: boolean; layerId: string; dirtyRect: NativeRectI32 }>(
    'native_rasterize_bezier',
    { docId: docId ?? null, params }
  );
}

// --- 9. Multiplayer Collab GPU Draft Fast-Path & Direct Binary Tile Delta Sync ---

export function nativeCollabRemoteStrokeStart(params: {
  peerId: string;
  strokeId: string;
  layerId: string;
  color: string;
  size: number;
  opacity: number;
  hardness: number;
  isEraser: boolean;
  usePressureSize: boolean;
}): Promise<void> {
  return invokeFireAndForget('native_collab_remote_stroke_start', { params });
}

export function nativeCollabRemoteStrokeChunk(
  peerId: string,
  strokeId: string,
  points: { x: number; y: number; pressure: number }[]
): Promise<void> {
  return invokeFireAndForget('native_collab_remote_stroke_chunk', {
    peerId,
    strokeId,
    points,
  });
}

export function nativeCollabRemoteStrokeFinish(
  peerId: string,
  strokeId: string,
  expectedTiles: number = 0
): Promise<void> {
  return invokeFireAndForget('native_collab_remote_stroke_finish', {
    peerId,
    strokeId,
    expectedTiles,
  });
}

export function nativeCollabRemoteStrokeDispose(peerId: string, strokeId: string): Promise<void> {
  return invokeFireAndForget('native_collab_remote_stroke_dispose', { peerId, strokeId });
}

export function nativeCollabRemotePeerDispose(peerId: string): Promise<void> {
  return invokeFireAndForget('native_collab_remote_peer_dispose', { peerId });
}

export async function nativeCollabEncodeTiles(
  layerId: string,
  coords?: { tx: number; ty: number }[] | null,
  docId?: string | null
): Promise<Uint8Array[]> {
  if (!isTauriDesktopRuntime()) return [];
  const invoke = await getTauriInvoke();
  const raw = await invoke<ArrayBuffer>('native_collab_encode_tiles', {
    docId: docId ?? null,
    layerId,
    coords: coords ?? null,
  });
  const bytes = new Uint8Array(raw);
  if (bytes.byteLength < 4) return [];
  const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
  const count = view.getUint32(0, true);
  const packets: Uint8Array[] = [];
  let offset = 4;
  for (let i = 0; i < count && offset + 4 <= bytes.byteLength; i++) {
    const len = view.getUint32(offset, true);
    offset += 4;
    if (offset + len > bytes.byteLength) break;
    packets.push(bytes.slice(offset, offset + len));
    offset += len;
  }
  return packets;
}

export async function nativeCollabApplyTileDelta(
  layerId: string,
  packet: Uint8Array,
  bumpEpoch: boolean = true,
  docId?: string | null
): Promise<{ layerId: string; tx: number; ty: number; codec: number; cleared: boolean } | null> {
  if (!isTauriDesktopRuntime()) return null;
  const invoke = await getTauriInvoke();
  const payload =
    packet.byteOffset === 0 && packet.byteLength === packet.buffer.byteLength
      ? packet
      : packet.slice();
  const headers: Record<string, string> = {
    'x-layer-id': encodeURIComponent(layerId),
    'x-bump-epoch': bumpEpoch ? '1' : '0',
  };
  if (docId) headers['x-doc-id'] = encodeURIComponent(docId);
  return invoke('native_collab_apply_tile_delta', payload, { headers });
}

export async function nativeCollabEncodeMask(
  layerId: string,
  docId?: string | null
): Promise<Uint8Array | null> {
  if (!isTauriDesktopRuntime()) return null;
  const invoke = await getTauriInvoke();
  const raw = await invoke<ArrayBuffer>('native_collab_encode_mask', {
    docId: docId ?? null,
    layerId,
  });
  return new Uint8Array(raw);
}

export async function nativeCollabApplyMask(
  layerId: string,
  packet: Uint8Array,
  docId?: string | null
): Promise<void> {
  if (!isTauriDesktopRuntime()) return;
  const invoke = await getTauriInvoke();
  const payload =
    packet.byteOffset === 0 && packet.byteLength === packet.buffer.byteLength
      ? packet
      : packet.slice();
  const headers: Record<string, string> = {
    'x-layer-id': encodeURIComponent(layerId),
  };
  if (docId) headers['x-doc-id'] = encodeURIComponent(docId);
  await invoke('native_collab_apply_mask', payload, { headers });
}

export async function nativeCollabChecksum(docId?: string | null): Promise<string | null> {
  if (!isTauriDesktopRuntime()) return null;
  return invokeNative<string>('native_collab_checksum', { docId: docId ?? null });
}

// --- 10. Zero-Canvas Native Image Export, Import & Layer Read ---

export async function exportNativeDocumentImage(params: {
  docId?: string | null;
  format: 'png' | 'jpg' | 'jpeg' | 'webp';
  quality?: number;
  options?: NativeFlattenOptions;
}): Promise<Uint8Array | null> {
  if (!isTauriDesktopRuntime()) return null;
  const invoke = await getTauriInvoke();
  const raw = await invoke<ArrayBuffer>('native_engine_export_image', {
    docId: params.docId ?? null,
    format: params.format,
    quality: params.quality ?? 0.92,
    options: params.options ?? null,
  });
  return new Uint8Array(raw);
}

export async function importNativeImageLayer(params: {
  docId?: string | null;
  layerId: string;
  name: string;
  bytes: Uint8Array;
  offsetX?: number;
  offsetY?: number;
  recordHistory?: boolean;
}): Promise<NativeDocumentMetaSnapshot | null> {
  if (!isTauriDesktopRuntime()) return null;
  const invoke = await getTauriInvoke();
  const payload =
    params.bytes.byteOffset === 0 && params.bytes.byteLength === params.bytes.buffer.byteLength
      ? params.bytes
      : params.bytes.slice();
  const headers: Record<string, string> = {
    'x-layer-id': encodeURIComponent(params.layerId),
    'x-name': encodeURIComponent(params.name),
    'x-record-history': params.recordHistory === false ? '0' : '1',
  };
  if (params.docId) headers['x-doc-id'] = encodeURIComponent(params.docId);
  if (params.offsetX !== undefined) headers['x-offset-x'] = String(Math.round(params.offsetX));
  if (params.offsetY !== undefined) headers['x-offset-y'] = String(Math.round(params.offsetY));
  return invoke<NativeDocumentMetaSnapshot>('native_engine_import_image_layer', payload, {
    headers,
  });
}

export async function readNativeLayerBoundsRgba(
  layerId: string,
  docId?: string | null
): Promise<{ x: number; y: number; width: number; height: number; rgba: Uint8ClampedArray<ArrayBuffer> } | null> {
  if (!isTauriDesktopRuntime()) return null;
  const invoke = await getTauriInvoke();
  const raw = await invoke<ArrayBuffer>('native_engine_read_layer_rgba', {
    docId: docId ?? null,
    layerId,
  });
  const bytes = new Uint8Array(raw);
  if (bytes.byteLength < 17 || bytes[0] === 0) return null;
  const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
  const x = view.getInt32(1, true);
  const y = view.getInt32(5, true);
  const width = view.getUint32(9, true);
  const height = view.getUint32(13, true);
  const rgba = new Uint8ClampedArray(new ArrayBuffer(bytes.byteLength - 17));
  rgba.set(bytes.subarray(17));
  return { x, y, width, height, rgba };
}

export async function readNativeLayerMaskRgba(
  layerId: string,
  docId?: string | null
): Promise<{ width: number; height: number; defaultColor: number; rgba: Uint8ClampedArray<ArrayBuffer> } | null> {
  if (!isTauriDesktopRuntime()) return null;
  const invoke = await getTauriInvoke();
  const raw = await invoke<ArrayBuffer>('native_engine_read_layer_mask_rgba', {
    docId: docId ?? null,
    layerId,
  });
  const bytes = new Uint8Array(raw);
  if (bytes.byteLength < 10 || bytes[0] === 0) return null;
  const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
  const defaultColor = bytes[1];
  const width = view.getUint32(2, true);
  const height = view.getUint32(6, true);
  const rgba = new Uint8ClampedArray(new ArrayBuffer(bytes.byteLength - 10));
  rgba.set(bytes.subarray(10));
  return { width, height, defaultColor, rgba };
}