Skip to content

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

80.5 KB
Raw Blame
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import {
  AnimationTimeline,
  BlendMode,
  DocumentStateDelta,
  ExpressionColor,
  FilterType,
  LayerColorLabel,
  LayerItem,
  LayerTreeDelta,
} from './types/editor';
import {
  createDefaultAnimationTimeline,
  removeFrameCel,
  setFrameCel,
} from './utils/animationEngine';
import { screenToCanvas } from './utils/canvasUtils';
import { createDefaultPageFrame } from './utils/frameEngine';
import { AutoAction, AutoActionExecutionContext, executeAutoAction } from './utils/autoActionEngine';
import { globalTimelapseManager, TimelapseLiveCaptureContext } from './utils/timelapseEngine';
import {
  addNativeLayer,
  clearNativeLayer,
  nativeSelectionFillColor,
  updateNativeLayer,
} from './utils/nativeEngineBridge';
import { multiplayerService } from './services/multiplayerService';
import { recoveryService } from './services/recoveryService';
import { updaterService } from './services/updaterService';
import { useCanvasDrawing } from './hooks/useCanvasDrawing';
import {
  PushHistoryStepFn,
  useGradientTool,
  usePenTool,
  useRetouchTool,
  useSelectionTools,
  useShapeAndFillTools,
  useVectorDrawing,
} from './hooks/drawing';
import { useCanvasNavigation } from './hooks/useCanvasNavigation';
import { createLayerTreeSnapshotDelta, useLayerManager } from './hooks/useLayerManager';
import { useCollabSync } from './hooks/useCollabSync';
import { useTonalAndFilterActions } from './hooks/useTonalAndFilterActions';
import { useAppMenuSections } from './hooks/useAppMenuSections';
import { useExternalFileDrop } from './hooks/useExternalFileDrop';
import {
  autoActionStoreActions,
  documentStoreActions,
  scene3DBridge,
  selectHasOpenDocument,
  toolStoreActions,
  uiStoreActions,
  use3DStore,
  useDocumentStore,
  useToolStore,
  useUiStore,
} from './stores';
import {
  DocumentLifecycleManager,
  useDocumentLifecycle,
} from './components/DocumentLifecycleManager';
import { GlobalShortcutListener } from './components/GlobalShortcutListener';
import { ModalHost } from './components/ModalHost';
import { AppShell } from './components/AppShell';
import { t, tc } from './i18n';

function cloneAnimationTimelineForHistory(
  timeline: AnimationTimeline | null | undefined
): AnimationTimeline | null {
  if (!timeline) return null;
  return {
    ...timeline,
    cels: { ...timeline.cels },
    onionSkin: { ...timeline.onionSkin },
    isPlaying: false,
  };
}

function analyzeAnimationTimelineDiff(
  before: AnimationTimeline | null,
  after: AnimationTimeline | null
): { changed: boolean; label: string; coalesceKey?: string } {
  if (!before && !after) return { changed: false, label: '' };
  if (!before && after) return { changed: true, label: t('Enable Animation Timeline') };
  if (before && !after) return { changed: true, label: t('Disable Animation Timeline') };
  if (!before || !after) return { changed: false, label: '' };

  if (JSON.stringify(before.cels) !== JSON.stringify(after.cels)) {
    return { changed: true, label: t('Update Animation Cels') };
  }
  if (
    before.fps !== after.fps ||
    before.totalFrames !== after.totalFrames ||
    Boolean(before.loop) !== Boolean(after.loop) ||
    JSON.stringify(before.onionSkin) !== JSON.stringify(after.onionSkin)
  ) {
    return {
      changed: true,
      label: t('Update Animation Timeline'),
      coalesceKey: 'animation-timeline-settings',
    };
  }
  return { changed: false, label: '' };
}

export function App() {
  const dimensions = useDocumentStore((s) => s.dimensions);
  const colorMode = useDocumentStore((s) => s.colorMode);
  const documents = useDocumentStore((s) => s.documents);
  const activeDocumentId = useDocumentStore((s) => s.activeDocumentId);
  const hasOpenDocument = useDocumentStore(selectHasOpenDocument);
  const softProofSettings = useDocumentStore((s) => s.softProofSettings);
  const perspectiveRuler = useDocumentStore((s) => s.perspectiveRuler);
  const straightRuler = useDocumentStore((s) => s.straightRuler);
  const activeEditTarget = useDocumentStore((s) => s.activeEditTarget);
  const animationTimeline = useDocumentStore((s) => s.animationTimeline);
  const isWebtoonMode = useUiStore((s) => s.isWebtoonMode);
  const is3DLayerOpen = useUiStore((s) => s.is3DLayerOpen);
  const canUndo3D = use3DStore((s) => s.canUndo3D);
  const canRedo3D = use3DStore((s) => s.canRedo3D);
  const appView = useUiStore((s) => s.appView);

  // Delayed silent startup check for desktop Tauri updates (never blocks startup or crash recovery)
  useEffect(() => {
    return updaterService.scheduleStartupUpdateCheck(4500);
  }, []);

  const selectiveUndoRef = useRef<(peerId?: string | number, strokeId?: string) => unknown>(() => {});
  const pushHistoryStepRef = useRef<PushHistoryStepFn | null>(null);
  const resetHistoryRef = useRef<((targetDocumentId?: string) => void) | null>(null);
  const flushPendingHistoryTasksRef = useRef<() => void>(() => {});
  const showToast = uiStoreActions.showToast;

  // Layer Management System
  const layerMgr = useLayerManager({
    dimensions,
    activeSessionId: activeDocumentId,
    pushHistoryStepRef,
  });

  const activeDoc = documents.find((d) => d.id === activeDocumentId);
  const activeAnimationTimeline =
    activeDoc?.animation !== undefined ? activeDoc.animation : animationTimeline;

  const applyAnimationTimelineState = useCallback(
    (timeline: AnimationTimeline | null, markDirty = true) => {
      documentStoreActions.setAnimationTimeline(timeline);
      const docId = useDocumentStore.getState().activeDocumentId;
      if (docId) {
        documentStoreActions.setDocuments((docs) =>
          docs.map((d) =>
            d.id === docId
              ? { ...d, animation: timeline, ...(markDirty ? { isDirty: true } : {}) }
              : d
          )
        );
      }
    },
    []
  );

  const handleUpdateAnimationTimeline = useCallback(
    (timeline: AnimationTimeline | null) => {
      const beforeTl = activeAnimationTimeline ?? null;
      const diff = analyzeAnimationTimelineDiff(beforeTl, timeline);
      applyAnimationTimelineState(timeline, diff.changed);
      if (diff.changed) {
        pushHistoryStepRef.current?.(
          'animation',
          diff.label,
          null,
          null,
          layerMgr.activeLayerId || '',
          undefined,
          undefined,
          undefined,
          undefined,
          undefined,
          false,
          undefined,
          {
            beforeAnimationTimeline: cloneAnimationTimelineForHistory(beforeTl),
            afterAnimationTimeline: cloneAnimationTimelineForHistory(timeline),
            ...(diff.coalesceKey ? { coalesceKey: diff.coalesceKey } : {}),
          }
        );
      }
    },
    [activeAnimationTimeline, applyAnimationTimelineState, layerMgr.activeLayerId]
  );

  const handleAddAnimationCel = useCallback(
    (frameIndex: number) => {
      const beforeLayers = layerMgr.layers;
      const beforeActiveLayerId = layerMgr.activeLayerId;
      const beforeTl = activeAnimationTimeline ?? null;
      const newLayerId = `layer-cel-${Date.now()}-${Math.random().toString(36).substring(2, 6)}`;
      const newCelLayer: LayerItem = {
        id: newLayerId,
        name: t('Cel Frame {n}', { n: frameIndex + 1 }),
        type: 'raster',
        visible: true,
        opacity: 1,
        blendMode: 'normal',
        locked: false,
        collapsed: false,
        parentId: null,
      };
      if (activeDocumentId) {
        void addNativeLayer(activeDocumentId, newCelLayer, 0, true);
      }

      const nextLayers = [newCelLayer, ...beforeLayers];
      layerMgr.setLayers(nextLayers);
      layerMgr.setActiveLayerId(newLayerId);

      const currentTl = beforeTl || createDefaultAnimationTimeline(beforeLayers);
      const nextTl = setFrameCel(currentTl, frameIndex, newLayerId);
      applyAnimationTimelineState(nextTl, true);

      pushHistoryStepRef.current?.(
        'animation',
        t('Add Cel Frame {n}', { n: frameIndex + 1 }),
        null,
        null,
        newLayerId,
        undefined,
        undefined,
        undefined,
        undefined,
        undefined,
        false,
        createLayerTreeSnapshotDelta(beforeLayers, nextLayers, beforeActiveLayerId, newLayerId),
        {
          beforeAnimationTimeline: cloneAnimationTimelineForHistory(beforeTl),
          afterAnimationTimeline: cloneAnimationTimelineForHistory(nextTl),
        }
      );

      showToast(t('Cel added for frame {n}', { n: frameIndex + 1 }));
    },
    [activeAnimationTimeline, activeDocumentId, applyAnimationTimelineState, layerMgr, showToast]
  );

  const handleDeleteAnimationCel = useCallback(
    (frameIndex: number) => {
      if (!activeAnimationTimeline) return;
      const beforeTl = activeAnimationTimeline;
      const nextTl = removeFrameCel(beforeTl, frameIndex);
      applyAnimationTimelineState(nextTl, true);
      pushHistoryStepRef.current?.(
        'animation',
        t('Remove Cel Frame {n}', { n: frameIndex + 1 }),
        null,
        null,
        layerMgr.activeLayerId || '',
        undefined,
        undefined,
        undefined,
        undefined,
        undefined,
        false,
        undefined,
        {
          beforeAnimationTimeline: cloneAnimationTimelineForHistory(beforeTl),
          afterAnimationTimeline: cloneAnimationTimelineForHistory(nextTl),
        }
      );
      showToast(t('Cel removed from frame {n}', { n: frameIndex + 1 }));
    },
    [activeAnimationTimeline, applyAnimationTimelineState, layerMgr.activeLayerId, showToast]
  );

  // Canvas Navigation
  const nav = useCanvasNavigation({
    dimensions,
    isWebtoonMode,
    activeDocumentId,
  });

  const stableResetHistory = useCallback((targetDocumentId?: string) => {
    resetHistoryRef.current?.(targetDocumentId);
  }, []);

  // Multiplayer & Collaborative Layer Sync
  const collab = useCollabSync({
    hasOpenDocument,
    dimensions,
    colorMode,
    layers: layerMgr.layers,
    activeLayerId: layerMgr.activeLayerId,
    selectedLayerIds: layerMgr.selectedLayerIds,
    perspectiveRuler,
    straightRuler,
    animationTimeline: activeAnimationTimeline,
    pushHistoryStepRef,
    selectiveUndoRef,
    resetZoomAndCenter: nav.resetZoomAndCenter,
    navigation: nav.navigation,
    viewportRef: nav.viewportRef,
    resetHistory: stableResetHistory,
    setLayers: layerMgr.setLayers,
    setActiveLayerId: layerMgr.setActiveLayerId,
    toggleLock: layerMgr.toggleLock,
    addLayer: layerMgr.addLayer,
    addRemoteLayer: layerMgr.addRemoteLayer,
    deleteLayer: layerMgr.deleteLayer,
    deleteRemoteLayer: layerMgr.deleteRemoteLayer,
    applyRemoteLayerUpdate: layerMgr.applyRemoteLayerUpdate,
    applyRemoteLayerTree: layerMgr.applyRemoteLayerTree,
    applyRemoteMaskData: layerMgr.applyRemoteMaskData,
    deleteSelectedLayers: layerMgr.deleteSelectedLayers,
    groupSelectedLayers: layerMgr.groupSelectedLayers,
    syncRemoteDocument: layerMgr.syncRemoteDocument,
    resizeCanvas: layerMgr.resizeCanvas,
    renameLayer: layerMgr.renameLayer,
    toggleVisibility: layerMgr.toggleVisibility,
    setOpacity: layerMgr.setOpacity,
    clearActiveLayer: layerMgr.clearActiveLayer,
    updateLayerThumbnail: layerMgr.updateLayerThumbnail,
    showToast,
  });

  const stableFlushPendingHistoryTasks = useCallback(
    () => flushPendingHistoryTasksRef.current(),
    []
  );
  const stablePushHistoryStep = useCallback<PushHistoryStepFn>(
    (...args) => {
      pushHistoryStepRef.current?.(...args);
    },
    []
  );

  const handleSyncNativeLayersFromSelection = useCallback(
    (nextLayers: LayerItem[], nextActiveLayerId?: string) => {
      layerMgr.layersRef.current = nextLayers;
      layerMgr.setLayers(nextLayers);
      if (nextActiveLayerId) {
        layerMgr.setActiveLayerId(nextActiveLayerId);
      }
    },
    [layerMgr.layersRef, layerMgr.setLayers, layerMgr.setActiveLayerId]
  );

  // Modular Selection & Transform Tools (mounted before useCanvasDrawing so selection is always synchronous)
  const selectionTools = useSelectionTools({
    dimensions,
    colorMode,
    layers: layerMgr.layers,
    activeLayer: layerMgr.activeLayer,
    activeLayerId: layerMgr.activeLayerId,
    selectedLayerIds: layerMgr.selectedLayerIds,
    flushPendingHistoryTasks: stableFlushPendingHistoryTasks,
    updateLayerThumbnail: layerMgr.updateLayerThumbnail,
    pushHistoryStep: stablePushHistoryStep,
    onSyncNativeLayers: handleSyncNativeLayersFromSelection,
    showToast,
  });

  const handleCollabStrokeStart = useCallback(
    (
      strokeId: string,
      layerId: string,
      bs: import('./types/editor').BrushSettings,
      t: import('./types/editor').ToolType,
      startPt: import('./types/editor').Point
    ) => {
      if (multiplayerService.isConnected()) {
        multiplayerService.sendStrokeStart(strokeId, layerId, bs, t, startPt);
      }
    },
    []
  );

  const handleCollabStrokeChunk = useCallback(
    (strokeId: string, pts: import('./types/editor').Point[]) => {
      if (multiplayerService.isConnected()) {
        multiplayerService.sendStrokeChunk(strokeId, pts);
      }
    },
    []
  );

  const handleCollabStrokeFinish = useCallback(
    (
      strokeId: string,
      layerId: string,
      endPt: import('./types/editor').Point,
      dirty?: import('./types/editor').DirtyRect,
      vectorStroke?: import('./types/editor').VectorStroke
    ) => {
      if (multiplayerService.isConnected()) {
        multiplayerService.sendStrokeFinish(strokeId, layerId, endPt, dirty, vectorStroke);
      }
    },
    []
  );

  const handleCollabCursorMove = useCallback(
    (x: number, y: number, isDrawing: boolean, t: import('./types/editor').ToolType) => {
      if (multiplayerService.isConnected()) {
        multiplayerService.sendCursor(x, y, isDrawing, t);
      }
    },
    []
  );

  // Auto-reset mask edit mode if active layer no longer has a mask
  const effectiveIsMaskMode =
    activeEditTarget === 'mask' &&
    Boolean(layerMgr.activeLayer?.hasMask || layerMgr.activeLayer?.maskCanvas);
  useEffect(() => {
    if (
      activeEditTarget === 'mask' &&
      !(layerMgr.activeLayer?.hasMask || layerMgr.activeLayer?.maskCanvas)
    ) {
      documentStoreActions.setActiveEditTarget('layer');
    }
  }, [activeEditTarget, layerMgr.activeLayer]);

  // Cancel transform session if all of its target layers were deleted.
  useEffect(() => {
    const ts = selectionTools.transformSession;
    if (!ts?.active) return;
    const targetIds = ts.layerIds && ts.layerIds.length > 0 ? ts.layerIds : [ts.layerId];
    const hasAnyTarget = targetIds.some((id) => layerMgr.layers.some((l) => l.id === id));
    if (!hasAnyTarget) {
      selectionTools.handleCancelTransform();
    }
  }, [selectionTools.transformSession, selectionTools.handleCancelTransform, layerMgr.layers]);

  const activeLayerIdForHistoryRef = useRef(layerMgr.activeLayerId);
  activeLayerIdForHistoryRef.current = layerMgr.activeLayerId;

  // Register ruler history recorder so perspective & straight ruler edits are undoable with Ctrl+Z
  useEffect(() => {
    documentStoreActions.setRulerHistoryRecorder((label, delta) => {
      const docId = useDocumentStore.getState().activeDocumentId;
      if (!docId) return;
      pushHistoryStepRef.current?.(
        'ruler',
        label,
        null,
        null,
        activeLayerIdForHistoryRef.current || '',
        undefined,
        undefined,
        undefined,
        undefined,
        undefined,
        false,
        undefined,
        delta
      );
      documentStoreActions.markDocumentDirty(docId, true);
    });
    return () => {
      documentStoreActions.setRulerHistoryRecorder(null);
    };
  }, []);

  const handleApplyDocumentStateDelta = useCallback(
    (delta: DocumentStateDelta, direction: 'undo' | 'redo') => {
      const activeId = useDocumentStore.getState().activeDocumentId;
      if (delta.beforeDimensions !== undefined || delta.afterDimensions !== undefined) {
        const targetDims = direction === 'undo' ? delta.beforeDimensions : delta.afterDimensions;
        if (targetDims) {
          documentStoreActions.setDimensions({ ...targetDims }, activeId);
          nav.resetZoomAndCenter(targetDims);
        }
      }
      if (delta.beforePerspectiveRuler !== undefined || delta.afterPerspectiveRuler !== undefined) {
        const targetPersp =
          direction === 'undo' ? delta.beforePerspectiveRuler : delta.afterPerspectiveRuler;
        documentStoreActions.setPerspectiveRuler(
          targetPersp
            ? {
                ...targetPersp,
                grid: { ...targetPersp.grid },
                vps: targetPersp.vps.map((vp) => ({ ...vp })),
              }
            : null,
          { recordHistory: false }
        );
      }
      if (delta.beforeStraightRuler !== undefined || delta.afterStraightRuler !== undefined) {
        const targetStraight =
          direction === 'undo' ? delta.beforeStraightRuler : delta.afterStraightRuler;
        documentStoreActions.setStraightRuler(targetStraight ? { ...targetStraight } : null, {
          recordHistory: false,
        });
      }
      if (
        delta.beforeAnimationTimeline !== undefined ||
        delta.afterAnimationTimeline !== undefined
      ) {
        const targetTl =
          direction === 'undo' ? delta.beforeAnimationTimeline : delta.afterAnimationTimeline;
        applyAnimationTimelineState(cloneAnimationTimelineForHistory(targetTl ?? null), false);
      }
      if (delta.beforeSelection !== undefined || delta.afterSelection !== undefined) {
        const targetSel = direction === 'undo' ? delta.beforeSelection : delta.afterSelection;
        selectionTools.restoreSelectionFromHistory(targetSel ?? null);
      }
    },
    [applyAnimationTimelineState, nav.resetZoomAndCenter, selectionTools.restoreSelectionFromHistory]
  );

  // Thin Canvas Drawing Dispatcher (reads tool & brushSettings from useToolStore without subscribing!)
  const drawing = useCanvasDrawing({
    dimensions,
    colorMode,
    disabled:
      !hasOpenDocument ||
      nav.isSpaceDown ||
      nav.isPanning ||
      nav.isRotating ||
      nav.isZoomDragging ||
      Boolean(selectionTools.transformSession?.active) ||
      ((collab.isConnected || collab.isReconnecting) && collab.myRole === 'viewer'),
    viewportRef: nav.viewportRef,
    pan: nav.pan,
    zoom: nav.zoom,
    rotation: nav.rotation,
    flipX: nav.flipX,
    flipY: nav.flipY,
    navigation: nav.navigation,
    activeLayerId: layerMgr.activeLayerId,
    activeSessionId: activeDocumentId,
    activeLayerLocked:
      (layerMgr.activeLayer?.locked ?? false) ||
      ((collab.isConnected || collab.isReconnecting) && !collab.canEditActiveLayer),
    activeLayerVisible: layerMgr.activeLayer
      ? layerMgr.isLayerEffectivelyVisible(layerMgr.activeLayer)
      : true,
    layers: hasOpenDocument ? layerMgr.layers : [],
    onUpdateLayerThumbnail: layerMgr.updateLayerThumbnail,
    onApplyLayerTreeDelta: layerMgr.applyLayerTreeDelta,
    onApplyDocumentStateDelta: handleApplyDocumentStateDelta,
    isMaskMode: effectiveIsMaskMode,
    onUpdateMaskThumbnail: layerMgr.updateMaskThumbnail,
    onCollabStrokeStart: handleCollabStrokeStart,
    onCollabStrokeChunk: handleCollabStrokeChunk,
    onCollabStrokeFinish: handleCollabStrokeFinish,
    onCollabCursorMove: handleCollabCursorMove,
    perspectiveRuler: hasOpenDocument ? perspectiveRuler : null,
    straightRuler: hasOpenDocument ? straightRuler : null,
    onActiveConstraintAxisChange: documentStoreActions.setActiveLockedAxis,
    selection: hasOpenDocument ? selectionTools.selection : null,
  });

  selectiveUndoRef.current = drawing.selectiveUndo;
  pushHistoryStepRef.current = drawing.pushHistoryStep;
  resetHistoryRef.current = drawing.resetHistory;
  flushPendingHistoryTasksRef.current = drawing.flushPendingHistoryTasks;

  // If the active layer switches mid-stroke (e.g. via shortcut or layer create/delete),
  // cleanly abort the in-progress stroke so it cannot stall or commit to the wrong layer.
  const prevStrokeLayerIdRef = useRef(layerMgr.activeLayerId);
  const abortActiveBrushStroke = drawing.abortActiveStroke;
  const brushIsDrawingRef = drawing.isDrawingRef;
  useEffect(() => {
    if (prevStrokeLayerIdRef.current !== layerMgr.activeLayerId) {
      prevStrokeLayerIdRef.current = layerMgr.activeLayerId;
      if (brushIsDrawingRef.current) {
        abortActiveBrushStroke();
      }
    }
  }, [layerMgr.activeLayerId, abortActiveBrushStroke, brushIsDrawingRef]);

  const handleUndo = useCallback(() => {
    if ((collab.isConnected || collab.isReconnecting) && collab.myRole === 'viewer') {
      showToast(t('Viewers have read-only access'));
      return;
    }
    if (
      useUiStore.getState().is3DLayerOpen &&
      useToolStore.getState().tool === '3d' &&
      scene3DBridge.canUndo?.()
    ) {
      if (scene3DBridge.undo?.()) {
        return;
      }
    }
    if (selectionTools.transformSession?.active) {
      selectionTools.handleCancelTransform();
      return;
    }
    if (collab.isConnected && collab.myPeer.id) {
      void drawing.selectiveUndo('local').then((undone) => {
        if (!undone) return;
        if (undone.conflictNotice) {
          showToast(undone.conflictNotice);
        }
        if (!multiplayerService.isConnected() || undone.syncedRemotely) return;
        if (undone.changedLayerIds && undone.changedLayerIds.length > 0) {
          for (const lid of undone.changedLayerIds) {
            multiplayerService.streamNativeLayerTiles(lid);
          }
        } else if (undone.strokeId) {
          multiplayerService.sendSelectiveUndo(undone.strokeId);
        }
      });
    } else {
      drawing.undo();
    }
  }, [collab.isConnected, collab.isReconnecting, collab.myPeer.id, collab.myRole, drawing, selectionTools, showToast]);

  const handleRedo = useCallback(() => {
    if ((collab.isConnected || collab.isReconnecting) && collab.myRole === 'viewer') {
      showToast(t('Viewers have read-only access'));
      return;
    }
    if (
      useUiStore.getState().is3DLayerOpen &&
      useToolStore.getState().tool === '3d' &&
      scene3DBridge.canRedo?.()
    ) {
      if (scene3DBridge.redo?.()) {
        return;
      }
    }
    if (collab.isConnected && collab.myPeer.id) {
      void drawing.selectiveRedo('local').then((redone) => {
        if (!redone) return;
        if (redone.conflictNotice) {
          showToast(redone.conflictNotice);
        }
        if (!multiplayerService.isConnected() || redone.syncedRemotely) return;
        if (redone.changedLayerIds && redone.changedLayerIds.length > 0) {
          for (const lid of redone.changedLayerIds) {
            multiplayerService.streamNativeLayerTiles(lid);
          }
        }
      });
    } else {
      drawing.redo();
    }
  }, [collab.isConnected, collab.isReconnecting, collab.myPeer.id, collab.myRole, drawing, showToast]);

  const getCanvasCoords = useCallback(
    (e: React.PointerEvent<HTMLElement> | PointerEvent) => {
      if (!nav.viewportRef.current) return { x: 0, y: 0 };
      const vRect = nav.viewportRef.current.getBoundingClientRect();
      return screenToCanvas(
        e.clientX,
        e.clientY,
        vRect,
        nav.navigation.panRef.current,
        nav.navigation.zoomRef.current,
        nav.navigation.rotationRef.current,
        dimensions,
        nav.navigation.flipXRef.current,
        nav.navigation.flipYRef.current
      );
    },
    [nav.viewportRef, nav.navigation, dimensions]
  );

  // Modular Shape, Fill, Eyedropper, Text, Balloon, Frame Folder & Liquify Tools
  const shapeFillTools = useShapeAndFillTools({
    dimensions,
    colorMode,
    layers: layerMgr.layers,
    activeLayer: layerMgr.activeLayer,
    activeLayerId: layerMgr.activeLayerId,
    selectedLayerIds: layerMgr.selectedLayerIds,
    selection: selectionTools.selection,
    onCommitFloatingSelection: selectionTools.handleCommitFloatingSelection,
    flushPendingHistoryTasks: drawing.flushPendingHistoryTasks,
    isLayerEffectivelyVisible: layerMgr.isLayerEffectivelyVisible,
    getEffectiveOpacity: layerMgr.getEffectiveOpacity,
    getCanvasCoords,
    setActiveLayerId: layerMgr.setActiveLayerId,
    upsertTextLayer: layerMgr.upsertTextLayer,
    upsertBalloonLayer: layerMgr.upsertBalloonLayer,
    createFrameFolder: layerMgr.createFrameFolder,
    divideFrameFolder: layerMgr.divideFrameFolder,
    deleteLayer: collab.handleDeleteLayer,
    updateLayerThumbnail: layerMgr.updateLayerThumbnail,
    pushHistoryStep: drawing.pushHistoryStep,
    showToast,
  });

  // Modular Vector Edit Tool
  const vectorTools = useVectorDrawing({
    activeLayer: layerMgr.activeLayer,
    activeLayerId: layerMgr.activeLayerId,
    dimensions,
    colorMode,
    getCanvasCoords,
    updateLayerThumbnail: layerMgr.updateLayerThumbnail,
    pushHistoryStep: drawing.pushHistoryStep,
    showToast,
  });

  // Modular Gradient Tool (Linear / Radial / Mesh)
  const gradientTools = useGradientTool({
    dimensions,
    colorMode,
    activeLayer: layerMgr.activeLayer,
    activeLayerId: layerMgr.activeLayerId,
    selection: selectionTools.selection,
    zoomRef: nav.navigation.zoomRef,
    flushPendingHistoryTasks: drawing.flushPendingHistoryTasks,
    isLayerEffectivelyVisible: layerMgr.isLayerEffectivelyVisible,
    getCanvasCoords,
    updateLayerThumbnail: layerMgr.updateLayerThumbnail,
    pushHistoryStep: drawing.pushHistoryStep,
    showToast,
  });

  // Modular Retouch Tools (Smudge / Blur / Dodge / Burn / Clone Stamp)
  const retouchTools = useRetouchTool({
    dimensions,
    colorMode,
    layers: layerMgr.layers,
    activeLayer: layerMgr.activeLayer,
    activeLayerId: layerMgr.activeLayerId,
    selection: selectionTools.selection,
    flushPendingHistoryTasks: drawing.flushPendingHistoryTasks,
    isLayerEffectivelyVisible: layerMgr.isLayerEffectivelyVisible,
    getEffectiveOpacity: layerMgr.getEffectiveOpacity,
    getCanvasCoords,
    updateLayerThumbnail: layerMgr.updateLayerThumbnail,
    pushHistoryStep: drawing.pushHistoryStep,
    showToast,
  });

  // Modular True Cubic Bézier Pen Tool
  const penTools = usePenTool({
    dimensions,
    colorMode,
    activeLayer: layerMgr.activeLayer,
    activeLayerId: layerMgr.activeLayerId,
    selection: selectionTools.selection,
    zoomRef: nav.navigation.zoomRef,
    flushPendingHistoryTasks: drawing.flushPendingHistoryTasks,
    isLayerEffectivelyVisible: layerMgr.isLayerEffectivelyVisible,
    getCanvasCoords,
    updateLayerThumbnail: layerMgr.updateLayerThumbnail,
    pushHistoryStep: drawing.pushHistoryStep,
    showToast,
  });

  // Tonal, Filter, Adjustment, Styles, Screentone & Expression Color Actions
  const tonalActions = useTonalAndFilterActions({
    hasOpenDocument,
    dimensions,
    colorMode,
    layers: layerMgr.layers,
    activeLayer: layerMgr.activeLayer,
    activeLayerId: layerMgr.activeLayerId,
    selection: selectionTools.selection,
    setActiveLayerId: layerMgr.setActiveLayerId,
    updateLayerThumbnail: layerMgr.updateLayerThumbnail,
    handleCommitFloatingSelection: selectionTools.handleCommitFloatingSelection,
    pushHistoryStepRef,
    addLayer: layerMgr.addLayer,
    pasteLayerFromCanvas: layerMgr.pasteLayerFromCanvas,
    addAdjustmentLayer: layerMgr.addAdjustmentLayer,
    updateAdjustmentData: layerMgr.updateAdjustmentData,
    updateLayerStyles: layerMgr.updateLayerStyles,
    fillScreentoneSelection: layerMgr.fillScreentoneSelection,
    applyExpressionColorOfPreview: layerMgr.applyExpressionColorOfPreview,
    applyLayerColorPermanently: layerMgr.applyLayerColorPermanently,
    convertLayer: layerMgr.convertLayer,
    showToast,
  });

  const clearSelectionWithoutHistory = useCallback(
    () => selectionTools.handleDeselect(false),
    [selectionTools.handleDeselect]
  );
  const getCurrentSelection = useCallback(
    () => selectionTools.selection,
    [selectionTools.selection]
  );

  // Document Lifecycle Operations
  const docLifecycle = useDocumentLifecycle({
    layers: layerMgr.layers,
    activeLayer: layerMgr.activeLayer,
    activeLayerId: layerMgr.activeLayerId,
    getEffectiveOpacity: layerMgr.getEffectiveOpacity,
    isLayerEffectivelyVisible: layerMgr.isLayerEffectivelyVisible,
    setActiveLayerId: layerMgr.setActiveLayerId,
    resetToNewCanvas: layerMgr.resetToNewCanvas,
    setDefaultToneFrequency: layerMgr.setDefaultToneFrequency,
    clearDocument: layerMgr.clearDocument,
    loadDocument: layerMgr.loadDocument,
    switchDocumentSession: layerMgr.switchDocumentSession,
    resizeCanvas: layerMgr.resizeCanvas,
    copyLayer: layerMgr.copyLayer,
    pasteLayer: layerMgr.pasteLayer,
    onDeselectAfterPaste: clearSelectionWithoutHistory,
    getSelection: getCurrentSelection,
    clearSelectionWithoutHistory,
    flushPendingHistoryTasks: drawing.flushPendingHistoryTasks,
    deleteLayer: collab.handleDeleteLayer,
    pasteLayerFromFile: layerMgr.pasteLayerFromFile,
    resetZoomAndCenter: nav.resetZoomAndCenter,
    resetHistory: drawing.resetHistory,
    pushHistoryStep: drawing.pushHistoryStep,
    showToast,
  });

  const handleToggleReferenceLayer = useCallback(
    (layerId: string) => {
      if (collab.isConnected || collab.isReconnecting) {
        if (collab.myRole === 'viewer') {
          showToast(t('Viewers have read-only access'));
          return;
        }
        const perm = collab.canEditLayerById(layerId);
        if (!perm.allowed) {
          showToast(perm.reason || t('Layer is locked by its owner'));
          return;
        }
      }
      const beforeLayers = layerMgr.layersRef.current;
      const target = beforeLayers.find((l) => l.id === layerId);
      if (!target) return;
      const nextIsReference = !target.isReference;
      const nextLayers = beforeLayers.map((l) =>
        l.id === layerId ? { ...l, isReference: nextIsReference } : l
      );
      layerMgr.layersRef.current = nextLayers;
      layerMgr.setLayers(nextLayers);
      if (activeDocumentId) {
        void updateNativeLayer(activeDocumentId, layerId, {
          isReference: nextIsReference,
          recordHistory: true,
          historyLabel: t('Toggle Reference Layer'),
        }).catch(() => {});
      }
      pushHistoryStepRef.current?.(
        'layer',
        t('Toggle Reference Layer'),
        null,
        null,
        layerId,
        undefined,
        undefined,
        undefined,
        undefined,
        undefined,
        false,
        createLayerTreeSnapshotDelta(beforeLayers, nextLayers, layerMgr.activeLayerId, layerMgr.activeLayerId)
      );
      documentStoreActions.markDocumentDirty(activeDocumentId, true);
    },
    [
      activeDocumentId,
      collab.isConnected,
      collab.isReconnecting,
      collab.myRole,
      collab.canEditLayerById,
      layerMgr,
      showToast,
    ]
  );

  const handleToggleTone = useCallback(
    (layerId: string) => {
      if (selectionTools.selection?.floating) {
        selectionTools.handleCommitFloatingSelection();
      }
      layerMgr.toggleTone(layerId, selectionTools.selection);
    },
    [layerMgr.toggleTone, selectionTools]
  );

  const checkCollabLayerEdit = useCallback(
    (layerId: string): boolean => {
      if (!collab.isConnected && !collab.isReconnecting) return true;
      if (collab.myRole === 'viewer') {
        showToast(t('Viewers have read-only access'));
        return false;
      }
      const perm = collab.canEditLayerById(layerId);
      if (!perm.allowed) {
        showToast(perm.reason || t('Layer is locked by its owner'));
        return false;
      }
      return true;
    },
    [collab.isConnected, collab.isReconnecting, collab.myRole, collab.canEditLayerById, showToast]
  );

  const handleMergeDown = useCallback(() => {
    if (collab.isConnected || collab.isReconnecting) {
      if (collab.myRole === 'viewer') {
        showToast(t('Viewers have read-only access'));
        return;
      }
      const delPerm = collab.canDeleteLayerById(layerMgr.activeLayerId);
      if (!delPerm.allowed) {
        showToast(delPerm.reason || t('Cannot merge a protected layer'));
        return;
      }
      const activeIdx = layerMgr.layers.findIndex((l) => l.id === layerMgr.activeLayerId);
      const belowLayer =
        activeIdx >= 0
          ? layerMgr.layers.slice(activeIdx + 1).find((l) => l.type === 'raster')
          : undefined;
      if (belowLayer) {
        const belowPerm = collab.canEditLayerById(belowLayer.id);
        if (!belowPerm.allowed) {
          showToast(belowPerm.reason || t('Target layer below is locked by its owner'));
          return;
        }
      }
    }
    const res = layerMgr.mergeDown();
    if (res) {
      documentStoreActions.markDocumentDirty(activeDocumentId, true);
      autoActionStoreActions.recordStep('merge-down', t('Merge Down'));
      showToast(t('Merged layer down'));
    } else {
      showToast(t('Cannot merge down: need an unlocked raster layer below'));
    }
  }, [
    collab.isConnected,
    collab.isReconnecting,
    collab.myRole,
    collab.canDeleteLayerById,
    collab.canEditLayerById,
    layerMgr.activeLayerId,
    layerMgr.layers,
    layerMgr.mergeDown,
    activeDocumentId,
    showToast,
  ]);

  const handleMergeFolder = useCallback(
    (folderId?: string) => {
      const targetId = folderId || layerMgr.activeLayerId;
      if (collab.isConnected || collab.isReconnecting) {
        if (collab.myRole === 'viewer') {
          showToast(t('Viewers have read-only access'));
          return;
        }
        if (targetId) {
          const perm = collab.canDeleteLayerById(targetId);
          if (!perm.allowed) {
            showToast(perm.reason || t('Cannot merge a protected folder'));
            return;
          }
        }
      }
      if (selectionTools.selection?.floating) {
        selectionTools.handleCommitFloatingSelection();
      }
      if (selectionTools.transformSession?.active) {
        selectionTools.handleApplyTransform();
      }
      const res = layerMgr.mergeFolder(folderId);
      if (res) {
        documentStoreActions.markDocumentDirty(activeDocumentId, true);
        autoActionStoreActions.recordStep('merge-folder', t('Merge Folder'));
        showToast(t('Merged folder into layer'));
      } else {
        showToast(t('Cannot merge folder: select an unlocked folder'));
      }
    },
    [
      collab.isConnected,
      collab.isReconnecting,
      collab.myRole,
      collab.canDeleteLayerById,
      layerMgr.activeLayerId,
      layerMgr.mergeFolder,
      activeDocumentId,
      selectionTools,
      showToast,
    ]
  );

  const handleAddDefaultFrameFolder = useCallback(() => {
    drawing.flushPendingHistoryTasks();
    const dpi = dimensions.dpi ?? 600;
    const defaultFrame = createDefaultPageFrame('', dimensions.width, dimensions.height, dpi, 15);
    const { folder, layerTreeDelta } = layerMgr.createFrameFolder([defaultFrame], undefined, true);
    drawing.pushHistoryStep(
      'frame',
      t('New Frame Border Folder'),
      null,
      null,
      folder.id,
      undefined,
      undefined,
      undefined,
      undefined,
      undefined,
      undefined,
      layerTreeDelta
    );
    autoActionStoreActions.recordStep('create-frame-folder', t('New Frame Border Folder'));
    showToast(t('Created Frame Border Folder'));
  }, [dimensions, layerMgr.createFrameFolder, drawing.flushPendingHistoryTasks, drawing.pushHistoryStep, showToast]);

  const handleRasterizeLayer = useCallback(
    (layerId: string) => {
      const ok = layerMgr.rasterizeLayer(layerId);
      if (ok) {
        autoActionStoreActions.recordStep('rasterize-layer', t('Rasterize Layer'));
        showToast(t('Layer rasterized'));
      } else {
        showToast(t('Only Text, Speech Balloon, or Vector layers can be rasterized'));
      }
    },
    [layerMgr.rasterizeLayer, showToast]
  );

  // Auto-Action Recording Wrappers for common layer/filter commands
  const handleRecordedAddLayer = useCallback(
    (type: 'raster' | 'folder' = 'raster') => {
      collab.handleAddLayer(type);
      autoActionStoreActions.recordStep(
        type === 'folder' ? 'create-folder' : 'create-layer',
        type === 'folder' ? t('Create Folder') : t('Create Layer')
      );
    },
    [collab.handleAddLayer]
  );

  const handleRecordedDuplicateLayer = useCallback(
    (id: string) => {
      if ((collab.isConnected || collab.isReconnecting) && collab.myRole === 'viewer') {
        showToast(t('Viewers have read-only access'));
        return;
      }
      layerMgr.duplicateLayer(id);
      autoActionStoreActions.recordStep('duplicate-layer', t('Duplicate Layer'));
    },
    [collab.isConnected, collab.isReconnecting, collab.myRole, layerMgr.duplicateLayer, showToast]
  );

  const handleRecordedSetBlendMode = useCallback(
    (id: string, blendMode: BlendMode) => {
      if (!checkCollabLayerEdit(id)) return;
      layerMgr.setBlendMode(id, blendMode);
      autoActionStoreActions.recordStep(
        'set-blend-mode',
        t('Blend Mode: {mode}', { mode: tc('blendModeId', blendMode) }),
        { blendMode }
      );
    },
    [checkCollabLayerEdit, layerMgr.setBlendMode]
  );

  const handleRecordedSetOpacity = useCallback(
    (id: string, opacity: number) => {
      collab.handleSetOpacity(id, opacity);
      autoActionStoreActions.recordStep(
        'set-opacity',
        t('Opacity: {percent}%', { percent: Math.round(opacity * 100) }),
        {
          opacity,
        }
      );
    },
    [collab.handleSetOpacity]
  );

  const handleRecordedToggleClipping = useCallback(
    (id: string) => {
      if (!checkCollabLayerEdit(id)) return;
      layerMgr.toggleClipping(id);
      autoActionStoreActions.recordStep('toggle-clipping', t('Toggle Clipping Mask'));
    },
    [checkCollabLayerEdit, layerMgr.toggleClipping]
  );

  const handleGuardedToggleAlphaLock = useCallback(
    (id: string) => {
      if (!checkCollabLayerEdit(id)) return;
      layerMgr.toggleAlphaLock(id);
    },
    [checkCollabLayerEdit, layerMgr.toggleAlphaLock]
  );

  const handleGuardedMoveLayer = useCallback(
    (id: string, direction: 'up' | 'down') => {
      if (!checkCollabLayerEdit(id)) return;
      layerMgr.moveLayer(id, direction);
    },
    [checkCollabLayerEdit, layerMgr.moveLayer]
  );

  const handleGuardedMoveLayerToFolder = useCallback(
    (layerId: string, targetFolderId: string | null) => {
      if (!checkCollabLayerEdit(layerId)) return;
      layerMgr.moveLayerToFolder(layerId, targetFolderId);
    },
    [checkCollabLayerEdit, layerMgr.moveLayerToFolder]
  );

  const handleGuardedReorderLayers = useCallback(
    (sourceId: string, targetId: string, position: 'above' | 'below' | 'inside') => {
      if (!checkCollabLayerEdit(sourceId)) return;
      layerMgr.reorderLayers(sourceId, targetId, position);
    },
    [checkCollabLayerEdit, layerMgr.reorderLayers]
  );

  const handleGuardedToggleLayerColor = useCallback(
    (id: string) => {
      if (!checkCollabLayerEdit(id)) return;
      layerMgr.toggleLayerColor(id);
    },
    [checkCollabLayerEdit, layerMgr.toggleLayerColor]
  );

  const handleGuardedSetLayerColorLabel = useCallback(
    (id: string, colorLabel: LayerColorLabel) => {
      if (!checkCollabLayerEdit(id)) return;
      layerMgr.setLayerColorLabel(id, colorLabel);
    },
    [checkCollabLayerEdit, layerMgr.setLayerColorLabel]
  );

  const handleGuardedSoloLayer = useCallback(
    (id: string) => {
      if (!checkCollabLayerEdit(id)) return;
      layerMgr.toggleSoloLayer(id);
    },
    [checkCollabLayerEdit, layerMgr.toggleSoloLayer]
  );

  const handleGuardedAddLayerMask = useCallback(
    (...args: Parameters<typeof layerMgr.addLayerMask>) => {
      if (!checkCollabLayerEdit(args[0])) return;
      layerMgr.addLayerMask(...args);
    },
    [checkCollabLayerEdit, layerMgr.addLayerMask]
  );

  const handleGuardedRemoveLayerMask = useCallback(
    (...args: Parameters<typeof layerMgr.removeLayerMask>) => {
      if (!checkCollabLayerEdit(args[0])) return;
      layerMgr.removeLayerMask(...args);
    },
    [checkCollabLayerEdit, layerMgr.removeLayerMask]
  );

  const handleGuardedToggleLayerMask = useCallback(
    (layerId: string) => {
      if (!checkCollabLayerEdit(layerId)) return;
      layerMgr.toggleLayerMask(layerId);
    },
    [checkCollabLayerEdit, layerMgr.toggleLayerMask]
  );

  const handleGuardedToggleMaskLinked = useCallback(
    (layerId: string) => {
      if (!checkCollabLayerEdit(layerId)) return;
      layerMgr.toggleMaskLinked(layerId);
    },
    [checkCollabLayerEdit, layerMgr.toggleMaskLinked]
  );

  const handleRecordedApplyFilter = useCallback(
    (type: FilterType, params?: import('./hooks/useTonalAndFilterActions').AnyFilterParams) => {
      tonalActions.handleApplyFilter(type, params);
      autoActionStoreActions.recordStep(
        'apply-filter',
        t('Filter: {type}', { type: tc('filterId', type) }),
        {
          filterType: type,
          ...(params || {}),
        }
      );
    },
    [tonalActions.handleApplyFilter]
  );

  const handleRecordedSetExpressionColor = useCallback(
    (id: string, mode: ExpressionColor) => {
      layerMgr.setLayerExpressionColor(id, mode);
      autoActionStoreActions.recordStep(
        'set-expression-color',
        t('Expression Color: {mode}', { mode: tc('expressionColorId', mode) }),
        { mode }
      );
    },
    [layerMgr.setLayerExpressionColor]
  );

  const handlePlayAutoAction = useCallback(
    async (action: AutoAction) => {
      if (!hasOpenDocument) return;
      autoActionStoreActions.setIsPlaying(true);
      const beforeAutoLayers = layerMgr.layers;
      const beforeAutoActiveId = layerMgr.activeLayerId;
      let currentLayerId = layerMgr.activeLayerId;
      let groupTargetLayerId = currentLayerId;
      let groupLayerTreeDelta: LayerTreeDelta | undefined;

      const ctx: AutoActionExecutionContext = {
        getActiveLayerId: () => currentLayerId,
        createLayer: (name, type = 'raster') => {
          const created = layerMgr.runWithoutLayerHistory(() =>
            layerMgr.addLayer(type, undefined, name, undefined, true)
          );
          currentLayerId = created.id;
          return created.id;
        },
        createFolder: (name) => {
          const created = layerMgr.runWithoutLayerHistory(() =>
            layerMgr.addLayer('folder', undefined, name, undefined, true)
          );
          currentLayerId = created.id;
          return created.id;
        },
        createFrameFolder: (name) => {
          const dpi = dimensions.dpi ?? 600;
          const df = createDefaultPageFrame('', dimensions.width, dimensions.height, dpi, 15);
          const { folder, layerTreeDelta } = layerMgr.createFrameFolder([df], name, true);
          if (!groupLayerTreeDelta) {
            groupLayerTreeDelta = {
              addedLayers: [...(layerTreeDelta.addedLayers || [])],
              insertBeforeLayerId: layerTreeDelta.insertBeforeLayerId,
              insertIndex: layerTreeDelta.insertIndex,
              beforeActiveLayerId: layerTreeDelta.beforeActiveLayerId,
              afterActiveLayerId: layerTreeDelta.afterActiveLayerId,
            };
          } else {
            groupLayerTreeDelta.addedLayers = [
              ...(layerTreeDelta.addedLayers || []),
              ...(groupLayerTreeDelta.addedLayers || []),
            ];
            groupLayerTreeDelta.afterActiveLayerId = layerTreeDelta.afterActiveLayerId;
          }
          currentLayerId = folder.id;
          return folder.id;
        },
        duplicateLayer: (id) => layerMgr.runWithoutLayerHistory(() => layerMgr.duplicateLayer(id)),
        deleteLayer: (id) => layerMgr.runWithoutLayerHistory(() => collab.handleDeleteLayer(id)),
        renameLayer: (id, name) => layerMgr.runWithoutLayerHistory(() => layerMgr.renameLayer(id, name)),
        setBlendMode: (id, blendMode) =>
          layerMgr.runWithoutLayerHistory(() => layerMgr.setBlendMode(id, blendMode)),
        setOpacity: (id, opacity) =>
          layerMgr.runWithoutLayerHistory(() => layerMgr.setOpacity(id, opacity)),
        setVisibility: (id) => layerMgr.runWithoutLayerHistory(() => layerMgr.toggleVisibility(id)),
        setClipping: (id, clipped) => {
          const existing = layerMgr.layersRef.current.find((l) => l.id === id);
          if (clipped === undefined || Boolean(existing?.clipped) !== clipped) {
            layerMgr.runWithoutLayerHistory(() => layerMgr.toggleClipping(id));
          }
        },
        setAlphaLock: (id) => layerMgr.runWithoutLayerHistory(() => layerMgr.toggleAlphaLock(id)),
        setExpressionColor: (id, mode) =>
          layerMgr.runWithoutLayerHistory(() => layerMgr.setLayerExpressionColor(id, mode)),
        setLayerColor: (id, enabled, color) => {
          layerMgr.runWithoutLayerHistory(() => {
            if (color) layerMgr.setLayerColor(id, color);
            const existing = layerMgr.layersRef.current.find((l) => l.id === id);
            if (Boolean(existing?.layerColorEnabled) !== enabled) {
              layerMgr.toggleLayerColor(id);
            }
          });
        },
        setTone: (id, enabled, opts) => {
          layerMgr.runWithoutLayerHistory(() => {
            const existing = layerMgr.layersRef.current.find((l) => l.id === id);
            if (Boolean(existing?.toneEnabled) !== enabled) {
              layerMgr.toggleTone(id);
            }
            if (opts?.frequency !== undefined) layerMgr.setToneFrequency(id, opts.frequency);
            if (opts?.density !== undefined) {
              layerMgr.setToneDensityType(id, 'specified');
              layerMgr.setToneDensity(id, opts.density);
            }
            if (opts?.angle !== undefined) layerMgr.setToneAngle(id, opts.angle);
          });
        },
        fillLayer: (id, color) => {
          groupTargetLayerId = id;
          void nativeSelectionFillColor({ color, layerId: id, docId: activeDocumentId }).then(() => {
            layerMgr.updateLayerThumbnail(id, true);
          });
        },
        clearLayer: (id) => {
          groupTargetLayerId = id;
          if (activeDocumentId) {
            void clearNativeLayer(activeDocumentId, id, true).then(() => {
              layerMgr.updateLayerThumbnail(id, true);
            });
          }
        },
        mergeDown: () => {
          layerMgr.runWithoutLayerHistory(() => layerMgr.mergeDown());
        },
        mergeFolder: (folderId) => {
          layerMgr.runWithoutLayerHistory(() => layerMgr.mergeFolder(folderId));
        },
        rasterizeLayer: (id) => {
          layerMgr.runWithoutLayerHistory(() => layerMgr.rasterizeLayer(id));
        },
        applyFilter: (type, params) => {
          tonalActions.handleApplyFilter(
            type,
            params as unknown as import('./hooks/useTonalAndFilterActions').AnyFilterParams
          );
        },
        exportImage: () => {
          docLifecycle.handleExportImage();
        },
        endHistoryGroup: (label) => {
          const targetId = groupTargetLayerId || currentLayerId;
          const finalTreeDelta =
            groupLayerTreeDelta ??
            createLayerTreeSnapshotDelta(
              beforeAutoLayers,
              layerMgr.layersRef.current,
              beforeAutoActiveId,
              currentLayerId
            );
          drawing.pushHistoryStep(
            'auto-action',
            label,
            null,
            null,
            targetId,
            undefined,
            undefined,
            undefined,
            undefined,
            undefined,
            undefined,
            finalTreeDelta
          );
        },
      };

      try {
        const res = await executeAutoAction(action, ctx);
        if (res.errors.length > 0) {
          showToast(
            t('Auto Action "{name}" finished with {count} error(s)', {
              name: action.name,
              count: res.errors.length,
            })
          );
        } else {
          showToast(
            t('Played "{name}" ({count} steps)', {
              name: action.name,
              count: res.executedSteps,
            })
          );
        }
      } finally {
        autoActionStoreActions.setIsPlaying(false);
      }
    },
    [
      hasOpenDocument,
      activeDocumentId,
      layerMgr,
      dimensions,
      tonalActions.handleApplyFilter,
      docLifecycle.handleExportImage,
      drawing.pushHistoryStep,
      showToast,
    ]
  );

  // Time-lapse recording reactive toggle & keyframe capture on committed history steps
  const [isTimelapseRecording, setIsTimelapseRecording] = useState<boolean>(() =>
    globalTimelapseManager.isRecording(activeDocumentId)
  );
  useEffect(() => {
    setIsTimelapseRecording(globalTimelapseManager.isRecording(activeDocumentId));
    return globalTimelapseManager.subscribe(() => {
      setIsTimelapseRecording(globalTimelapseManager.isRecording(activeDocumentId));
    });
  }, [activeDocumentId]);

  const getTimelapseCaptureContext = useCallback((): TimelapseLiveCaptureContext => {
    const docState = useDocumentStore.getState();
    const uiState = useUiStore.getState();
    return {
      viewportElement: nav.viewportRef.current,
      camera: nav.navigation.getCameraState(),
      showCheckerboard: uiState.appSettings.showCheckerboard,
      valueCheckEnabled: docState.valueCheckEnabled,
      isDrawingActive: () => recoveryService.getIsDrawingActive(),
      documentName: docState.documentName,
    };
  }, [nav.viewportRef, nav.navigation]);

  const handleCaptureTimelapseNow = useCallback(() => {
    if (!activeDocumentId) return;
    globalTimelapseManager
      .captureKeyframe(
        activeDocumentId,
        layerMgr.layers,
        dimensions,
        true,
        getTimelapseCaptureContext()
      )
      .catch(() => {});
  }, [activeDocumentId, layerMgr.layers, dimensions, getTimelapseCaptureContext]);

  const handleToggleTimelapseRecording = useCallback(() => {
    if (!activeDocumentId) return;
    const docName = useDocumentStore.getState().documentName;
    const next = globalTimelapseManager.toggleRecording(activeDocumentId, docName);
    documentStoreActions.markDocumentDirty(activeDocumentId, true);
    if (next) {
      globalTimelapseManager
        .captureKeyframe(
          activeDocumentId,
          layerMgr.layers,
          dimensions,
          true,
          getTimelapseCaptureContext()
        )
        .catch(() => {});
      showToast(t('Time-lapse recording started (saved locally)'));
    } else {
      showToast(t('Time-lapse recording paused'));
    }
  }, [
    activeDocumentId,
    layerMgr.layers,
    dimensions,
    getTimelapseCaptureContext,
    showToast,
  ]);

  // Mark active document dirty & record time-lapse keyframe whenever a new history step is committed
  const lastHistoryMetaRef = useRef<{ docId: string | null; itemId: string | null }>({
    docId: null,
    itemId: null,
  });
  useEffect(() => {
    const safeHistoryList = Array.isArray(drawing.historyList) ? drawing.historyList : [];
    const currentItem =
      drawing.historyIndex >= 0 && drawing.historyIndex < safeHistoryList.length
        ? safeHistoryList[drawing.historyIndex]
        : undefined;
    const currentItemId = currentItem?.id ?? null;
    const prev = lastHistoryMetaRef.current;
    if (
      activeDocumentId &&
      prev.docId === activeDocumentId &&
      currentItemId &&
      currentItemId !== prev.itemId &&
      drawing.historyIndex > 0 &&
      currentItem?.type !== 'selection'
    ) {
      documentStoreActions.markDocumentDirty(activeDocumentId, true);
      if (globalTimelapseManager.isRecording(activeDocumentId)) {
        globalTimelapseManager
          .captureKeyframe(
            activeDocumentId,
            layerMgr.layers,
            dimensions,
            false,
            getTimelapseCaptureContext()
          )
          .catch(() => {});
      }
    }
    lastHistoryMetaRef.current = { docId: activeDocumentId, itemId: currentItemId };
  }, [
    activeDocumentId,
    drawing.historyList,
    drawing.historyIndex,
    layerMgr.layers,
    dimensions,
    getTimelapseCaptureContext,
  ]);

  // Unified Pointer Dispatcher reading tool imperatively from useToolStore.
  // Tracks which tool initiated the current pointer drag so a mid-drag tool switch
  // never leaves gradient/retouch/pen/vector-edit/selection/shape drag state stuck.
  const activePointerToolRef = useRef<ReturnType<typeof useToolStore.getState>['tool'] | null>(null);

  const handlePointerDown = useCallback(
    (e: React.PointerEvent<HTMLElement>, coalescedEvents?: PointerEvent[]) => {
      if (!hasOpenDocument || e.button !== 0) return;
      const tool = useToolStore.getState().tool;
      if (selectionTools.transformSession?.active) {
        if (tool === 'brush' || tool === 'decoration' || tool === 'eraser') {
          showToast(t('Transform active — press Enter to apply or Esc / Ctrl+Z to cancel'));
        }
        return;
      }

      // Collaborative role & owner-lock guard on canvas mutations
      if ((collab.isConnected || collab.isReconnecting) && tool !== 'pipette') {
        if (collab.myRole === 'viewer') {
          showToast(t('Viewers have read-only access'));
          return;
        }
        const editPerm = collab.canEditLayerById(layerMgr.activeLayerId);
        if (!editPerm.allowed) {
          showToast(editPerm.reason || t('Layer is locked by its owner'));
          return;
        }
      }

      activePointerToolRef.current = tool;

      if (tool === 'brush' || tool === 'decoration' || tool === 'eraser') {
        const curLayer = layerMgr.activeLayer;
        if (curLayer?.type === 'text' || curLayer?.type === 'balloon') {
          activePointerToolRef.current = null;
          showToast(t('Use Text/Object tool to edit, or Rasterize Layer to paint directly'));
          return;
        }
        if (curLayer?.type === 'frame-folder') {
          activePointerToolRef.current = null;
          showToast(t('Select a child layer inside the Frame Border Folder to draw'));
          return;
        }
        if (selectionTools.selection?.floating) {
          selectionTools.handleCommitFloatingSelection();
        }
        drawing.handlePointerDown(e, coalescedEvents);
        return;
      }

      // Compute canvas coords only for non-brush tools (avoids redundant getBoundingClientRect reflow on every brush touchdown!)
      const pt = getCanvasCoords(e);

      if (tool === 'vector-edit') {
        vectorTools.handleVectorEditPointerDown(e, pt);
        return;
      }

      if (tool === 'gradient') {
        gradientTools.handleGradientPointerDown(e, pt);
        return;
      }

      if (tool === 'retouch') {
        retouchTools.handleRetouchPointerDown(e, pt);
        return;
      }

      if (tool === 'pen') {
        penTools.handlePenPointerDown(e, pt);
        return;
      }

      if (selectionTools.handleSelectionPointerDown(e, pt)) return;
      shapeFillTools.handleShapeFillPointerDown(e, pt);
    },
    [
      hasOpenDocument,
      getCanvasCoords,
      selectionTools,
      drawing,
      vectorTools,
      gradientTools,
      retouchTools,
      penTools,
      shapeFillTools,
      collab.isConnected,
      collab.isReconnecting,
      collab.myRole,
      collab.canEditLayerById,
      layerMgr.activeLayer,
      layerMgr.activeLayerId,
      showToast,
    ]
  );

  const handlePointerMove = useCallback(
    (
      e: React.PointerEvent<HTMLElement>,
      coalescedEvents?: PointerEvent[],
      predictedEvents?: PointerEvent[]
    ) => {
      if (drawing.isDrawingRef.current) {
        drawing.handlePointerMove(e, coalescedEvents, predictedEvents);
        return;
      }
      const tool = activePointerToolRef.current ?? useToolStore.getState().tool;
      if (tool === 'brush' || tool === 'decoration' || tool === 'eraser') {
        drawing.handlePointerMove(e, coalescedEvents, predictedEvents);
        return;
      }
      if (tool === 'vector-edit') {
        vectorTools.handleVectorEditPointerMove(e);
        return;
      }
      if (tool === 'gradient') {
        gradientTools.handleGradientPointerMove(e);
        return;
      }
      if (tool === 'retouch') {
        retouchTools.handleRetouchPointerMove(e);
        return;
      }
      if (tool === 'pen') {
        penTools.handlePenPointerMove(e);
        return;
      }
      if (shapeFillTools.handleShapeFillPointerMove(e)) return;
      selectionTools.handleSelectionPointerMove(getCanvasCoords(e));
    },
    [drawing, vectorTools, gradientTools, retouchTools, penTools, shapeFillTools, selectionTools, getCanvasCoords]
  );

  const handlePointerUp = useCallback(
    (e: React.PointerEvent<HTMLElement>) => {
      const startedTool = activePointerToolRef.current;
      activePointerToolRef.current = null;
      // Always finalize an active brush stroke even if tool changed mid-stroke (e.g. modifier/shortcut)
      // so drawing.isDrawingRef can never be left stranded true.
      if (drawing.isDrawingRef.current) {
        drawing.handlePointerUp(e);
        return;
      }
      const tool = startedTool ?? useToolStore.getState().tool;
      if (tool === 'brush' || tool === 'decoration' || tool === 'eraser') {
        drawing.handlePointerUp(e);
        return;
      }
      if (tool === 'vector-edit') {
        vectorTools.handleVectorEditPointerUp();
        return;
      }
      const pt = getCanvasCoords(e);
      if (tool === 'gradient') {
        gradientTools.handleGradientPointerUp(e, pt);
        return;
      }
      if (tool === 'retouch') {
        retouchTools.handleRetouchPointerUp(e);
        return;
      }
      if (tool === 'pen') {
        penTools.handlePenPointerUp(e);
        return;
      }
      if (selectionTools.handleSelectionPointerUp(pt, e)) return;
      shapeFillTools.handleShapeFillPointerUp(e, pt);
    },
    [drawing, vectorTools, gradientTools, retouchTools, penTools, getCanvasCoords, selectionTools, shapeFillTools]
  );

  // Memoized Top Menu Bar Sections (independent of brush size & color)
  const menuSections = useAppMenuSections({
    hasOpenDocument,
    dimensions,
    layers: layerMgr.layers,
    activeLayer: layerMgr.activeLayer,
    activeLayerId: layerMgr.activeLayerId,
    selection: selectionTools.selection,
    canUndo: drawing.canUndo || (is3DLayerOpen && canUndo3D),
    canRedo: drawing.canRedo || (is3DLayerOpen && canRedo3D),
    flipX: nav.flipX,
    flipY: nav.flipY,
    isWebtoonMode,
    perspectiveRuler,
    straightRuler,
    softProofSettings,
    activeAnimationTimeline,
    clearCanvas: drawing.clearCanvas,
    handleUndo,
    redo: handleRedo,
    handleTriggerOpenFile: docLifecycle.handleTriggerOpenFile,
    handleTriggerImport3DFile: docLifecycle.handleTriggerImport3DFile,
    handleSave: docLifecycle.handleSave,
    handleSaveAs: docLifecycle.handleSaveAs,
    handleExportImage: docLifecycle.handleExportImage,
    handleCutSelection: selectionTools.handleCutSelection,
    handleCopySelection: selectionTools.handleCopySelection,
    handleMoveSelectionToNewLayer: selectionTools.handleMoveSelectionToNewLayer,
    handleClearSelection: selectionTools.handleClearSelection,
    handleDeleteOutsideSelection: selectionTools.handleDeleteOutsideSelection,
    handleCopySelectedLayer: docLifecycle.handleCopySelectedLayer,
    handlePasteSelectedLayer: docLifecycle.handlePasteSelectedLayer,
    handleTriggerPasteFromFile: docLifecycle.handleTriggerPasteFromFile,
    handleDeleteSelectedLayer: docLifecycle.handleDeleteSelectedLayer,
    handleClearActiveLayer: collab.handleClearActiveLayer,
    handleStartTransform: selectionTools.handleStartTransform,
    handleDeselect: selectionTools.handleDeselect,
    handleFillSelectionColor: selectionTools.handleFillSelectionColor,
    handleOpenTonalModal: tonalActions.handleOpenTonalModal,
    handleApplyReverseGradient: tonalActions.handleApplyReverseGradient,
    handleSelectAll: selectionTools.handleSelectAll,
    handleInvertSelection: selectionTools.handleInvertSelection,
    handleExpandSelection: selectionTools.handleExpandSelection,
    handleContractSelection: selectionTools.handleContractSelection,
    handleFeatherSelection: selectionTools.handleFeatherSelection,
    handleAddLayer: handleRecordedAddLayer,
    handleFillScreentone: tonalActions.handleFillScreentone,
    toggleTone: handleToggleTone,
    handleOpenAdjustmentModal: tonalActions.handleOpenAdjustmentModal,
    addLayerMask: layerMgr.addLayerMask,
    removeLayerMask: layerMgr.removeLayerMask,
    toggleLayerMask: layerMgr.toggleLayerMask,
    toggleMaskLinked: layerMgr.toggleMaskLinked,
    duplicateLayer: handleRecordedDuplicateLayer,
    handleMergeDown,
    handleMergeFolder,
    handleOpenLayerStylesModal: tonalActions.handleOpenLayerStylesModal,
    toggleLayerColor: layerMgr.toggleLayerColor,
    handleConvertLayer: tonalActions.handleConvertLayer,
    deleteLayer: collab.handleDeleteLayer,
    handleApplyFilter: handleRecordedApplyFilter,
    zoomIn: nav.zoomIn,
    zoomOut: nav.zoomOut,
    resetZoomAndCenter: nav.resetZoomAndCenter,
    resetZoomTo100: nav.resetZoomTo100,
    resetRotation: nav.resetRotation,
    toggleFlipHorizontal: nav.toggleFlipHorizontal,
    toggleFlipVertical: nav.toggleFlipVertical,
    resetViewFlip: nav.resetViewFlip,
    handleUpdateAnimationTimeline,
    handleAddAnimationCel,
    handleAddDefaultFrameFolder,
    handleRasterizeLayer,
    isTimelapseRecording,
    handleToggleTimelapseRecording,
    showToast,
  });

  const handleOpenCollabModal = useCallback(() => {
    collab.setIsHostModalOpen(true);
  }, [collab.setIsHostModalOpen]);

  const collabRoomOverlayProps = useMemo(
    () => ({
      isConnected: collab.isConnected,
      isReconnecting: collab.isReconnecting,
      connectionStatus: collab.connectionStatus,
      myRole: collab.myRole,
      hostInfo: collab.hostInfo,
      myPeer: collab.myPeer,
      peers: collab.peers,
      chatMessages: collab.chatMessages,
      unreadChatCount: collab.unreadChatCount,
      onSendChatMessage: collab.sendChatMessage,
      onChatVisibilityChange: collab.setChatVisible,
      followingPeerId: collab.followingPeerId,
      onToggleFollowPeer: collab.toggleFollowPeer,
      onStopFollowing: () => collab.stopFollowing(false),
      grabbingPeerId: collab.grabbingPeerId,
      onGrabPeerBrush: collab.grabPeerBrush,
      onTrySharedBrush: collab.trySharedBrush,
      onShareMyBrush: collab.shareMyBrush,
      activeGrabbedBrush: collab.activeGrabbedBrush,
      onSaveGrabbedBrush: () => {
        void collab.saveActiveGrabbedBrush();
      },
      onDismissGrabbedBrush: collab.dismissActiveGrabbedBrush,
      onOpenHostModal: handleOpenCollabModal,
      diagnostics: collab.diagnostics,
    }),
    [
      collab.isConnected,
      collab.isReconnecting,
      collab.connectionStatus,
      collab.myRole,
      collab.hostInfo,
      collab.myPeer,
      collab.peers,
      collab.chatMessages,
      collab.unreadChatCount,
      collab.sendChatMessage,
      collab.setChatVisible,
      collab.followingPeerId,
      collab.toggleFollowPeer,
      collab.stopFollowing,
      collab.grabbingPeerId,
      collab.grabPeerBrush,
      collab.trySharedBrush,
      collab.shareMyBrush,
      collab.activeGrabbedBrush,
      collab.saveActiveGrabbedBrush,
      collab.dismissActiveGrabbedBrush,
      collab.diagnostics,
      handleOpenCollabModal,
    ]
  );

  const canvasProps = useMemo(
    () => ({
      viewportRef: nav.viewportRef,
      onViewportReady: docLifecycle.handleViewportReady,
      zoom: nav.zoom,
      pan: nav.pan,
      rotation: nav.rotation,
      flipX: nav.flipX,
      flipY: nav.flipY,
      navigation: nav.navigation,
      isSpaceDown: nav.isSpaceDown,
      isShiftDown: nav.isShiftDown,
      heldModifierAction: nav.heldModifierAction,
      isRotateModifier: nav.isRotateModifier,
      isPanning: nav.isPanning,
      isRotating: nav.isRotating,
      isZoomDragging: nav.isZoomDragging,
      startPan: nav.startPan,
      startRotate: nav.startRotate,
      startZoomDrag: nav.startZoomDrag,
      onSampleColor: shapeFillTools.handleSampleColor,
      onUndo: handleUndo,
      onRedo: handleRedo,
      onFlipHorizontal: nav.toggleFlipHorizontal,
      isHovering: drawing.isHovering,
      cursorPos: drawing.cursorPos,
      onPointerDown: handlePointerDown,
      onPointerMove: handlePointerMove,
      onPointerUp: handlePointerUp,
      onPointerEnter: drawing.handlePointerEnter,
      onPointerLeave: drawing.handlePointerLeave,
      layers: layerMgr.layers,
      activeLayerId: layerMgr.activeLayerId,
      getEffectiveOpacity: layerMgr.getEffectiveOpacity,
      isLayerEffectivelyVisible: layerMgr.isLayerEffectivelyVisible,
      interactionRef: drawing.interactionRef,
      peers: collab.peers,
      peerCursorStore: collab.peerCursorStore,
      activePings: collab.activePings,
      selection: selectionTools.selection,
      onDeselect: selectionTools.handleDeselect,
      onTransformSelection: selectionTools.handleStartTransform,
      onFillScreentone: tonalActions.handleFillScreentone,
      onFillColor: selectionTools.handleFillSelectionColor,
      onClearSelection: selectionTools.handleClearSelection,
      onDeleteOutsideSelection: selectionTools.handleDeleteOutsideSelection,
      onCutSelection: selectionTools.handleCutSelection,
      onCopySelection: selectionTools.handleCopySelection,
      onPasteSelection: docLifecycle.handlePasteSelectedLayer,
      onMoveSelectionToNewLayer: selectionTools.handleMoveSelectionToNewLayer,
      onInvertSelection: selectionTools.handleInvertSelection,
      onExpandSelection: selectionTools.handleExpandSelection,
      onContractSelection: selectionTools.handleContractSelection,
      onFeatherSelection: selectionTools.handleFeatherSelection,
      transformSession: selectionTools.transformSession,
      setTransformSession: selectionTools.setTransformSession,
      onApplyTransform: selectionTools.handleApplyTransform,
      onCancelTransform: selectionTools.handleCancelTransform,
      textSession: shapeFillTools.textSession,
      setTextSession: shapeFillTools.setTextSession,
      textDragPreview: shapeFillTools.textDragPreview,
      onConfirmText: shapeFillTools.handleConfirmText,
      onCancelText: shapeFillTools.handleCancelText,
      onDeleteText: shapeFillTools.handleDeleteText,
      onInsertRasterLayer: tonalActions.handleInsert3DRasterLayer,
      activeBalloon: shapeFillTools.activeBalloon,
      setActiveBalloon: shapeFillTools.setActiveBalloon,
      onConfirmBalloon: shapeFillTools.handleConfirmBalloon,
      onDeleteBalloon: shapeFillTools.handleDeleteBalloon,
      frameDragPreview: shapeFillTools.frameDragPreview,
      shapeDragPreview: shapeFillTools.shapeDragPreview,
      quickShapePreview: drawing.quickShapePreview,
      lassoFillPreview: shapeFillTools.lassoFillPreview,
      gradientDragPreview: gradientTools.gradientDragPreview,
      gradientMesh: gradientTools.gradientMesh,
      gradientMeshMarqueeRect: gradientTools.gradientMeshMarqueeRect,
      isRotatingGradientMesh: gradientTools.isRotatingGradientMesh,
      onApplyGradientMesh: gradientTools.handleApplyGradientMesh,
      onCancelGradientMesh: gradientTools.handleCancelGradientMesh,
      onStartRotateGradientMesh: gradientTools.handleStartRotateGradientMesh,
      cloneSourceIndicator: retouchTools.cloneSourceIndicator,
      penSession: penTools.penSession,
      onCommitPenPath: penTools.handleCommitPenPath,
      onCancelPenPath: penTools.handleCancelPenPath,
      onToggleClosePenPath: penTools.handleClosePenPath,
      animationTimeline: activeAnimationTimeline,
      onUpdateAnimationTimeline: handleUpdateAnimationTimeline,
      onAddAnimationCel: handleAddAnimationCel,
      onDeleteAnimationCel: handleDeleteAnimationCel,
      onSelectCelLayer: layerMgr.setActiveLayerId,
      onApplyResizeCanvas: docLifecycle.handleResizeCanvas,
    }),
    [
      nav,
      docLifecycle.handleViewportReady,
      docLifecycle.handlePasteSelectedLayer,
      docLifecycle.handleResizeCanvas,
      drawing.isHovering,
      drawing.cursorPos,
      drawing.handlePointerEnter,
      drawing.handlePointerLeave,
      drawing.interactionRef,
      drawing.quickShapePreview,
      handlePointerDown,
      handlePointerMove,
      handlePointerUp,
      layerMgr.layers,
      layerMgr.activeLayerId,
      layerMgr.getEffectiveOpacity,
      layerMgr.isLayerEffectivelyVisible,
      layerMgr.setActiveLayerId,
      collab.peers,
      collab.peerCursorStore,
      collab.activePings,
      selectionTools,
      tonalActions.handleFillScreentone,
      tonalActions.handleInsert3DRasterLayer,
      shapeFillTools.textSession,
      shapeFillTools.setTextSession,
      shapeFillTools.textDragPreview,
      shapeFillTools.handleConfirmText,
      shapeFillTools.handleCancelText,
      shapeFillTools.handleDeleteText,
      shapeFillTools.activeBalloon,
      shapeFillTools.setActiveBalloon,
      shapeFillTools.handleConfirmBalloon,
      shapeFillTools.handleDeleteBalloon,
      shapeFillTools.frameDragPreview,
      shapeFillTools.shapeDragPreview,
      shapeFillTools.lassoFillPreview,
      shapeFillTools.handleSampleColor,
      gradientTools.gradientDragPreview,
      gradientTools.gradientMesh,
      gradientTools.gradientMeshMarqueeRect,
      gradientTools.isRotatingGradientMesh,
      gradientTools.handleApplyGradientMesh,
      gradientTools.handleCancelGradientMesh,
      gradientTools.handleStartRotateGradientMesh,
      retouchTools.cloneSourceIndicator,
      penTools.penSession,
      penTools.handleCommitPenPath,
      penTools.handleCancelPenPath,
      penTools.handleClosePenPath,
      handleUndo,
      handleRedo,
      activeAnimationTimeline,
      handleUpdateAnimationTimeline,
      handleAddAnimationCel,
      handleDeleteAnimationCel,
    ]
  );

  const handleMarkActiveDocumentDirty = useCallback(() => {
    documentStoreActions.markDocumentDirty(activeDocumentId, true);
  }, [activeDocumentId]);

  const handleImportDropped3DModelFile = useCallback(
    (file: File) => {
      toolStoreActions.selectTool('3d');
      if (useUiStore.getState().is3DLayerOpen && scene3DBridge.loadFile) {
        scene3DBridge.loadFile(file);
      } else {
        uiStoreActions.set3DLayerOpen(true, file);
      }
      showToast(t('Imported 3D model "{name}"', { name: file.name }));
    },
    [showToast]
  );

  const externalFileDrop = useExternalFileDrop({
    enabled: hasOpenDocument && appView === 'workspace',
    is3DModeActive: is3DLayerOpen,
    importImageFileAsLayer: layerMgr.importImageFileAsLayer,
    import3DModelFile: handleImportDropped3DModelFile,
    onMarkDirty: handleMarkActiveDocumentDirty,
    showToast,
  });

  return (
    <AppShell
      fileInputRef={docLifecycle.fileInputRef}
      pasteFileInputRef={docLifecycle.pasteFileInputRef}
      import3DFileInputRef={docLifecycle.import3DFileInputRef}
      handleFileInputChange={docLifecycle.handleFileInputChange}
      handlePasteFileInputChange={docLifecycle.handlePasteFileInputChange}
      handleImport3DFileInputChange={docLifecycle.handleImport3DFileInputChange}
      canUndo={drawing.canUndo || (is3DLayerOpen && canUndo3D)}
      canRedo={drawing.canRedo || (is3DLayerOpen && canRedo3D)}
      handleUndo={handleUndo}
      redo={handleRedo}
      zoom={nav.zoom}
      zoomIn={nav.zoomIn}
      zoomOut={nav.zoomOut}
      resetZoomAndCenter={nav.resetZoomAndCenter}
      resetZoomTo100={nav.resetZoomTo100}
      rotation={nav.rotation}
      resetRotation={nav.resetRotation}
      flipX={nav.flipX}
      flipY={nav.flipY}
      toggleFlipHorizontal={nav.toggleFlipHorizontal}
      toggleFlipVertical={nav.toggleFlipVertical}
      resetViewFlip={nav.resetViewFlip}
      menuSections={menuSections}
      handleSelectDocument={docLifecycle.handleSelectDocument}
      handleCloseDocument={docLifecycle.handleCloseDocument}
      handleRenameDocument={docLifecycle.handleRenameDocument}
      handleSave={docLifecycle.handleSave}
      handleSaveAs={docLifecycle.handleSaveAs}
      handleClearActiveLayer={collab.handleClearActiveLayer}
      handleMergeDown={handleMergeDown}
      isCollabConnected={collab.isConnected}
      isCollabReconnecting={collab.isReconnecting}
      collabPeerCount={collab.peers.length + 1}
      onOpenCollabModal={handleOpenCollabModal}
      collabRoomOverlayProps={collabRoomOverlayProps}
      handleTriggerOpenFile={docLifecycle.handleTriggerOpenFile}
      handleSelectWelcomeDocument={docLifecycle.handleSelectWelcomeDocument}
      handleCreateNewCanvas={docLifecycle.handleCreateNewCanvas}
      showToast={showToast}
      canvasProps={canvasProps}
      historyList={drawing.historyList}
      historyIndex={drawing.historyIndex}
      jumpToHistoryIndex={drawing.jumpToHistoryIndex}
      layers={layerMgr.layers}
      activeLayerId={layerMgr.activeLayerId}
      selectedLayerIds={layerMgr.selectedLayerIds}
      setActiveLayerId={layerMgr.setActiveLayerId}
      toggleLayerSelection={layerMgr.toggleLayerSelection}
      handleGroupSelectedLayers={collab.handleGroupSelectedLayers}
      handleDeleteSelectedLayers={collab.handleDeleteSelectedLayers}
      handleAddLayer={handleRecordedAddLayer}
      duplicateLayer={handleRecordedDuplicateLayer}
      handleDeleteLayer={collab.handleDeleteLayer}
      handleToggleVisibility={collab.handleToggleVisibility}
      soloLayerId={layerMgr.soloLayerId}
      handleSoloLayer={handleGuardedSoloLayer}
      handleExitSoloLayer={layerMgr.exitSoloLayer}
      setLayerColorLabel={handleGuardedSetLayerColorLabel}
      handleSetOpacity={handleRecordedSetOpacity}
      setBlendMode={handleRecordedSetBlendMode}
      toggleLock={collab.handleToggleLock}
      toggleOwnerLock={collab.handleToggleOwnerLock}
      toggleAlphaLock={handleGuardedToggleAlphaLock}
      toggleClipping={handleRecordedToggleClipping}
      toggleCollapse={layerMgr.toggleCollapse}
      handleRenameLayer={collab.handleRenameLayer}
      moveLayer={handleGuardedMoveLayer}
      moveLayerToFolder={handleGuardedMoveLayerToFolder}
      reorderLayers={handleGuardedReorderLayers}
      handleToggleReferenceLayer={handleToggleReferenceLayer}
      toggleTone={handleToggleTone}
      setToneFrequency={layerMgr.setToneFrequency}
      setToneAngle={layerMgr.setToneAngle}
      setToneDotShape={layerMgr.setToneDotShape}
      setToneDensity={layerMgr.setToneDensity}
      setToneDensityType={layerMgr.setToneDensityType}
      toggleLayerColor={handleGuardedToggleLayerColor}
      setLayerColor={layerMgr.setLayerColor}
      setLayerSubColor={layerMgr.setLayerSubColor}
      setLayerExpressionColor={handleRecordedSetExpressionColor}
      setLayerMonoThreshold={layerMgr.setLayerMonoThreshold}
      setLayerMonoExpressMode={layerMgr.setLayerMonoExpressMode}
      handleApplyExpressionColor={tonalActions.handleApplyExpressionColor}
      handleApplyLayerColor={tonalActions.handleApplyLayerColor}
      addLayerMask={handleGuardedAddLayerMask}
      removeLayerMask={handleGuardedRemoveLayerMask}
      toggleLayerMask={handleGuardedToggleLayerMask}
      toggleMaskLinked={handleGuardedToggleMaskLinked}
      handleOpenAdjustmentModal={tonalActions.handleOpenAdjustmentModal}
      handleOpenLayerStylesModal={tonalActions.handleOpenLayerStylesModal}
      onEditVectorLayer={shapeFillTools.openLayerForEditing}
      onRasterizeLayer={handleRasterizeLayer}
      onMergeFolder={handleMergeFolder}
      onPlayAutoAction={handlePlayAutoAction}
      externalFileDropTarget={externalFileDrop.activeDropTarget}
    >
      <DocumentLifecycleManager
        layers={layerMgr.layers}
        activeLayerId={layerMgr.activeLayerId}
        needsAdaptiveFitRef={docLifecycle.needsAdaptiveFitRef}
        pendingFitDimsRef={docLifecycle.pendingFitDimsRef}
        autoCreatedInitialDocIdRef={docLifecycle.autoCreatedInitialDocIdRef}
        resetToNewCanvas={layerMgr.resetToNewCanvas}
        resetZoomAndCenter={nav.resetZoomAndCenter}
        resetHistory={drawing.resetHistory}
        onSelectDocument={docLifecycle.handleSelectDocument}
        onOpenFilePaths={docLifecycle.handleOpenFilePaths}
      />

      <GlobalShortcutListener
        hasOpenDocument={hasOpenDocument}
        dimensions={dimensions}
        layers={layerMgr.layers}
        activeLayer={layerMgr.activeLayer}
        activeLayerId={layerMgr.activeLayerId}
        selection={selectionTools.selection}
        transformSession={selectionTools.transformSession}
        textSession={shapeFillTools.textSession}
        activeAnimationTimeline={activeAnimationTimeline}
        isSpaceDown={nav.isSpaceDown}
        isHostModalOpen={collab.isHostModalOpen}
        isDrawingRef={drawing.isDrawingRef}
        isSelectionPenDrawingRef={selectionTools.isSelectionPenDrawingRef}
        isPipetteSamplingRef={shapeFillTools.isPipetteSamplingRef}
        handleUndo={handleUndo}
        redo={handleRedo}
        handleAddLayer={collab.handleAddLayer}
        handleTriggerOpenFile={docLifecycle.handleTriggerOpenFile}
        handleSave={docLifecycle.handleSave}
        handleSaveAs={docLifecycle.handleSaveAs}
        duplicateLayer={layerMgr.duplicateLayer}
        handleCutSelection={selectionTools.handleCutSelection}
        handleCopySelection={selectionTools.handleCopySelection}
        handleCopySelectedLayer={docLifecycle.handleCopySelectedLayer}
        handlePasteSelectedLayer={docLifecycle.handlePasteSelectedLayer}
        handleMoveSelectionToNewLayer={selectionTools.handleMoveSelectionToNewLayer}
        handleCopySelectionToNewLayer={selectionTools.handleCopySelectionToNewLayer}
        handleGroupSelectedLayers={collab.handleGroupSelectedLayers}
        handleStartTransform={selectionTools.handleStartTransform}
        setTransformSession={selectionTools.setTransformSession}
        handleSelectAll={selectionTools.handleSelectAll}
        handleDeselect={selectionTools.handleDeselect}
        handleInvertSelection={selectionTools.handleInvertSelection}
        handleApplyReverseGradient={tonalActions.handleApplyReverseGradient}
        handleOpenTonalModal={tonalActions.handleOpenTonalModal}
        handleUpdateAnimationTimeline={handleUpdateAnimationTimeline}
        handleAddAnimationCel={handleAddAnimationCel}
        zoomIn={nav.zoomIn}
        zoomOut={nav.zoomOut}
        resetZoomAndCenter={nav.resetZoomAndCenter}
        resetZoomTo100={nav.resetZoomTo100}
        resetRotation={nav.resetRotation}
        toggleFlipHorizontal={nav.toggleFlipHorizontal}
        toggleFlipVertical={nav.toggleFlipVertical}
        handleClearSelection={selectionTools.handleClearSelection}
        handleDeleteSelectedLayer={docLifecycle.handleDeleteSelectedLayer}
        handleCancelTransform={selectionTools.handleCancelTransform}
        handleCancelText={shapeFillTools.handleCancelText}
        handleApplyTransform={selectionTools.handleApplyTransform}
        handleProcessFile={docLifecycle.handleProcessFile}
        showToast={showToast}
      />

      <ModalHost
        layers={layerMgr.layers}
        activeLayer={layerMgr.activeLayer}
        getEffectiveOpacity={layerMgr.getEffectiveOpacity}
        isLayerEffectivelyVisible={layerMgr.isLayerEffectivelyVisible}
        handleCreateNewCanvas={docLifecycle.handleCreateNewCanvas}
        handleResizeCanvas={docLifecycle.handleResizeCanvas}
        selectionBounds={selectionTools.selection?.bounds ?? null}
        handleUpdateSettings={docLifecycle.handleUpdateSettings}
        handleRestoreCrashedSession={docLifecycle.handleRestoreCrashedSession}
        handleDiscardCrashedSession={docLifecycle.handleDiscardCrashedSession}
        handleDiscardAllCrashedSessions={docLifecycle.handleDiscardAllCrashedSessions}
        handleTonalCancel={tonalActions.handleTonalCancel}
        handleTonalApply={tonalActions.handleTonalApply}
        handleTonalPreviewChange={tonalActions.handleTonalPreviewChange}
        handleApplyFilter={handleRecordedApplyFilter}
        handleApplyAdjustment={tonalActions.handleApplyAdjustment}
        handleApplyLayerStyles={tonalActions.handleApplyLayerStyles}
        handleConfirmTone={tonalActions.handleConfirmTone}
        handleApplyMangaEffects={tonalActions.handleApplyMangaEffects}
        isHostModalOpen={collab.isHostModalOpen}
        setIsHostModalOpen={collab.setIsHostModalOpen}
        isCollabHost={collab.isHost}
        isCollabConnected={collab.isConnected}
        collabConnectionStatus={collab.connectionStatus}
        collabReconnectAttempt={collab.reconnectAttempt}
        collabMyRole={collab.myRole}
        collabHostInfo={collab.hostInfo}
        collabPeers={collab.peers}
        collabBannedPeerIds={collab.bannedPeerIds}
        collabMyPeer={collab.myPeer}
        updateMyName={collab.updateMyName}
        handleStartHosting={collab.handleStartHosting}
        handleStartWebRtcHosting={collab.handleStartWebRtcHosting}
        stopHosting={collab.stopHosting}
        joinByInviteUrl={collab.joinByInviteUrl}
        leaveRoom={collab.leaveRoom}
        onSetPeerRole={collab.setPeerRole}
        onKickPeer={collab.kickPeer}
        onBanPeer={collab.banPeer}
        onUnbanPeer={collab.unbanPeer}
        followingPeerId={collab.followingPeerId}
        onToggleFollowPeer={collab.toggleFollowPeer}
        grabbingPeerId={collab.grabbingPeerId}
        onGrabPeerBrush={collab.grabPeerBrush}
        clipboardInvite={collab.clipboardInvite}
        setClipboardInvite={collab.setClipboardInvite}
        webLandingInvite={collab.webLandingInvite}
        setWebLandingInvite={collab.setWebLandingInvite}
        joinRoom={collab.joinRoom}
        onCaptureTimelapseNow={handleCaptureTimelapseNow}
        handleSave={docLifecycle.handleSave}
        handleSaveDocumentById={docLifecycle.handleSaveDocumentById}
        showToast={showToast}
      />
    </AppShell>
  );
}

export default App;