Skip to content

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

87.4 KB
Raw Blame
import React, { useRef, useEffect, useCallback } from 'react';
import {
  CanvasColorMode,
  CanvasDimensions,
  CanvasSelection,
  DocumentTab,
  LayerItem,
  LoadedDocument,
  NewCanvasOptions,
} from '../types/editor';
import { AppSettings, ResizeCanvasOptions } from '../types/settings';
import { openFile } from '../utils/imageLoader';
import {
  getParentDirectory,
  promptExportPngImage,
  promptSaveAs,
  sanitizeDocumentStem,
  SaveDocumentData,
  SaveProgress,
  saveToExistingHandle,
} from '../utils/saveManager';
import { globalTimelapseManager } from '../utils/timelapseEngine';
import {
  FileSystemFileHandleLike,
  RecentDocument,
  saveRecentDocument,
} from '../utils/recentDocumentsManager';
import { enforceColorMode } from '../utils/colorUtils';
import { importBrushFile, isSupportedBrushFileName } from '../utils/inkbBrushFormat';
import { documentStore } from '../utils/documentStore';
import { computeRecommendedSettings, performanceManager } from '../utils/performanceManager';
import {
  artworkTimeTracker,
  sanitizeWorkTimeMs,
} from '../utils/artworkTimeTracker';
import { shortcutManager } from '../utils/shortcutManager';
import { recoveryService, CrashedSessionInfo } from '../services/recoveryService';
import { multiplayerService } from '../services/multiplayerService';
import {
  colorSetsStoreActions,
  documentStoreActions,
  toolStoreActions,
  uiStoreActions,
  useDocumentStore,
  useToolStore,
  useUiStore,
} from '../stores';
import { PushHistoryStepFn } from '../hooks/drawing';
import {
  CanvasResizeResult,
  transformPerspectiveRulerForResize,
  transformStraightRulerForResize,
} from '../hooks/layerManager/useLayerResize';
import { cloneSelectionForHistory } from '../utils/selectionUtils';
import { isTauriEnvironment } from '../hooks/useMultiplayer';
import {
  SaveDocumentResult,
  isFinalizingAppClose,
  requestAppClose,
} from '../utils/appCloseFlow';
import { installReloadGuard } from '../utils/reloadGuard';
import {
  findOpenDocumentBySourcePath,
  listenForOpenFiles,
  readTauriPathAsFile,
  takePendingOpenFiles,
} from '../utils/osFileOpen';
import {
  closeNativeDocument,
  flushNativeGpuPool,
  fromNativeLayerNodeMeta,
  getNativeMemoryStats,
  isNativeCanvasActive,
  NativeMemoryStats,
  nativeRecoveryRestore,
  openNativeDocumentBytes,
  openNativeDocumentFromPath,
  purgeNativeMemory,
  resizeNativeCanvas,
  saveNativeInkDocument,
  saveNativeInkDocumentWithDialog,
  setNativeMemoryBudget,
  subscribeNativeCanvasActive,
  subscribeNativeStrokeCommitted,
  vramBudgetMbFromPreset,
} from '../utils/nativeEngineBridge';
import { t } from '../i18n';

function hasMeaningfulLayerEdit(prev: LayerItem[], next: LayerItem[]): boolean {
  if (prev === next) return false;
  if (prev.length !== next.length) return true;
  for (let i = 0; i < prev.length; i++) {
    const a = prev[i];
    const b = next[i];
    if (a === b) continue;
    if (
      a.id !== b.id ||
      a.name !== b.name ||
      a.type !== b.type ||
      a.visible !== b.visible ||
      a.opacity !== b.opacity ||
      a.blendMode !== b.blendMode ||
      a.locked !== b.locked ||
      a.alphaLocked !== b.alphaLocked ||
      a.clipped !== b.clipped ||
      a.parentId !== b.parentId ||
      a.isReference !== b.isReference ||
      a.isToneLayer !== b.isToneLayer ||
      a.toneEnabled !== b.toneEnabled ||
      a.toneFrequency !== b.toneFrequency ||
      a.toneAngle !== b.toneAngle ||
      a.toneDotShape !== b.toneDotShape ||
      a.toneDensity !== b.toneDensity ||
      a.toneDensityType !== b.toneDensityType ||
      a.layerColorEnabled !== b.layerColorEnabled ||
      a.layerColor !== b.layerColor ||
      a.expressionColor !== b.expressionColor ||
      a.maskEnabled !== b.maskEnabled ||
      a.maskLinked !== b.maskLinked ||
      a.maskVersion !== b.maskVersion ||
      a.adjustmentData !== b.adjustmentData ||
      a.styles !== b.styles ||
      a.vectorStrokes !== b.vectorStrokes ||
      a.textData !== b.textData ||
      a.balloonData !== b.balloonData ||
      a.comicFrames !== b.comicFrames
    ) {
      return true;
    }
  }
  return false;
}

function computeEffectiveOpacityForLayers(allLayers: LayerItem[], layer: LayerItem): number {
  let opacity = layer.opacity;
  let parentId = layer.parentId;
  const visited = new Set<string>([layer.id]);
  while (parentId && !visited.has(parentId)) {
    visited.add(parentId);
    const parent = allLayers.find((l) => l.id === parentId);
    if (!parent) break;
    opacity *= parent.opacity;
    parentId = parent.parentId;
  }
  return opacity;
}

function computeLayerVisibleForLayers(allLayers: LayerItem[], layer: LayerItem): boolean {
  if (!layer.visible) return false;
  let parentId = layer.parentId;
  const visited = new Set<string>([layer.id]);
  while (parentId && !visited.has(parentId)) {
    visited.add(parentId);
    const parent = allLayers.find((l) => l.id === parentId);
    if (!parent) break;
    if (!parent.visible) return false;
    parentId = parent.parentId;
  }
  return true;
}

interface FileWithOptionalPath extends File {
  path?: string;
}

interface TauriWindow extends Window {
  __TAURI_INTERNALS__?: unknown;
}

interface PickerWindow extends Window {
  showOpenFilePicker?: (options?: {
    types?: Array<{ description?: string; accept: Record<string, string[]> }>;
    multiple?: boolean;
  }) => Promise<FileSystemFileHandleLike[]>;
}

interface ProcessFileOptions {
  handle?: FileSystemFileHandleLike | null;
  sourcePath?: string;
  docId?: string;
  isStarred?: boolean;
}

const DIRECT_SAVE_EXTENSIONS = new Set([
  '.ink',
  '.psd',
  '.psb',
  '.png',
  '.jpg',
  '.jpeg',
  '.webp',
]);

function isRealNativeDiskPath(p: string | null | undefined): p is string {
  if (!p || typeof p !== 'string') return false;
  const trimmed = p.trim();
  if (!trimmed) return false;
  // Ignore legacy placeholder display paths that were never real disk paths
  if (trimmed.startsWith('InkStudio\\') || trimmed.startsWith('InkStudio/')) return false;
  if (trimmed.startsWith('C:\\Users\\Artist\\Documents\\InkStudio\\')) return false;
  return /^[a-zA-Z]:[\\/]/.test(trimmed) || trimmed.startsWith('\\\\') || trimmed.startsWith('/');
}

const OPEN_FILE_PICKER_TYPES = [
  {
    description: 'Ink Studio & Image Files',
    accept: {
      'application/octet-stream': [
        '.ink',
        '.psd',
        '.psb',
        '.clip',
        '.csp',
        '.lip',
        '.inkb',
        '.sut',
        '.sora',
      ],
      'image/png': ['.png'],
      'image/jpeg': ['.jpg', '.jpeg'],
      'image/webp': ['.webp'],
      'image/bmp': ['.bmp'],
      'image/gif': ['.gif'],
      'image/svg+xml': ['.svg'],
    },
  },
];

export interface UseDocumentLifecycleParams {
  layers: LayerItem[];
  activeLayer: LayerItem | undefined;
  activeLayerId: string;
  getEffectiveOpacity: (layer: LayerItem) => number;
  isLayerEffectivelyVisible: (layer: LayerItem) => boolean;
  setActiveLayerId: (id: string) => void;
  resetToNewCanvas: (
    dims: CanvasDimensions,
    bgColor: string,
    mode: CanvasColorMode,
    defaultFreq: number,
    docId: string
  ) => { layers: LayerItem[]; activeLayerId: string };
  setDefaultToneFrequency: (freq: number) => void;
  clearDocument: () => void;
  loadDocument: (
    doc: Pick<LoadedDocument, 'name' | 'dimensions' | 'colorMode' | 'layers'>,
    sessionId?: string,
    alreadyInGrid?: boolean
  ) => void;
  switchDocumentSession: (
    docId: string,
    layers: LayerItem[],
    activeLayerId: string,
    dimensions: CanvasDimensions
  ) => void;
  resizeCanvas: (
    newDims: CanvasDimensions,
    options: ResizeCanvasOptions
  ) => CanvasResizeResult | void;
  copyLayer: (id: string) => LayerItem | null;
  pasteLayer: () => Promise<{
    success: boolean;
    layerId?: string;
    layerName?: string;
    tileDeltas?: import('../types/editor').TileDelta[];
    layerTreeDelta?: import('../types/editor').LayerTreeDelta;
  }>;
  onDeselectAfterPaste?: () => void;
  getSelection?: () => CanvasSelection | null;
  clearSelectionWithoutHistory?: () => void;
  flushPendingHistoryTasks?: () => void;
  deleteLayer: (id: string) => void;
  pasteLayerFromFile: (file: File) => Promise<string>;
  resetZoomAndCenter: (dims?: CanvasDimensions) => void;
  resetHistory: (targetDocumentId?: string) => void;
  pushHistoryStep: PushHistoryStepFn;
  showToast: (msg: string) => void;
}

export function useDocumentLifecycle({
  layers,
  activeLayer,
  activeLayerId,
  getEffectiveOpacity: _getEffectiveOpacity,
  isLayerEffectivelyVisible: _isLayerEffectivelyVisible,
  setActiveLayerId,
  resetToNewCanvas,
  setDefaultToneFrequency,
  clearDocument,
  loadDocument,
  switchDocumentSession,
  resizeCanvas,
  copyLayer,
  pasteLayer,
  onDeselectAfterPaste,
  getSelection,
  clearSelectionWithoutHistory,
  flushPendingHistoryTasks,
  deleteLayer,
  pasteLayerFromFile,
  resetZoomAndCenter,
  resetHistory,
  pushHistoryStep,
  showToast,
}: UseDocumentLifecycleParams) {
  const activeDocumentId = useDocumentStore((s) => s.activeDocumentId);
  const documentName = useDocumentStore((s) => s.documentName);
  const savedFileInfo = useDocumentStore((s) => s.savedFileInfo);

  const fileInputRef = useRef<HTMLInputElement>(null);
  const pasteFileInputRef = useRef<HTMLInputElement>(null);
  const import3DFileInputRef = useRef<HTMLInputElement>(null);
  const needsAdaptiveFitRef = useRef<boolean>(true);
  const pendingFitDimsRef = useRef<CanvasDimensions | null>(null);
  const autoCreatedInitialDocIdRef = useRef<string | null>(null);
  const openFileQueueRef = useRef<Promise<void>>(Promise.resolve());
  const savingDocIdsRef = useRef<Set<string>>(new Set());
  const layersRef = useRef<LayerItem[]>(layers);
  layersRef.current = layers;

  const handleViewportReady = useCallback(
    (viewport: HTMLDivElement) => {
      if (needsAdaptiveFitRef.current) {
        if (viewport.clientWidth <= 0 || viewport.clientHeight <= 0) {
          return;
        }
        needsAdaptiveFitRef.current = false;
        const targetDims = pendingFitDimsRef.current || useDocumentStore.getState().dimensions;
        pendingFitDimsRef.current = null;
        resetZoomAndCenter(targetDims);
      }
    },
    [resetZoomAndCenter]
  );

  const handleCreateNewCanvas = useCallback(
    (options: NewCanvasOptions) => {
      if (useUiStore.getState().isResizeCanvasModalOpen) {
        uiStoreActions.setResizeCanvasModalOpen(false);
      }
      const safeWidth =
        typeof options?.width === 'number' && Number.isFinite(options.width) && options.width >= 1
          ? Math.round(options.width)
          : 1920;
      const safeHeight =
        typeof options?.height === 'number' && Number.isFinite(options.height) && options.height >= 1
          ? Math.round(options.height)
          : 1080;
      const safeDpi =
        typeof options?.dpi === 'number' && Number.isFinite(options.dpi) && options.dpi >= 1
          ? Math.round(options.dpi)
          : 300;
      const safeColorMode: CanvasColorMode =
        options?.colorMode === 'monochrome' || options?.colorMode === 'grayscale'
          ? options.colorMode
          : 'color';
      const safeBackgroundColor =
        typeof options?.backgroundColor === 'string' && options.backgroundColor.trim().length > 0
          ? options.backgroundColor
          : '#ffffff';
      const newDims: CanvasDimensions = {
        width: safeWidth,
        height: safeHeight,
        dpi: safeDpi,
      };
      documentStoreActions.setDimensions(newDims);
      documentStoreActions.setColorMode(safeColorMode);
      let name = (typeof options?.name === 'string' && options.name.trim() ? options.name : 'Untitled').trim();
      if (!/\.[a-zA-Z0-9]+$/.test(name) && !name.endsWith('*')) {
        name = `${name}*`;
      }
      documentStoreActions.setDocumentName(name);
      documentStoreActions.setSavedFileInfo(null);

      const rawPrimaryColor = useToolStore.getState().primaryColor;
      const primaryColor =
        typeof rawPrimaryColor === 'string' && rawPrimaryColor.trim().length > 0
          ? rawPrimaryColor
          : '#000000';
      if (safeColorMode === 'monochrome') {
        const snapPrimary = enforceColorMode(primaryColor, 'monochrome');
        toolStoreActions.setPrimaryColor(snapPrimary, false, 'monochrome');
        toolStoreActions.updateBrushSettings({ color: snapPrimary, hardness: 1.0 });
      } else if (safeColorMode === 'grayscale') {
        const snapPrimary = enforceColorMode(primaryColor, 'grayscale');
        toolStoreActions.setPrimaryColor(snapPrimary, false, 'grayscale');
        toolStoreActions.updateBrushSettings({ color: snapPrimary });
      }

      const defaultFreq =
        typeof options?.defaultFrequency === 'number' && Number.isFinite(options.defaultFrequency)
          ? options.defaultFrequency
          : 60;
      const newDocId = `doc-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`;
      const { layers: initialLayers, activeLayerId: topId } = resetToNewCanvas(
        newDims,
        safeBackgroundColor,
        safeColorMode,
        defaultFreq,
        newDocId
      );
      needsAdaptiveFitRef.current = true;
      pendingFitDimsRef.current = newDims;
      resetZoomAndCenter(newDims);
      resetHistory(newDocId);

      const newDoc: DocumentTab = {
        id: newDocId,
        name,
        dimensions: newDims,
        colorMode: safeColorMode,
        layers: Array.isArray(initialLayers) ? initialLayers : [],
        activeLayerId: topId,
        perspectiveRuler: null,
        defaultFrequency: defaultFreq,
        workTimeMs: 0,
      };

      artworkTimeTracker.initDocument(newDocId, 0);
      documentStoreActions.setPerspectiveRuler(null, { recordHistory: false });
      documentStoreActions.setStraightRuler(null, { recordHistory: false });
      documentStoreActions.setDocuments((prev) => (Array.isArray(prev) ? [...prev, newDoc] : [newDoc]));
      documentStoreActions.setActiveDocumentId(newDocId);
      uiStoreActions.setAppView('workspace');
      showToast(t('Created {name}', { name }));
    },
    [resetHistory, resetToNewCanvas, resetZoomAndCenter, showToast]
  );

  const handleCopySelectedLayer = useCallback(() => {
    if (!activeLayer) return;
    const copied = copyLayer(activeLayerId);
    if (copied) {
      showToast(t('Copied layer "{name}"', { name: copied.name }));
    }
  }, [activeLayer, activeLayerId, copyLayer, showToast]);

  const handlePasteSelectedLayer = useCallback(async () => {
    const res = await pasteLayer();
    if (res.success && res.layerName) {
      if (res.layerId && ((res.tileDeltas && res.tileDeltas.length > 0) || res.layerTreeDelta)) {
        pushHistoryStep(
          'selection-move',
          t('Paste "{name}"', { name: res.layerName }),
          null,
          null,
          res.layerId,
          undefined,
          res.tileDeltas,
          undefined,
          undefined,
          undefined,
          false,
          res.layerTreeDelta
        );
      }
      onDeselectAfterPaste?.();
      showToast(t('Pasted into "{name}"', { name: res.layerName }));
    } else {
      showToast(t('Clipboard is empty'));
    }
  }, [onDeselectAfterPaste, pasteLayer, pushHistoryStep, showToast]);

  const handleDeleteSelectedLayer = useCallback(() => {
    const rasterCount = layers.filter((l) => l.type === 'raster').length;
    if (rasterCount <= 1) {
      showToast(t('Cannot delete the only raster layer'));
      return;
    }
    const layerName = activeLayer?.name || t('layer');
    deleteLayer(activeLayerId);
    showToast(t('Deleted layer "{name}"', { name: layerName }));
  }, [activeLayer, activeLayerId, deleteLayer, layers, showToast]);

  const handleTriggerPasteFromFile = useCallback(() => {
    pasteFileInputRef.current?.click();
  }, []);

  const handlePasteFileInputChange = useCallback(
    async (e: React.ChangeEvent<HTMLInputElement>) => {
      const file = e.target.files?.[0];
      if (file) {
        try {
          const layerName = await pasteLayerFromFile(file);
          documentStoreActions.markDocumentDirty(useDocumentStore.getState().activeDocumentId, true);
          showToast(t('Pasted "{name}" from file', { name: layerName }));
        } catch (err: unknown) {
          console.error('Failed to paste from file:', err);
          const errMsg = err instanceof Error ? err.message : String(err);
          void uiStoreActions.alertDialog({
            title: t('Paste Image Failed'),
            message: t('Failed to paste image from file: {error}', { error: errMsg }),
          });
        } finally {
          if (pasteFileInputRef.current) {
            pasteFileInputRef.current.value = '';
          }
        }
      }
    },
    [pasteLayerFromFile, showToast]
  );

  const handleTriggerImport3DFile = useCallback(() => {
    import3DFileInputRef.current?.click();
  }, []);

  const handleImport3DFileInputChange = useCallback(
    (e: React.ChangeEvent<HTMLInputElement>) => {
      const file = e.target.files?.[0];
      if (file) {
        toolStoreActions.selectTool('3d');
        uiStoreActions.set3DLayerOpen(true, file);
        showToast(t('Importing 3D model "{name}" into 3D stage...', { name: file.name }));
        if (import3DFileInputRef.current) {
          import3DFileInputRef.current.value = '';
        }
      }
    },
    [showToast]
  );

  const handleResizeCanvas = useCallback(
    (options: ResizeCanvasOptions) => {
      if (multiplayerService.isConnected() && multiplayerService.getLocalRole() === 'viewer') {
        showToast(t('Viewers have read-only access'));
        return;
      }

      flushPendingHistoryTasks?.();

      const storeState = useDocumentStore.getState();
      const curDims = storeState.dimensions;
      const activeId = storeState.activeDocumentId;
      const newDims: CanvasDimensions = {
        width: options.width,
        height: options.height,
        dpi: options.dpi || curDims.dpi,
      };

      const beforeDims: CanvasDimensions = { ...curDims };
      const beforePersp = storeState.perspectiveRuler
        ? {
            ...storeState.perspectiveRuler,
            grid: { ...storeState.perspectiveRuler.grid },
            vps: storeState.perspectiveRuler.vps.map((vp) => ({ ...vp })),
          }
        : null;
      const beforeStraight = storeState.straightRuler
        ? { ...storeState.straightRuler }
        : null;
      const beforeSelection = cloneSelectionForHistory(getSelection?.() ?? null);

      const useNativeResize = isNativeCanvasActive() && Boolean(activeId);
      const resizeRes = useNativeResize
        ? undefined
        : (resizeCanvas(newDims, options) as CanvasResizeResult | void);

      const scaleContent = resizeRes ? resizeRes.scaleContent : Boolean(options.scaleContent);
      let offsetX = resizeRes ? resizeRes.offsetX : 0;
      let offsetY = resizeRes ? resizeRes.offsetY : 0;
      if (useNativeResize && !scaleContent) {
        const anchor = options.anchor || 'center';
        const dw = newDims.width - curDims.width;
        const dh = newDims.height - curDims.height;
        if (anchor.includes('left')) offsetX = 0;
        else if (anchor.includes('right')) offsetX = dw;
        else offsetX = Math.round(dw / 2);
        if (anchor.includes('top')) offsetY = 0;
        else if (anchor.includes('bottom')) offsetY = dh;
        else offsetY = Math.round(dh / 2);
      }

      if (useNativeResize && activeId) {
        void resizeNativeCanvas({
          docId: activeId,
          dimensions: newDims,
          offsetX,
          offsetY,
          scaleContent,
          bgHex: options.backgroundColor || '#ffffff',
          recordHistory: true,
        });
      }

      if (clearSelectionWithoutHistory) {
        clearSelectionWithoutHistory();
      } else {
        onDeselectAfterPaste?.();
      }

      const scaleX = resizeRes ? resizeRes.scaleX : newDims.width / Math.max(1, curDims.width);
      const scaleY = resizeRes ? resizeRes.scaleY : newDims.height / Math.max(1, curDims.height);
      const afterPersp = transformPerspectiveRulerForResize(
        beforePersp,
        scaleContent,
        offsetX,
        offsetY,
        scaleX,
        scaleY
      );
      const afterStraight = transformStraightRulerForResize(
        beforeStraight,
        scaleContent,
        offsetX,
        offsetY,
        scaleX,
        scaleY
      );

      documentStoreActions.setDimensions(newDims, activeId);
      if (beforePersp) {
        documentStoreActions.setPerspectiveRuler(afterPersp, { recordHistory: false });
      }
      if (beforeStraight) {
        documentStoreActions.setStraightRuler(afterStraight, { recordHistory: false });
      }
      documentStoreActions.markDocumentDirty(activeId, true);

      pendingFitDimsRef.current = newDims;
      needsAdaptiveFitRef.current = true;
      resetZoomAndCenter(newDims);

      if (!useNativeResize) {
        pushHistoryStep(
          'canvas-resize',
          scaleContent
            ? t('Resize Canvas ({width} × {height})', {
                width: newDims.width,
                height: newDims.height,
              })
            : t('Crop / Resize Canvas ({width} × {height})', {
                width: newDims.width,
                height: newDims.height,
              }),
          null,
          null,
          activeLayerId || layersRef.current[0]?.id || '',
          { x: 0, y: 0, width: newDims.width, height: newDims.height },
          resizeRes?.tileDeltas,
          undefined,
          undefined,
          undefined,
          false,
          resizeRes?.layerTreeDelta,
          {
            beforeDimensions: beforeDims,
            afterDimensions: { ...newDims },
            ...(beforePersp
              ? { beforePerspectiveRuler: beforePersp, afterPerspectiveRuler: afterPersp }
              : {}),
            ...(beforeStraight
              ? { beforeStraightRuler: beforeStraight, afterStraightRuler: afterStraight }
              : {}),
            ...(beforeSelection ? { beforeSelection, afterSelection: null } : {}),
          }
        );
      }

      if (multiplayerService.isConnected()) {
        multiplayerService.sendCanvasResize(newDims, options);
      }
      showToast(
        t('Canvas resized to {width} × {height} px', {
          width: newDims.width,
          height: newDims.height,
        })
      );
    },
    [
      activeLayerId,
      clearSelectionWithoutHistory,
      flushPendingHistoryTasks,
      getSelection,
      onDeselectAfterPaste,
      pushHistoryStep,
      resetZoomAndCenter,
      resizeCanvas,
      showToast,
    ]
  );

  const handleUpdateSettings = useCallback((newSettings: AppSettings) => {
    const prev = useUiStore.getState().appSettings;
    uiStoreActions.updateAppSettings(newSettings);
    shortcutManager.setOverrides(newSettings.shortcuts);
    if (prev.tileMemoryBudgetMb !== newSettings.tileMemoryBudgetMb) {
      documentStore.setTileBudgetMb(newSettings.tileMemoryBudgetMb || 1024);
    }
    if (prev.undoRamSteps !== newSettings.undoRamSteps) {
      documentStore.setSharedUndoRamStepsBudget(newSettings.undoRamSteps || 15);
    }
    if (prev.offloadInactiveTabs !== newSettings.offloadInactiveTabs) {
      documentStore.setOffloadInactiveUndoOnSwitch(newSettings.offloadInactiveTabs);
    }
    if (
      prev.gpuPowerPreference !== newSettings.gpuPowerPreference ||
      prev.desktopGraphicsApi !== newSettings.desktopGraphicsApi ||
      prev.scratchDiskPath !== newSettings.scratchDiskPath ||
      prev.scratchDiskCompression !== newSettings.scratchDiskCompression ||
      prev.cpuWorkerThreads !== newSettings.cpuWorkerThreads
    ) {
      void performanceManager.syncDesktopBackendConfig(newSettings);
    }
    if (
      prev.defaultStabilization !== newSettings.defaultStabilization ||
      prev.usePressureByDefault !== newSettings.usePressureByDefault ||
      prev.smoothingEnabled !== newSettings.smoothingEnabled
    ) {
      toolStoreActions.updateBrushSettings({
        stabilization: newSettings.defaultStabilization,
        usePressure: newSettings.usePressureByDefault,
        smoothing: newSettings.smoothingEnabled,
      });
    }
  }, []);

  const handleProcessFile = useCallback(
    async (file: File, options?: ProcessFileOptions) => {
      const lowerName = file.name.toLowerCase();
      if (
        (lowerName.endsWith('.glb') || lowerName.endsWith('.gltf') || lowerName.endsWith('.obj')) &&
        useDocumentStore.getState().documents.length > 0
      ) {
        toolStoreActions.selectTool('3d');
        uiStoreActions.set3DLayerOpen(true, file);
        showToast(t('Importing 3D model "{name}" into 3D stage...', { name: file.name }));
        return;
      }
      if (lowerName.endsWith('.cls')) {
        try {
          uiStoreActions.setLoading(true, t('Importing Color Set: {name}...', { name: file.name }));
          const res = await colorSetsStoreActions.importSetFile(file);
          if (res.ok) {
            showToast(
              t('Imported color set "{name}" ({count} colors)', {
                name: res.set.name,
                count: res.set.swatches.length,
              })
            );
          } else {
            showToast(res.error);
          }
        } catch {
          showToast(t('Failed to import color set file.'));
        } finally {
          uiStoreActions.setLoading(false, '');
          if (fileInputRef.current) {
            fileInputRef.current.value = '';
          }
        }
        return;
      }

      if (isSupportedBrushFileName(file.name)) {
        try {
          uiStoreActions.setLoading(true, t('Importing Brush: {name}...', { name: file.name }));
          const parsedBrush = await importBrushFile(file);
          if (parsedBrush.importWarnings && parsedBrush.importWarnings.length > 0) {
            const count = parsedBrush.importWarnings.length;
            showToast(
              count === 1
                ? t('Imported "{name}" (Notice: {notice})', {
                    name: parsedBrush.name,
                    notice: parsedBrush.importWarnings[0],
                  })
                : t('Imported "{name}" with {count} CSP import notices — check inspector', {
                    name: parsedBrush.name,
                    count,
                  })
            );
          } else {
            showToast(t('Imported brush "{name}"', { name: parsedBrush.name }));
          }
        } catch (err: unknown) {
          const msg = err instanceof Error ? err.message : t('Failed to import brush file.');
          showToast(msg);
        } finally {
          uiStoreActions.setLoading(false, '');
          if (fileInputRef.current) {
            fileInputRef.current.value = '';
          }
        }
        return;
      }

      try {
        uiStoreActions.setLoading(true, t('Loading {name}...', { name: file.name }));

        const alreadyOpenId = options?.docId
          ? useDocumentStore.getState().documents.some((d) => d.id === options.docId)
          : false;
        const newDocId =
          options?.docId && !alreadyOpenId
            ? options.docId
            : `doc-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`;
        const openedExt = file.name.includes('.')
          ? file.name.slice(file.name.lastIndexOf('.')).toLowerCase()
          : '';
        const fileHandle = options?.handle ?? undefined;
        const fileWithPath = file as FileWithOptionalPath;
        const candidateSourcePath = options?.sourcePath || fileWithPath.path || null;
        const realDiskPath = isRealNativeDiskPath(candidateSourcePath)
          ? candidateSourcePath
          : null;

        const isNativeZeroCopyFormat =
          openedExt === '.ink' ||
          openedExt === '.clip' ||
          openedExt === '.csp' ||
          openedExt === '.lip' ||
          openedExt === '.psd' ||
          openedExt === '.psb' ||
          openedExt === '.png' ||
          openedExt === '.jpg' ||
          openedExt === '.jpeg' ||
          openedExt === '.webp' ||
          openedExt === '.bmp' ||
          openedExt === '.gif' ||
          openedExt === '.ico' ||
          openedExt === '.tif' ||
          openedExt === '.tiff';

        let doc: LoadedDocument;
        let openedDirectlyInRust = false;

        if (isNativeCanvasActive() && isNativeZeroCopyFormat) {
          // Phase 6 Zero-Copy Rust Hydration: parses .ink / .clip / .psd / WIC raster images directly into
          // crates/ink-engine SparseLayerGrid and returns ONLY compact metadata + 64x64 thumbnails!
          const nativeRes = realDiskPath
            ? await openNativeDocumentFromPath(newDocId, realDiskPath)
            : await openNativeDocumentBytes(
                newDocId,
                file.name,
                new Uint8Array(await file.arrayBuffer())
              );
          openedDirectlyInRust = true;
          doc = {
            name: nativeRes.doc.name || file.name,
            dimensions: nativeRes.doc.dimensions,
            colorMode: nativeRes.doc.colorMode,
            layers: nativeRes.doc.layers.map(fromNativeLayerNodeMeta),
            previewDataUrl: nativeRes.previewDataUrl ?? nativeRes.doc.previewDataUrl ?? undefined,
            perspectiveRuler: (nativeRes.doc.perspectiveRuler as any) ?? null,
            animationTimeline: nativeRes.doc.animationTimeline as any,
            timelapse: (nativeRes.doc.timelapse as any) ?? null,
            workTimeMs: nativeRes.doc.workTimeMs,
          };
        } else {
          doc = await openFile(file, newDocId);
          openedDirectlyInRust = isNativeCanvasActive();
        }

        const initialSavedInfo =
          (fileHandle || realDiskPath) && DIRECT_SAVE_EXTENSIONS.has(openedExt)
            ? {
                name: file.name,
                ...(fileHandle ? { handle: fileHandle } : {}),
                ...(realDiskPath ? { path: realDiskPath } : {}),
                extension: openedExt,
              }
            : null;
        const resolvedSourcePath = realDiskPath;

        documentStoreActions.setDimensions(doc.dimensions);
        documentStoreActions.setColorMode(doc.colorMode);
        documentStoreActions.setDocumentName(doc.name);
        documentStoreActions.setSavedFileInfo(initialSavedInfo);

        loadDocument(doc, newDocId, openedDirectlyInRust);
        needsAdaptiveFitRef.current = true;
        pendingFitDimsRef.current = doc.dimensions;
        resetZoomAndCenter(doc.dimensions);
        resetHistory(newDocId);

        const topEditableLayer = doc.layers.find((l) => l.type === 'raster');
        const restoredWorkTimeMs = sanitizeWorkTimeMs(doc.workTimeMs);
        artworkTimeTracker.initDocument(newDocId, restoredWorkTimeMs);

        // Reconnect external persistent time-lapse recording (or migrate legacy embedded `.ink` frames)
        // before activating the tab so recording seamlessly resumes after restarts.
        let restoredTimelapse = { enabled: false, frameCount: 0 };
        const frameTotal = doc.timelapseFrames?.length ?? 0;
        if (frameTotal > 0) {
          uiStoreActions.setLoading(
            true,
            frameTotal === 1
              ? t('Migrating time-lapse to local storage ({count} frame)...', { count: frameTotal })
              : t('Migrating time-lapse to local storage ({count} frames)...', {
                  count: frameTotal,
                })
          );
        }
        restoredTimelapse = await globalTimelapseManager.attachOrRestoreSession(newDocId, {
          documentName: doc.name,
          metadata: doc.timelapse ?? null,
          legacyFrames: doc.timelapseFrames,
          linkedDocId: options?.docId ?? null,
          sourcePath: resolvedSourcePath,
          fallbackDims: doc.dimensions,
          onProgress: (done, total) => {
            if (frameTotal > 0 && total > 0) {
              uiStoreActions.setLoading(
                true,
                t('Migrating time-lapse to local storage ({done}/{total})...', { done, total })
              );
            }
          },
        });

        const newDoc: DocumentTab = {
          id: newDocId,
          name: doc.name,
          dimensions: doc.dimensions,
          colorMode: doc.colorMode,
          layers: doc.layers,
          activeLayerId: topEditableLayer?.id || doc.layers[0]?.id || 'layer-1',
          perspectiveRuler: doc.perspectiveRuler ?? null,
          sourcePath: resolvedSourcePath ?? undefined,
          savedFileInfo: initialSavedInfo ?? undefined,
          workTimeMs: restoredWorkTimeMs,
        };

        documentStoreActions.setPerspectiveRuler(doc.perspectiveRuler ?? null, {
          recordHistory: false,
        });
        documentStoreActions.setStraightRuler(null, { recordHistory: false });
        if (doc.animationTimeline !== undefined) {
          documentStoreActions.setAnimationTimeline(doc.animationTimeline);
        }
        // If the only open tab was the untouched auto-created initial blank canvas, replace it
        // cleanly so opening a `.ink` file doesn't leave an unwanted blank "Untitled*" tab behind.
        let replacedAutoDocId: string | null = null;
        documentStoreActions.setDocuments((prev) => {
          const autoId = autoCreatedInitialDocIdRef.current;
          if (
            autoId &&
            prev.length === 1 &&
            prev[0]?.id === autoId &&
            !prev[0]?.isDirty &&
            !prev[0]?.savedFileInfo &&
            !prev[0]?.sourcePath
          ) {
            replacedAutoDocId = autoId;
            autoCreatedInitialDocIdRef.current = null;
            return [newDoc];
          }
          return [...prev, newDoc];
        });
        if (replacedAutoDocId) {
          artworkTimeTracker.removeDocument(replacedAutoDocId);
          globalTimelapseManager.detachSession(replacedAutoDocId).catch(console.warn);
          documentStore.closeSession(replacedAutoDocId).catch(console.warn);
          recoveryService.closeSession(replacedAutoDocId).catch(console.warn);
          if (isNativeCanvasActive()) {
            void closeNativeDocument(replacedAutoDocId);
          }
        }
        documentStoreActions.setActiveDocumentId(newDocId);
        uiStoreActions.setAppView('workspace');

        saveRecentDocument({
          id: newDocId,
          title: file.name,
          path:
            resolvedSourcePath ||
            `C:\\Users\\Artist\\Documents\\InkStudio\\${file.name}`,
          size: file.size || 1048576,
          coverUrl: doc.previewDataUrl || doc.layers[0]?.thumbnailUrl,
          isStarred: options?.isStarred ?? false,
          fileType: openedExt || undefined,
          width: doc.dimensions?.width,
          height: doc.dimensions?.height,
          dpi: doc.dimensions?.dpi,
          isSaved: true,
          handle: fileHandle,
        }).catch(console.warn);

        showToast(
          openedExt === '.sora'
            ? t('Migrated legacy {name} (read-only) — save as .ink', { name: file.name })
            : restoredTimelapse.enabled
              ? restoredTimelapse.frameCount > 0
                ? t('Opened {name} — time-lapse resumed ({count} frames)', {
                    name: file.name,
                    count: restoredTimelapse.frameCount,
                  })
                : t('Opened {name} — time-lapse resumed', { name: file.name })
              : t('Opened {name}', { name: file.name })
        );
      } catch (err: unknown) {
        console.error('Failed to open file:', err);
        const errMsg = err instanceof Error ? err.message : String(err);
        void uiStoreActions.alertDialog({
          title: t('Could Not Open File'),
          message: t('Could not open "{name}".', { name: file.name }),
          detail: errMsg || t('Unsupported or corrupted file.'),
        });
      } finally {
        uiStoreActions.setLoading(false, '');
        if (fileInputRef.current) {
          fileInputRef.current.value = '';
        }
      }
    },
    [loadDocument, resetHistory, resetZoomAndCenter, showToast]
  );

  const handleSelectDocument = useCallback(
    (id: string) => {
      const storeState = useDocumentStore.getState();
      if (id === storeState.activeDocumentId) {
        uiStoreActions.setAppView('workspace');
        return;
      }
      const doc = storeState.documents.find((d) => d.id === id);
      if (!doc) return;
      if (useUiStore.getState().isResizeCanvasModalOpen) {
        uiStoreActions.setResizeCanvasModalOpen(false);
      }
      uiStoreActions.setAppView('workspace');
      documentStoreActions.setDimensions(doc.dimensions);
      documentStoreActions.setColorMode(doc.colorMode);
      documentStoreActions.setDocumentName(doc.name);
      if (doc.defaultFrequency) {
        setDefaultToneFrequency(doc.defaultFrequency);
      }
      if (doc.savedFileInfo && doc.savedFileInfo.extension) {
        documentStoreActions.setSavedFileInfo({
          name: doc.savedFileInfo.name,
          handle: doc.savedFileInfo.handle,
          ...(doc.savedFileInfo.path ? { path: doc.savedFileInfo.path } : {}),
          extension: doc.savedFileInfo.extension,
        });
      } else {
        documentStoreActions.setSavedFileInfo(null);
      }
      switchDocumentSession(id, doc.layers || [], doc.activeLayerId || '', doc.dimensions);
      documentStoreActions.setActiveDocumentId(id);
      documentStoreActions.setPerspectiveRuler(doc.perspectiveRuler ?? null, {
        recordHistory: false,
      });
      documentStoreActions.setStraightRuler(doc.straightRuler ?? null, { recordHistory: false });
      needsAdaptiveFitRef.current = true;
      pendingFitDimsRef.current = doc.dimensions;
      resetZoomAndCenter(doc.dimensions);
    },
    [resetZoomAndCenter, setDefaultToneFrequency, switchDocumentSession]
  );

  const handleCloseDocument = useCallback(
    (id: string) => {
      const storeState = useDocumentStore.getState();
      const curActiveId = storeState.activeDocumentId;
      if (id === curActiveId && useUiStore.getState().isResizeCanvasModalOpen) {
        uiStoreActions.setResizeCanvasModalOpen(false);
      }
      const next = storeState.documents.filter((d) => d.id !== id);
      documentStoreActions.setDocuments(next);
      if (id === curActiveId) {
        if (next.length > 0) {
          const nextActive = next[next.length - 1];
          documentStoreActions.setDimensions(nextActive.dimensions);
          documentStoreActions.setColorMode(nextActive.colorMode);
          documentStoreActions.setDocumentName(nextActive.name);
          documentStoreActions.setPerspectiveRuler(nextActive.perspectiveRuler ?? null, {
            recordHistory: false,
          });
          documentStoreActions.setStraightRuler(nextActive.straightRuler ?? null, {
            recordHistory: false,
          });
          if (nextActive.savedFileInfo && nextActive.savedFileInfo.extension) {
            documentStoreActions.setSavedFileInfo({
              name: nextActive.savedFileInfo.name,
              handle: nextActive.savedFileInfo.handle,
              ...(nextActive.savedFileInfo.path ? { path: nextActive.savedFileInfo.path } : {}),
              extension: nextActive.savedFileInfo.extension,
            });
          } else {
            documentStoreActions.setSavedFileInfo(null);
          }
          if (nextActive.layers && nextActive.layers.length > 0) {
            switchDocumentSession(
              nextActive.id,
              nextActive.layers,
              nextActive.activeLayerId || '',
              nextActive.dimensions
            );
            documentStoreActions.setActiveDocumentId(nextActive.id);
            needsAdaptiveFitRef.current = true;
            pendingFitDimsRef.current = nextActive.dimensions;
            resetZoomAndCenter(nextActive.dimensions);
          } else {
            documentStoreActions.setActiveDocumentId(nextActive.id);
            clearDocument();
          }
        } else {
          documentStore.setActiveDocument(null);
          documentStoreActions.setActiveDocumentId(null);
          documentStoreActions.setDocumentName('');
          documentStoreActions.setSavedFileInfo(null);
          clearDocument();
          documentStoreActions.setPerspectiveRuler(null, { recordHistory: false });
          documentStoreActions.setStraightRuler(null, { recordHistory: false });
          uiStoreActions.setAppView('home');
        }
      }
      if (id) {
        artworkTimeTracker.removeDocument(id);
        globalTimelapseManager.detachSession(id).catch(console.warn);
        documentStore.closeSession(id).catch(console.warn);
        recoveryService.closeSession(id).catch(console.warn);
        if (isNativeCanvasActive()) {
          void closeNativeDocument(id);
        }
      }
    },
    [clearDocument, resetZoomAndCenter, switchDocumentSession]
  );

  const handleRestoreCrashedSession = useCallback(
    async (session: CrashedSessionInfo) => {
      try {
        // Phase 6 Zero-Copy Rust Recovery: replays INKG v1 snapshot + TD v1 WAL directly in Rust!
        const restoredMeta = await nativeRecoveryRestore(
          session.session_id,
          session.session_id
        );
        const restoredLayers = restoredMeta.layers.map(fromNativeLayerNodeMeta);
        const restoredDims: CanvasDimensions = restoredMeta.dimensions;
        const restoredPersp = (restoredMeta.perspectiveRuler as any) ?? null;
        const restoredStraight = (restoredMeta.straightRuler as any) ?? null;
        const restoredAnim = (restoredMeta.animationTimeline as any) ?? null;
        loadDocument(
          {
            name: restoredMeta.name,
            dimensions: restoredDims,
            colorMode: restoredMeta.colorMode,
            layers: restoredLayers,
          },
          session.session_id,
          true
        );
        if (restoredMeta.activeLayerId) {
          setActiveLayerId(restoredMeta.activeLayerId);
        }
        documentStoreActions.setDimensions(restoredDims);
        documentStoreActions.setColorMode(restoredMeta.colorMode);
        documentStoreActions.setDocumentName(restoredMeta.name);
        documentStoreActions.setSavedFileInfo(null);
        documentStoreActions.setPerspectiveRuler(restoredPersp, { recordHistory: false });
        documentStoreActions.setStraightRuler(restoredStraight, { recordHistory: false });
        documentStoreActions.setAnimationTimeline(restoredAnim);
        if (typeof restoredMeta.defaultToneFrequency === 'number' && restoredMeta.defaultToneFrequency > 0) {
          setDefaultToneFrequency(restoredMeta.defaultToneFrequency);
        }
        const restoredWorkTimeMs = sanitizeWorkTimeMs(restoredMeta.workTimeMs);
        artworkTimeTracker.initDocument(session.session_id, restoredWorkTimeMs);
        const restoredDoc: DocumentTab = {
          id: session.session_id,
          name: restoredMeta.name,
          isDirty: true,
          dimensions: restoredDims,
          colorMode: restoredMeta.colorMode,
          defaultFrequency: restoredMeta.defaultToneFrequency || undefined,
          layers: restoredLayers,
          activeLayerId: restoredMeta.activeLayerId || restoredLayers[0]?.id || '',
          perspectiveRuler: restoredPersp,
          straightRuler: restoredStraight,
          animation: restoredAnim ?? undefined,
          workTimeMs: restoredWorkTimeMs,
        };
        documentStoreActions.setDocuments((prev) => {
          const filtered = prev.filter((d) => d.id !== session.session_id);
          return [restoredDoc, ...filtered];
        });
        documentStoreActions.setActiveDocumentId(session.session_id);
        uiStoreActions.setAppView('workspace');
        needsAdaptiveFitRef.current = true;
        pendingFitDimsRef.current = restoredDims;
        resetZoomAndCenter(restoredDims);
        uiStoreActions.setRecoveryModal(false);
        uiStoreActions.setCrashedSessions((prev) =>
          prev.filter((s) => s.session_id !== session.session_id)
        );
        showToast(t('Restored "{name}"', { name: restoredMeta.name }));
      } catch (err: unknown) {
        console.error('[Recovery] Restore error:', err);
        const msg = err instanceof Error ? err.message : String(err);
        void uiStoreActions.alertDialog({
          title: t('Recovery Failed'),
          message: t('Failed to restore crashed session.'),
          detail: msg,
        });
      }
    },
    [loadDocument, resetZoomAndCenter, setDefaultToneFrequency, showToast, setActiveLayerId]
  );

  const handleDiscardCrashedSession = useCallback(
    async (session: CrashedSessionInfo) => {
      try {
        await recoveryService.discardCrashedSession(session.session_id);
        await globalTimelapseManager.removeSession(session.session_id).catch(() => {});
        let remainingCount = 0;
        uiStoreActions.setCrashedSessions((prev) => {
          const next = prev.filter((s) => s.session_id !== session.session_id);
          remainingCount = next.length;
          return next;
        });
        if (remainingCount === 0) {
          uiStoreActions.setRecoveryModal(false);
        }
        showToast(t('Crashed session discarded'));
      } catch (err: unknown) {
        console.warn('[Recovery] Discard error:', err);
      }
    },
    [showToast]
  );

  const handleDiscardAllCrashedSessions = useCallback(
    async (sessionsToDiscard: CrashedSessionInfo[]) => {
      if (!sessionsToDiscard || sessionsToDiscard.length === 0) {
        uiStoreActions.setCrashedSessions([]);
        uiStoreActions.setRecoveryModal(false);
        return;
      }
      try {
        const sessionIds = sessionsToDiscard.map((s) => s.session_id);
        const { discardedIds, failedIds } =
          await recoveryService.discardAllCrashedSessions(sessionIds);
        const discardedSet = new Set(discardedIds);

        await Promise.allSettled(
          discardedIds.map((sessionId) => globalTimelapseManager.removeSession(sessionId))
        );

        let remainingCount = 0;
        uiStoreActions.setCrashedSessions((prev) => {
          const next = prev.filter((s) => !discardedSet.has(s.session_id));
          remainingCount = next.length;
          return next;
        });
        if (remainingCount === 0) {
          uiStoreActions.setRecoveryModal(false);
        }

        if (failedIds.length > 0) {
          showToast(
            t('Discarded {discarded} of {total} crashed sessions', {
              discarded: discardedIds.length,
              total: sessionIds.length,
            })
          );
        } else {
          showToast(
            discardedIds.length === 1
              ? t('Crashed session discarded')
              : t('Discarded all {count} crashed sessions', { count: discardedIds.length })
          );
        }
      } catch (err: unknown) {
        console.warn('[Recovery] Discard all error:', err);
      }
    },
    [showToast]
  );

  const handleRenameDocument = useCallback(
    (id: string, newName: string) => {
      documentStoreActions.setDocuments((prev) =>
        prev.map((d) => (d.id === id ? { ...d, name: newName } : d))
      );
      globalTimelapseManager.setDocumentName(id, newName);
      if (id === activeDocumentId) {
        documentStoreActions.setDocumentName(newName);
      }
    },
    [activeDocumentId]
  );

  const handleTriggerOpenFile = useCallback(() => {
    const pickerWindow = typeof window !== 'undefined' ? (window as PickerWindow) : undefined;
    if (pickerWindow && typeof pickerWindow.showOpenFilePicker === 'function') {
      void pickerWindow
        .showOpenFilePicker({
          types: OPEN_FILE_PICKER_TYPES.map((item) => ({
            ...item,
            description: t(item.description),
          })),
          multiple: false,
        })
        .then(async ([handle]) => {
          if (!handle) return;
          const file = await handle.getFile();
          await handleProcessFile(file, { handle });
        })
        .catch((err: unknown) => {
          if (err && typeof err === 'object' && 'name' in err && err.name === 'AbortError') {
            return;
          }
          console.warn('showOpenFilePicker failed, falling back to file input:', err);
          fileInputRef.current?.click();
        });
      return;
    }
    fileInputRef.current?.click();
  }, [handleProcessFile]);

  const handleFileInputChange = useCallback(
    (e: React.ChangeEvent<HTMLInputElement>) => {
      const file = e.target.files?.[0];
      if (file) {
        handleProcessFile(file);
      }
    },
    [handleProcessFile]
  );

  const buildSaveData = useCallback(
    (onProgress?: (p: SaveProgress) => void): SaveDocumentData => {
      const docStoreState = useDocumentStore.getState();
      const curDocId = docStoreState.activeDocumentId || activeDocumentId;
      const cleanNameForSave = sanitizeDocumentStem(
        docStoreState.documentName || documentName,
        'Untitled'
      );
      const liveLayers = layersRef.current;
      const tlMeta = globalTimelapseManager.getRecoveryMetadata(curDocId);
      artworkTimeTracker.flush(curDocId);
      const workTimeMs = artworkTimeTracker.getWorkTimeMs(curDocId);
      return {
        name: cleanNameForSave,
        dimensions: docStoreState.dimensions,
        colorMode: docStoreState.colorMode,
        layers: liveLayers,
        getEffectiveOpacity: (layer) => computeEffectiveOpacityForLayers(liveLayers, layer),
        isLayerEffectivelyVisible: (layer) => computeLayerVisibleForLayers(liveLayers, layer),
        tabId: curDocId || undefined,
        perspectiveRuler: docStoreState.perspectiveRuler,
        straightRuler: docStoreState.straightRuler,
        animationTimeline: docStoreState.animationTimeline,
        timelapse: tlMeta,
        timelapseFrameProvider: globalTimelapseManager.createPersistenceProvider(curDocId),
        workTimeMs,
        onProgress,
      };
    },
    [activeDocumentId, documentName]
  );

  const handleSaveDocumentById = useCallback(
    async (docId: string): Promise<SaveDocumentResult> => {
      if (savingDocIdsRef.current.has(docId)) {
        return 'canceled';
      }
      const storeState = useDocumentStore.getState();
      const targetDoc = storeState.documents.find((d) => d.id === docId);
      if (!targetDoc) return 'error';

      savingDocIdsRef.current.add(docId);
      try {
        const isActive = storeState.activeDocumentId === docId;
        const docLayers = isActive ? layersRef.current : targetDoc.layers;
        const docDims = isActive ? storeState.dimensions : targetDoc.dimensions;
        const docColorMode = isActive ? storeState.colorMode : targetDoc.colorMode;
        const docSavedInfo = isActive
          ? storeState.savedFileInfo ?? targetDoc.savedFileInfo ?? null
          : targetDoc.savedFileInfo ?? null;
        const cleanNameForSave = sanitizeDocumentStem(
          docSavedInfo?.name || targetDoc.name,
          'Untitled'
        );
        const tlMeta = globalTimelapseManager.getRecoveryMetadata(docId);
        artworkTimeTracker.flush(docId);
        const docWorkTimeMs = artworkTimeTracker.getWorkTimeMs(docId);

        const onProgress = (p: SaveProgress) => {
          uiStoreActions.setLoading(true, `${p.message} (${p.percent}%)`);
        };

        const docData: SaveDocumentData = {
          name: cleanNameForSave,
          dimensions: docDims,
          colorMode: docColorMode,
          layers: docLayers,
          getEffectiveOpacity: (layer) => computeEffectiveOpacityForLayers(docLayers, layer),
          isLayerEffectivelyVisible: (layer) => computeLayerVisibleForLayers(docLayers, layer),
          tabId: docId,
          perspectiveRuler: isActive
            ? storeState.perspectiveRuler
            : targetDoc.perspectiveRuler ?? null,
          straightRuler: isActive
            ? storeState.straightRuler
            : targetDoc.straightRuler ?? null,
          animationTimeline:
            targetDoc.animation !== undefined
              ? targetDoc.animation
              : isActive
                ? storeState.animationTimeline
                : null,
          timelapse: tlMeta,
          timelapseFrameProvider: globalTimelapseManager.createPersistenceProvider(docId),
          workTimeMs: docWorkTimeMs,
          onProgress,
        };

        const preferredExt =
          docSavedInfo?.extension && docSavedInfo.extension.toLowerCase() !== '.sora'
            ? docSavedInfo.extension
            : '.ink';
        const initialDir = getParentDirectory(docSavedInfo?.path ?? targetDoc.sourcePath);

        const applySavedMetadata = (
          info: {
            name: string;
            handle?: any;
            path?: string;
            extension: string;
            size?: number;
            previewDataUrl?: string;
          },
          updateHandle: boolean
        ) => {
          const latestActiveId = useDocumentStore.getState().activeDocumentId;
          if (latestActiveId === docId) {
            if (updateHandle) {
              documentStoreActions.setSavedFileInfo(info);
            }
            documentStoreActions.setDocumentName(info.name);
          }
          documentStoreActions.setDocuments((prev) =>
            prev.map((d) =>
              d.id === docId
                ? {
                    ...d,
                    name: info.name,
                    dimensions: docDims,
                    colorMode: docColorMode,
                    ...(updateHandle ? { savedFileInfo: info } : {}),
                    ...(info.path ? { sourcePath: info.path } : {}),
                    isDirty: false,
                    workTimeMs: docWorkTimeMs,
                  }
                : d
            )
          );
          globalTimelapseManager.linkDocumentSave(docId, {
            documentName: info.name,
            sourcePath: info.path || `InkStudio\\${info.name}`,
          });
          saveRecentDocument({
            id: docId,
            title: info.name,
            path: info.path || `InkStudio\\${info.name}`,
            size: info.size || 1572864,
            coverUrl: info.previewDataUrl || docLayers[0]?.thumbnailUrl,
            isStarred: false,
            fileType: info.extension,
            width: docDims?.width,
            height: docDims?.height,
            dpi: docDims?.dpi,
            isSaved: true,
            handle: info.handle,
          }).catch(console.warn);
          showToast(t('Saved to {name}', { name: info.name }));
        };

        const hasDirectTarget = Boolean(
          docSavedInfo?.handle || isRealNativeDiskPath(docSavedInfo?.path)
        );

        // Phase 2 Native Rust Direct `.ink` Save: reads sparse tiles straight from crates/ink-engine
        // with Rayon parallel compression and atomic disk write — ZERO JS pixel transfer!
        if (isNativeCanvasActive() && preferredExt.toLowerCase() === '.ink') {
          try {
            uiStoreActions.setLoading(true, t('Saving .ink project...'));
            const nativeSave =
              hasDirectTarget && isRealNativeDiskPath(docSavedInfo?.path)
                ? await saveNativeInkDocument(docId, docSavedInfo!.path!)
                : await saveNativeInkDocumentWithDialog(
                    docId,
                    `${cleanNameForSave}.ink`,
                    initialDir
                  );
            if (!nativeSave.path) {
              return 'canceled';
            }
            const fileName = nativeSave.path.split(/[\\/]/).pop() || `${cleanNameForSave}.ink`;
            applySavedMetadata(
              {
                name: fileName,
                path: nativeSave.path,
                extension: '.ink',
                size: nativeSave.bytesWritten,
                previewDataUrl: nativeSave.previewDataUrl ?? undefined,
              },
              true
            );
            void recoveryService.markCleanSaved(docId);
            return 'saved';
          } catch (err: unknown) {
            const msg = err instanceof Error ? err.message : String(err);
            void uiStoreActions.alertDialog({
              title: t('Save Failed'),
              message: t('Failed to save file.'),
              detail: msg,
            });
            return 'error';
          } finally {
            uiStoreActions.setLoading(false, '');
          }
        }

        if (!hasDirectTarget || docSavedInfo?.extension?.toLowerCase() === '.sora') {
          try {
            const info = await promptSaveAs(docData, preferredExt, true, { initialDir });
            applySavedMetadata(info, true);
            return 'saved';
          } catch (err: unknown) {
            const msg = err instanceof Error ? err.message : String(err);
            if (msg === 'Save canceled') {
              return 'canceled';
            }
            void uiStoreActions.alertDialog({
              title: t('Save Failed'),
              message: t('Failed to save file.'),
              detail: msg,
            });
            return 'error';
          } finally {
            uiStoreActions.setLoading(false, '');
          }
        }

        try {
          const saveRes = await saveToExistingHandle(docData, docSavedInfo!);
          applySavedMetadata(
            {
              name: docSavedInfo!.name,
              handle: docSavedInfo!.handle,
              ...(docSavedInfo!.path ? { path: docSavedInfo!.path } : {}),
              extension: docSavedInfo!.extension,
              size: saveRes.size,
              previewDataUrl: saveRes.previewDataUrl,
            },
            false
          );
          return 'saved';
        } catch (err: unknown) {
          console.warn('Direct handle/path save failed, prompting with Save As:', err);
          try {
            const info = await promptSaveAs(docData, preferredExt, true, { initialDir });
            applySavedMetadata(info, true);
            return 'saved';
          } catch (e: unknown) {
            const msg = e instanceof Error ? e.message : String(e);
            if (msg === 'Save canceled') {
              return 'canceled';
            }
            void uiStoreActions.alertDialog({
              title: t('Save Failed'),
              message: t('Failed to save file.'),
              detail: msg,
            });
            return 'error';
          }
        } finally {
          uiStoreActions.setLoading(false, '');
        }
      } finally {
        savingDocIdsRef.current.delete(docId);
      }
    },
    [showToast]
  );

  const handleSave = useCallback(async () => {
    const currentId = useDocumentStore.getState().activeDocumentId;
    if (!currentId) return;
    await handleSaveDocumentById(currentId);
  }, [handleSaveDocumentById]);

  const handleSaveAs = useCallback(async () => {
    const currentId = activeDocumentId;
    if (currentId && savingDocIdsRef.current.has(currentId)) return;
    if (currentId) savingDocIdsRef.current.add(currentId);

    const onProgress = (p: SaveProgress) => {
      uiStoreActions.setLoading(true, `${p.message} (${p.percent}%)`);
    };
    const docData = buildSaveData(onProgress);

    try {
      const defaultExt =
        savedFileInfo?.extension && savedFileInfo.extension.toLowerCase() !== '.sora'
          ? savedFileInfo.extension
          : '.ink';
      const activeDoc = useDocumentStore
        .getState()
        .documents.find((d) => d.id === activeDocumentId);
      const initialDir = getParentDirectory(savedFileInfo?.path ?? activeDoc?.sourcePath);

      const info = await promptSaveAs(docData, defaultExt, true, { initialDir });
      const targetDocId = currentId || activeDocumentId;
      if (useDocumentStore.getState().activeDocumentId === targetDocId) {
        documentStoreActions.setSavedFileInfo(info);
        documentStoreActions.setDocumentName(info.name);
      }
      documentStoreActions.setDocuments((prev) =>
        prev.map((d) =>
          d.id === targetDocId
            ? {
                ...d,
                name: info.name,
                dimensions: docData.dimensions,
                colorMode: docData.colorMode,
                savedFileInfo: info,
                ...(info.path ? { sourcePath: info.path } : {}),
                isDirty: false,
                workTimeMs: docData.workTimeMs,
              }
            : d
        )
      );
      if (targetDocId) {
        void recoveryService.markCleanSaved(targetDocId).catch(console.warn);
      }
      globalTimelapseManager.linkDocumentSave(targetDocId, {
        documentName: info.name,
        sourcePath: info.path || `InkStudio\\${info.name}`,
      });
      saveRecentDocument({
        id: targetDocId || `doc-${Date.now()}`,
        title: info.name,
        path: info.path || `InkStudio\\${info.name}`,
        size: info.size || 1572864,
        coverUrl: info.previewDataUrl || docData.layers[0]?.thumbnailUrl,
        isStarred: false,
        fileType: info.extension,
        width: docData.dimensions.width,
        height: docData.dimensions.height,
        dpi: docData.dimensions.dpi,
        isSaved: true,
        handle: info.handle,
      }).catch(console.warn);
      showToast(t('Saved as {name}', { name: info.name }));
    } catch (err: unknown) {
      const msg = err instanceof Error ? err.message : String(err);
      if (msg !== 'Save canceled') {
        void uiStoreActions.alertDialog({
          title: t('Save Failed'),
          message: t('Failed to save file.'),
          detail: msg,
        });
      }
    } finally {
      if (currentId) savingDocIdsRef.current.delete(currentId);
      uiStoreActions.setLoading(false, '');
    }
  }, [activeDocumentId, buildSaveData, savedFileInfo, showToast]);

  const handleExportImage = useCallback(async () => {
    const cleanNameForSave = sanitizeDocumentStem(documentName, 'artwork');
    const onProgress = (p: SaveProgress) => {
      uiStoreActions.setLoading(true, `${p.message} (${p.percent}%)`);
    };
    const docData = buildSaveData(onProgress);
    const activeDoc = useDocumentStore
      .getState()
      .documents.find((d) => d.id === activeDocumentId);
    const initialDir = getParentDirectory(savedFileInfo?.path ?? activeDoc?.sourcePath);

    try {
      const exportedName = await promptExportPngImage(docData, cleanNameForSave, { initialDir });
      showToast(t('Exported image to {name}', { name: exportedName }));
    } catch (err: unknown) {
      const msg = err instanceof Error ? err.message : String(err);
      if (msg !== 'Export canceled') {
        void uiStoreActions.alertDialog({
          title: t('Export Failed'),
          message: t('Failed to export image.'),
          detail: msg,
        });
      }
    } finally {
      uiStoreActions.setLoading(false, '');
    }
  }, [activeDocumentId, buildSaveData, documentName, savedFileInfo?.path, showToast]);

  const handleSelectWelcomeDocument = useCallback(
    async (doc: RecentDocument) => {
      const openDocs = useDocumentStore.getState().documents;
      const openDoc =
        openDocs.find((d) => d.id === doc.id) ??
        (doc.path ? findOpenDocumentBySourcePath(openDocs, doc.path) : undefined);
      if (openDoc) {
        handleSelectDocument(openDoc.id);
        return;
      }

      if (doc.handle && typeof doc.handle.getFile === 'function') {
        try {
          let permission: 'granted' | 'denied' | 'prompt' = 'granted';
          if (typeof doc.handle.queryPermission === 'function') {
            permission = await doc.handle.queryPermission({ mode: 'read' });
            if (permission !== 'granted' && typeof doc.handle.requestPermission === 'function') {
              permission = await doc.handle.requestPermission({ mode: 'read' });
            }
          }
          if (permission === 'granted') {
            const file = await doc.handle.getFile();
            await handleProcessFile(file, {
              handle: doc.handle,
              sourcePath: doc.path,
              docId: doc.id,
              isStarred: doc.isStarred,
            });
            return;
          }
          showToast(t('Permission denied to open "{title}"', { title: doc.title }));
          return;
        } catch (err) {
          console.warn('Direct FileSystemFileHandle read failed:', err);
        }
      }

      if (typeof window !== 'undefined' && (window as TauriWindow).__TAURI_INTERNALS__ && doc.path) {
        try {
          const { invoke } = await import('@tauri-apps/api/core');
          let bytes: Uint8Array;
          try {
            const buf = await invoke<ArrayBuffer>('read_file_binary', { path: doc.path });
            bytes = buf instanceof Uint8Array ? buf : new Uint8Array(buf);
          } catch (binErr) {
            const msg = binErr instanceof Error ? binErr.message : String(binErr);
            if (msg.toLowerCase().includes('not found') || msg.toLowerCase().includes('unknown')) {
              const arr = await invoke<number[]>('read_file_from_disk', { path: doc.path });
              bytes = new Uint8Array(arr);
            } else {
              throw binErr;
            }
          }
          if (bytes.byteLength > 0) {
            const copy = new Uint8Array(bytes.byteLength);
            copy.set(bytes);
            const file = new File([copy.buffer], doc.title, { type: 'application/octet-stream' });
            await handleProcessFile(file, {
              sourcePath: doc.path,
              docId: doc.id,
              isStarred: doc.isStarred,
            });
            return;
          }
        } catch (err) {
          console.warn('Direct disk read via Tauri failed:', err);
        }
      }

      showToast(t('Cannot reopen "{title}" directly — select the file to open', { title: doc.title }));
      handleTriggerOpenFile();
    },
    [handleProcessFile, handleSelectDocument, handleTriggerOpenFile, showToast]
  );

  const handleOpenFilePaths = useCallback(
    (paths: readonly string[]): Promise<void> => {
      const validPaths = paths.filter(
        (p): p is string => typeof p === 'string' && p.trim().length > 0
      );
      if (validPaths.length === 0) return Promise.resolve();

      const run = async () => {
        for (const filePath of validPaths) {
          // If this file is already open in a tab, focus that tab instead of duplicating it.
          const existing = findOpenDocumentBySourcePath(
            useDocumentStore.getState().documents,
            filePath
          );
          if (existing) {
            handleSelectDocument(existing.id);
            showToast(t('Switched to {name}', { name: existing.name }));
            continue;
          }

          try {
            const file = await readTauriPathAsFile(filePath);
            await handleProcessFile(file, { sourcePath: filePath });
          } catch (err: unknown) {
            console.error('Failed to open file from OS path:', filePath, err);
            const errMsg = err instanceof Error ? err.message : String(err);
            void uiStoreActions.alertDialog({
              title: t('Could Not Open File'),
              message: t('Could not open "{name}".', { name: filePath }),
              detail: errMsg || t('File could not be read.'),
            });
          }
        }
      };

      const next = openFileQueueRef.current.then(run, run);
      openFileQueueRef.current = next;
      return next;
    },
    [handleProcessFile, handleSelectDocument, showToast]
  );

  return {
    fileInputRef,
    pasteFileInputRef,
    import3DFileInputRef,
    needsAdaptiveFitRef,
    pendingFitDimsRef,
    autoCreatedInitialDocIdRef,
    handleViewportReady,
    handleCreateNewCanvas,
    handleCopySelectedLayer,
    handlePasteSelectedLayer,
    handleDeleteSelectedLayer,
    handleTriggerPasteFromFile,
    handlePasteFileInputChange,
    handleTriggerImport3DFile,
    handleImport3DFileInputChange,
    handleResizeCanvas,
    handleUpdateSettings,
    handleProcessFile,
    handleOpenFilePaths,
    handleSelectDocument,
    handleCloseDocument,
    handleRestoreCrashedSession,
    handleDiscardCrashedSession,
    handleDiscardAllCrashedSessions,
    handleRenameDocument,
    handleTriggerOpenFile,
    handleFileInputChange,
    handleSave,
    handleSaveDocumentById,
    handleSaveAs,
    handleExportImage,
    handleSelectWelcomeDocument,
  };
}

export interface DocumentLifecycleManagerProps {
  layers: LayerItem[];
  activeLayerId: string;
  needsAdaptiveFitRef: React.MutableRefObject<boolean>;
  pendingFitDimsRef: React.MutableRefObject<CanvasDimensions | null>;
  autoCreatedInitialDocIdRef?: React.MutableRefObject<string | null>;
  resetToNewCanvas: (
    dims: CanvasDimensions,
    bgColor: string,
    mode: CanvasColorMode,
    defaultFreq: number,
    docId: string
  ) => { layers: LayerItem[]; activeLayerId: string };
  resetZoomAndCenter: (dims?: CanvasDimensions) => void;
  resetHistory: (targetDocumentId?: string) => void;
  onSelectDocument: (id: string) => void;
  onOpenFilePaths?: (paths: readonly string[]) => Promise<void>;
}

/**
 * Headless lifecycle coordinator: handles startup crash recovery detection,
 * OS file-association launch & single-instance file open events, initial canvas creation,
 * WAL checkpointing, tile memory budget sync, active document tab metadata synchronization,
 * and app close confirmation guard.
 */
export const DocumentLifecycleManager: React.FC<DocumentLifecycleManagerProps> = React.memo(
  ({
    layers,
    activeLayerId,
    needsAdaptiveFitRef,
    pendingFitDimsRef,
    autoCreatedInitialDocIdRef,
    resetToNewCanvas,
    resetZoomAndCenter,
    resetHistory,
    onSelectDocument,
    onOpenFilePaths,
  }) => {
    const documents = useDocumentStore((s) => s.documents);
    const activeDocumentId = useDocumentStore((s) => s.activeDocumentId);
    const dimensions = useDocumentStore((s) => s.dimensions);
    const colorMode = useDocumentStore((s) => s.colorMode);
    const documentName = useDocumentStore((s) => s.documentName);
    const appSettings = useUiStore((s) => s.appSettings);
    const appClosePrompt = useUiStore((s) => s.appClosePrompt);
    const appView = useUiStore((s) => s.appView);
    const isLoadingFile = useUiStore((s) => s.isLoadingFile);

    // 1. Scan for unfinalized crashed WAL sessions on launch
    useEffect(() => {
      recoveryService
        .checkForCrashedSessions()
        .then((sessions) => {
          if (sessions && sessions.length > 0) {
            uiStoreActions.setRecoveryModal(true, sessions);
          }
        })
        .catch((err) => {
          console.warn('[Recovery] Error scanning for crashed sessions:', err);
        });
    }, []);

    // 2. Synchronize tile RAM, undo RAM, inactive tab offload, and memory telemetry hooks
    useEffect(() => {
      documentStore.setTileBudgetMb(appSettings.tileMemoryBudgetMb || 1024);
      documentStore.setSharedUndoRamStepsBudget(appSettings.undoRamSteps || 15);
      documentStore.setOffloadInactiveUndoOnSwitch(appSettings.offloadInactiveTabs);
      const syncNativeBudget = () => {
        if (!isNativeCanvasActive()) return;
        void setNativeMemoryBudget({
          ramBudgetMb: appSettings.tileMemoryBudgetMb || 1024,
          vramBudgetMb: vramBudgetMbFromPreset(appSettings.gpuTexturePoolPreset),
          maxHistorySteps: appSettings.maxHistorySteps || 50,
          offloadInactiveTabs: appSettings.offloadInactiveTabs !== false,
        });
      };
      syncNativeBudget();
      return subscribeNativeCanvasActive((active) => {
        if (active) syncNativeBudget();
      });
    }, [
      appSettings.tileMemoryBudgetMb,
      appSettings.gpuTexturePoolPreset,
      appSettings.maxHistorySteps,
      appSettings.undoRamSteps,
      appSettings.offloadInactiveTabs,
    ]);

    useEffect(() => {
      let cachedNativeStats: NativeMemoryStats | null = null;
      const refreshNativeMemoryStats = async () => {
        if (!isNativeCanvasActive()) return null;
        const stats = await getNativeMemoryStats();
        if (stats) {
          cachedNativeStats = stats;
        }
        return stats;
      };
      void refreshNativeMemoryStats();

      performanceManager.registerMemoryHooks({
        getActiveTileBytes: () => cachedNativeStats?.ramTotalBytes ?? 0,
        getTileBudgetBytes: () =>
          (cachedNativeStats && cachedNativeStats.ramBudgetBytes > 0
            ? cachedNativeStats.ramBudgetBytes
            : null) ??
          (useUiStore.getState().appSettings.tileMemoryBudgetMb || 1024) * 1024 * 1024,
        getUndoStats: () => documentStore.getUndoMemoryStats(),
        getActiveSessionIds: () => documentStore.getActiveSessionIds(),
        purgeTiles: async () => {
          if (isNativeCanvasActive()) {
            const stats = await purgeNativeMemory();
            if (stats) cachedNativeStats = stats;
          }
          return documentStore.purgeTileMemory();
        },
        purgeUndo: () => documentStore.purgeUndoMemory(),
        flushBrushGpuCaches: () => {
          if (isNativeCanvasActive()) {
            void flushNativeGpuPool();
          }
        },
        refreshNativeMemoryStats,
      });

      let cancelled = false;
      const current = useUiStore.getState().appSettings;
      if (current.autoOptimizePerformance !== false) {
        performanceManager
          .detectHardwareInfo(false)
          .then((hw) => {
            if (cancelled) return;
            const latest = useUiStore.getState().appSettings;
            if (latest.autoOptimizePerformance === false) return;
            const rec = computeRecommendedSettings(hw);
            const next: AppSettings = { ...latest, ...rec.settings };
            const changed = (
              Object.keys(rec.settings) as Array<keyof AppSettings>
            ).some((k) => latest[k] !== next[k]);
            if (changed) {
              uiStoreActions.updateAppSettings(next);
              documentStore.setTileBudgetMb(next.tileMemoryBudgetMb || 1024);
              documentStore.setSharedUndoRamStepsBudget(next.undoRamSteps || 15);
              documentStore.setOffloadInactiveUndoOnSwitch(next.offloadInactiveTabs);
            }
            void performanceManager.syncDesktopBackendConfig(next);
          })
          .catch(() => {
            void performanceManager.syncDesktopBackendConfig(current);
          });
      } else {
        void performanceManager.syncDesktopBackendConfig(current);
      }

      return () => {
        cancelled = true;
        performanceManager.registerMemoryHooks(null);
      };
    }, []);

    // 3. Open OS-associated launch files (cold + single-instance warm events) or auto-create initial white canvas
    const hasAutoCreatedInitialDocRef = useRef(false);
    const onOpenFilePathsRef = useRef(onOpenFilePaths);
    onOpenFilePathsRef.current = onOpenFilePaths;

    const createInitialBlankCanvas = useCallback(() => {
      if (useDocumentStore.getState().documents.length > 0) return;
      const latestSettings = useUiStore.getState().appSettings;
      const initDims: CanvasDimensions = {
        width: latestSettings.defaultWidth || 1920,
        height: latestSettings.defaultHeight || 1080,
        dpi: latestSettings.defaultDpi || 300,
      };
      const initColorMode = latestSettings.defaultColorMode || 'color';
      const initBg = latestSettings.defaultBgColor || '#ffffff';
      const initName = 'Untitled*';
      const newDocId = `doc-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`;
      documentStoreActions.setDimensions(initDims);
      documentStoreActions.setColorMode(initColorMode);
      documentStoreActions.setDocumentName(initName);
      const { layers: initialLayers, activeLayerId: topId } = resetToNewCanvas(
        initDims,
        initBg,
        initColorMode,
        60,
        newDocId
      );
      needsAdaptiveFitRef.current = true;
      pendingFitDimsRef.current = initDims;
      resetZoomAndCenter(initDims);
      resetHistory(newDocId);
      artworkTimeTracker.initDocument(newDocId, 0);
      if (autoCreatedInitialDocIdRef) {
        autoCreatedInitialDocIdRef.current = newDocId;
      }
      documentStoreActions.setDocuments([
        {
          id: newDocId,
          name: initName,
          dimensions: initDims,
          colorMode: initColorMode,
          layers: initialLayers,
          activeLayerId: topId,
          perspectiveRuler: null,
          defaultFrequency: 60,
          workTimeMs: 0,
        },
      ]);
      documentStoreActions.setActiveDocumentId(newDocId);
      uiStoreActions.setAppView('workspace');
    }, [
      autoCreatedInitialDocIdRef,
      needsAdaptiveFitRef,
      pendingFitDimsRef,
      resetHistory,
      resetToNewCanvas,
      resetZoomAndCenter,
    ]);

    useEffect(() => {
      if (!isTauriEnvironment()) {
        if (hasAutoCreatedInitialDocRef.current || useDocumentStore.getState().documents.length > 0) {
          return;
        }
        hasAutoCreatedInitialDocRef.current = true;
        createInitialBlankCanvas();
        return;
      }

      let disposed = false;
      let unlisten: (() => void) | undefined;

      void (async () => {
        // 1) Attach single-instance warm open-file listener FIRST so no event is missed
        const stop = await listenForOpenFiles((paths) => {
          if (disposed) return;
          void onOpenFilePathsRef.current?.(paths);
        });
        if (disposed) {
          stop();
          return;
        }
        unlisten = stop;

        // 2) Atomically mark frontend ready and drain any cold-launch OS file args (e.g. double-clicked .ink)
        const pendingPaths = await takePendingOpenFiles();
        if (disposed) return;

        if (pendingPaths.length > 0 && onOpenFilePathsRef.current) {
          hasAutoCreatedInitialDocRef.current = true;
          await onOpenFilePathsRef.current(pendingPaths);
          if (disposed) return;
          // Fall back to a blank canvas only if none of the launch files opened a document tab
          // (e.g. launching with a `.inkb` brush or `.cls` color set, or a corrupt file).
          if (useDocumentStore.getState().documents.length === 0) {
            createInitialBlankCanvas();
          }
          return;
        }

        if (!hasAutoCreatedInitialDocRef.current && useDocumentStore.getState().documents.length === 0) {
          hasAutoCreatedInitialDocRef.current = true;
          createInitialBlankCanvas();
        }
      })();

      return () => {
        disposed = true;
        unlisten?.();
      };
    }, [createInitialBlankCanvas]);

    // 4. Sync active document recovery session & WAL periodic checkpointing
    const recoveryStateRef = useRef({
      documents,
      documentName,
      dimensions,
      colorMode,
      layers,
      activeLayerId,
    });
    recoveryStateRef.current = {
      documents,
      documentName,
      dimensions,
      colorMode,
      layers,
      activeLayerId,
    };

    useEffect(() => {
      if (!activeDocumentId) return;
      const st = recoveryStateRef.current;
      const initDoc = st.documents.find((d) => d.id === activeDocumentId);
      if (!initDoc) return;

      recoveryService.initSession(activeDocumentId, () => {
        const cur = recoveryStateRef.current;
        const doc = cur.documents.find((d) => d.id === activeDocumentId);
        return {
          sessionId: activeDocumentId,
          documentName: doc?.name || cur.documentName || 'Untitled Document',
          width: cur.dimensions.width || doc?.dimensions.width || 1920,
          height: cur.dimensions.height || doc?.dimensions.height || 1080,
          dpi: cur.dimensions.dpi || doc?.dimensions.dpi || 600,
          colorMode: cur.colorMode || doc?.colorMode || 'color',
          layers: cur.layers.length > 0 ? cur.layers : doc?.layers || [],
          activeLayerId: cur.activeLayerId || doc?.activeLayerId || '',
          timestamp: Date.now(),
          workTimeMs: artworkTimeTracker.getWorkTimeMs(activeDocumentId),
          timelapse: globalTimelapseManager.getRecoveryMetadata(activeDocumentId),
        };
      });
    }, [activeDocumentId]);

    // 5. Keep active document tab's metadata (layers, activeLayerId, dimensions, colorMode) in sync
    useEffect(() => {
      if (!activeDocumentId) return;
      documentStoreActions.setActiveLayerId(activeLayerId);
      documentStoreActions.setDocuments((prev) => {
        const curr = prev.find((d) => d.id === activeDocumentId);
        if (!curr) return prev;
        const dimsSame =
          curr.dimensions.width === dimensions.width &&
          curr.dimensions.height === dimensions.height &&
          curr.dimensions.dpi === dimensions.dpi;
        if (
          curr.layers === layers &&
          curr.activeLayerId === activeLayerId &&
          dimsSame &&
          curr.colorMode === colorMode
        ) {
          return prev;
        }
        return prev.map((d) =>
          d.id === activeDocumentId
            ? {
                ...d,
                layers,
                activeLayerId,
                dimensions: dimsSame ? d.dimensions : dimensions,
                colorMode,
              }
            : d
        );
      });
    }, [layers, activeLayerId, activeDocumentId, dimensions, colorMode]);

    // 6. Intercept OS/window close requests (Alt+F4, taskbar close, WM close) and protect
    //    against accidental page reloads (Ctrl+R, Cmd+R, F5, context-menu Reload, browser back/forward)
    //    in BOTH Tauri desktop and web browser environments.
    useEffect(() => {
      const uninstallReloadGuard = installReloadGuard({
        getDocuments: () => useDocumentStore.getState().documents,
        isFinalizingClose: () => isFinalizingAppClose(),
        isDrawingActive: () => recoveryService.getIsDrawingActive(),
        shouldNotifyBlockedKey: (e) => {
          const uiState = useUiStore.getState();
          if (uiState.isSettingsModalOpen) return false;
          const matched = shortcutManager.matchEvent(e, uiState.appSettings.shortcuts);
          return !matched;
        },
        onBlockedReloadShortcut: () => {
          const docs = useDocumentStore.getState().documents;
          const hasDirty = docs.some((d) => Boolean(d.isDirty));
          uiStoreActions.showToast(
            hasDirty
              ? t('Page reload blocked to protect unsaved artwork')
              : t('Page reload is disabled in Ink Studio')
          );
        },
      });

      if (!isTauriEnvironment()) {
        return uninstallReloadGuard;
      }

      let disposed = false;
      let unlisten: (() => void) | undefined;

      void import('@tauri-apps/api/window')
        .then(({ getCurrentWindow }) =>
          getCurrentWindow().onCloseRequested((event) => {
            if (isFinalizingAppClose()) return;
            event.preventDefault();
            requestAppClose();
          })
        )
        .then((fn) => {
          if (disposed) {
            fn();
          } else {
            unlisten = fn;
          }
        })
        .catch((err) => {
          console.warn('Failed to register Tauri close-requested guard:', err);
        });

      return () => {
        disposed = true;
        if (unlisten) unlisten();
        uninstallReloadGuard();
      };
    }, []);

    // 7. Focus the canvas currently being confirmed during the per-canvas save prompt
    const pendingCloseDocId =
      appClosePrompt.isOpen && appClosePrompt.step === 'per-canvas'
        ? appClosePrompt.pendingDocIds[appClosePrompt.currentIndex] ?? null
        : null;
    useEffect(() => {
      if (!pendingCloseDocId) return;
      onSelectDocument(pendingCloseDocId);
    }, [pendingCloseDocId, onSelectDocument]);

    // 8. Smart, action-gated artwork time tracking (never starts until genuine artwork action; adapts to drawing cadence)
    const isWorkspaceTimeTrackable = Boolean(
      activeDocumentId && appView === 'workspace' && !isLoadingFile
    );

    useEffect(() => {
      artworkTimeTracker.setActiveDocument(activeDocumentId, isWorkspaceTimeTrackable);
    }, [activeDocumentId, isWorkspaceTimeTrackable]);

    // Detect genuine layer structure/property edits on the active document (ignores doc switch / initial mount)
    const lastTrackedLayersRef = useRef<{ docId: string | null; layers: LayerItem[] }>({
      docId: null,
      layers,
    });
    useEffect(() => {
      if (!isWorkspaceTimeTrackable || !activeDocumentId) {
        lastTrackedLayersRef.current = { docId: activeDocumentId, layers };
        return;
      }
      const prev = lastTrackedLayersRef.current;
      if (prev.docId === activeDocumentId && hasMeaningfulLayerEdit(prev.layers, layers)) {
        artworkTimeTracker.recordArtworkAction(activeDocumentId);
      }
      lastTrackedLayersRef.current = { docId: activeDocumentId, layers };
    }, [activeDocumentId, isWorkspaceTimeTrackable, layers]);

    // Detect genuine native Rust canvas pixel/stroke mutations (strokes, undo/redo, paste, filters, tonal edits, fills)
    useEffect(() => {
      if (!isWorkspaceTimeTrackable || !activeDocumentId) return;
      return subscribeNativeStrokeCommitted((ev) => {
        if (!ev.docId || ev.docId === activeDocumentId) {
          artworkTimeTracker.recordArtworkAction(activeDocumentId);
        }
      });
    }, [activeDocumentId, isWorkspaceTimeTrackable]);

    useEffect(() => {
      if (!isWorkspaceTimeTrackable || typeof window === 'undefined' || typeof document === 'undefined') {
        return;
      }

      const isFocusedNow = () =>
        document.visibilityState === 'visible' &&
        (typeof document.hasFocus !== 'function' || document.hasFocus());

      artworkTimeTracker.setWindowFocused(isFocusedNow());

      let lastSupportReportAt = 0;
      let lastStylusReportAt = 0;

      const isInsideInfoPanel = (target: EventTarget | null): boolean => {
        if (!target || typeof Element === 'undefined' || !(target instanceof Element)) {
          return false;
        }
        return Boolean(target.closest('[data-testid="info-panel"]'));
      };

      // Supporting workspace interactions (zoom, shortcuts, tool/color clicks, active drags):
      // NEVER wake an idle timer; only sustain an already-active artwork session up to the safety cap.
      const handleSupportingEvent = (e: Event) => {
        if (isInsideInfoPanel(e.target)) return;
        const now = typeof performance !== 'undefined' ? performance.now() : Date.now();
        if (now - lastSupportReportAt >= 350) {
          lastSupportReportAt = now;
          artworkTimeTracker.recordSupportingActivity();
        }
      };

      const handlePointerMove = (e: PointerEvent) => {
        // Hovering without holding a button never counts as activity
        if (e.buttons === 0 || isInsideInfoPanel(e.target)) return;
        const now = typeof performance !== 'undefined' ? performance.now() : Date.now();
        if (now - lastSupportReportAt >= 350) {
          lastSupportReportAt = now;
          artworkTimeTracker.recordSupportingActivity();
        }
      };

      // Native WinTab / Windows Ink stylus pressure stream (bypasses DOM pointer events)
      const handleCanvasPointerStat = (e: Event) => {
        const detail = (e as CustomEvent<{ x: number | null; y: number | null; pressure: number }>)
          .detail;
        if (!detail || (detail.pressure ?? 0) <= 0) return;
        const now = typeof performance !== 'undefined' ? performance.now() : Date.now();
        if (now - lastStylusReportAt >= 350) {
          lastStylusReportAt = now;
          artworkTimeTracker.recordArtworkAction();
        }
      };

      const handleBlur = () => {
        artworkTimeTracker.setWindowFocused(false);
      };

      const handleFocus = () => {
        artworkTimeTracker.setWindowFocused(document.visibilityState === 'visible');
      };

      const handleVisibilityChange = () => {
        artworkTimeTracker.setWindowFocused(isFocusedNow());
      };

      window.addEventListener('pointerdown', handleSupportingEvent, { passive: true });
      window.addEventListener('pointermove', handlePointerMove, { passive: true });
      window.addEventListener('wheel', handleSupportingEvent, { passive: true });
      window.addEventListener('keydown', handleSupportingEvent, { passive: true });
      window.addEventListener('canvas-pointer-stat', handleCanvasPointerStat);
      window.addEventListener('blur', handleBlur);
      window.addEventListener('focus', handleFocus);
      document.addEventListener('visibilitychange', handleVisibilityChange);

      return () => {
        artworkTimeTracker.flush();
        window.removeEventListener('pointerdown', handleSupportingEvent);
        window.removeEventListener('pointermove', handlePointerMove);
        window.removeEventListener('wheel', handleSupportingEvent);
        window.removeEventListener('keydown', handleSupportingEvent);
        window.removeEventListener('canvas-pointer-stat', handleCanvasPointerStat);
        window.removeEventListener('blur', handleBlur);
        window.removeEventListener('focus', handleFocus);
        document.removeEventListener('visibilitychange', handleVisibilityChange);
      };
    }, [isWorkspaceTimeTrackable]);

    return null;
  }
);

DocumentLifecycleManager.displayName = 'DocumentLifecycleManager';