Skip to content

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

108 KB
Raw Blame
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import {
  Plus,
  ChevronLeft,
  ChevronRight,
  Trash2,
  ZoomIn,
  ZoomOut,
  Maximize,
  RotateCcw,
  RotateCw,
  FlipHorizontal,
  FlipVertical,
  Pipette,
  Hand,
  List,
  ImagePlus,
  RefreshCw,
  LayoutGrid,
  Square,
  Contrast,
  Columns2,
  Grid3x3,
  SlidersHorizontal,
  Palette,
  ClipboardPaste,
  MousePointer2,
  Lock,
  Unlock,
  Copy,
  BringToFront,
  SendToBack,
  Focus,
  X,
  Rows3,
  Columns3,
  Sparkles,
} from 'lucide-react';
import { CanvasColorMode } from '../types/editor';
import { ThemePreset } from '../types/settings';
import {
  SUB_VIEW_MAX_ZOOM,
  SUB_VIEW_MIN_ZOOM,
  SubViewBoardLayoutMode,
  SubViewImageItem,
  SubViewTransform,
  hydrateSubViewImages,
  subViewStoreActions,
  useSubViewStore,
} from '../stores/useSubViewStore';
import { toolStoreActions } from '../stores/useToolStore';
import {
  CardHandleKind,
  ExtractedSwatch,
  PixelCoord,
  SubViewGridMode,
  SubViewStudyFilter,
  SubViewValueSteps,
  boardPointToStagePoint,
  buildFilteredReferenceCanvas,
  clampBoardCardScale,
  clampSubViewZoom,
  computeBoardFitTransform,
  computeSubViewFitZoom,
  drawProportionalGrid,
  extractDominantColorsFromCanvas,
  getCardStageOverlay,
  getStudyFilterSignature,
  hitTestBoardCards,
  hitTestCardHandle,
  isStudyFilterVisualActive,
  stageDeltaToBoardDelta,
  stagePointToBoardPoint,
  subViewPointToImagePixel,
} from '../utils/subViewEngine';
import { clampNavigatorSplitRatio, computePerceptualLuminanceByte } from '../utils/valueCheck';
import { isImeComposing, t as translate, tc as translateCtx, useI18n } from '../i18n';

export type { PixelCoord };
export { subViewPointToImagePixel, computeSubViewFitZoom };

const DND_PANEL_MIME = 'application/x-inkstudio-panel';
const VALID_IMAGE_EXT_RE = /\.(png|jpe?g|webp|gif|bmp|avif|ico|svg)$/i;

const GRID_MODE_LABELS: Record<SubViewGridMode, string> = {
  none: 'Off',
  thirds: '3×3',
  grid4: '4×4',
  grid8: '8×8',
  golden: 'φ',
  crosshair: '+',
};

const VALUE_STEP_LABELS: Record<SubViewValueSteps, string> = {
  0: 'Val',
  2: '2V',
  3: '3V',
  5: '5V',
};

/**
 * Safely samples a `#rrggbb` hex color at `(px, py)` from an owned offscreen 2D canvas.
 * Catches CORS/SecurityError exceptions cleanly and ignores fully transparent pixels.
 */
export function samplePixelHexFromCanvas(
  canvas: HTMLCanvasElement | null,
  px: number,
  py: number
): string | null {
  if (!canvas || px < 0 || py < 0 || px >= canvas.width || py >= canvas.height) {
    return null;
  }
  try {
    const ctx = canvas.getContext('2d', { willReadFrequently: true });
    if (!ctx) return null;
    const data = ctx.getImageData(px, py, 1, 1).data;
    const alpha = data[3];
    if (alpha === 0) return null;
    const r = data[0].toString(16).padStart(2, '0');
    const g = data[1].toString(16).padStart(2, '0');
    const b = data[2].toString(16).padStart(2, '0');
    return `#${r}${g}${b}`;
  } catch {
    // Guard against tainted canvas / SecurityError
    return null;
  }
}

function hexToPerceptualValuePercent(hex: string): number | null {
  const m = /^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(hex);
  if (!m) return null;
  const r = parseInt(m[1], 16);
  const g = parseInt(m[2], 16);
  const b = parseInt(m[3], 16);
  return Math.round((computePerceptualLuminanceByte(r, g, b) / 255) * 100);
}

function isImageFile(file: File): boolean {
  if (file.type && file.type.startsWith('image/')) return true;
  return VALID_IMAGE_EXT_RE.test(file.name);
}

function readLocalImageFile(
  file: File
): Promise<{ name: string; src: string; width: number; height: number }> {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onerror = () => reject(new Error(`Failed to read ${file.name}`));
    reader.onload = () => {
      const dataUrl = typeof reader.result === 'string' ? reader.result : '';
      if (!dataUrl) {
        reject(new Error(`Empty image data for ${file.name}`));
        return;
      }
      const img = new Image();
      img.onload = () => {
        resolve({
          name: file.name || translateCtx('subView', 'Reference'),
          src: dataUrl,
          width: img.naturalWidth || img.width || 1,
          height: img.naturalHeight || img.height || 1,
        });
      };
      img.onerror = () => reject(new Error(`Unsupported image format: ${file.name}`));
      img.src = dataUrl;
    };
    reader.readAsDataURL(file);
  });
}

function drawBoardBackgroundDots(
  ctx: CanvasRenderingContext2D,
  sw: number,
  sh: number,
  t: SubViewTransform
): void {
  // Subtle PureRef-style spatial dot grid that moves/scales/rotates with the board camera
  const baseSpacing = 40;
  let step = baseSpacing;
  while (step * t.zoom < 18) step *= 2;
  while (step * t.zoom > 72) step /= 2;

  const corners = [
    stagePointToBoardPoint(0, 0, sw, sh, t),
    stagePointToBoardPoint(sw, 0, sw, sh, t),
    stagePointToBoardPoint(sw, sh, sw, sh, t),
    stagePointToBoardPoint(0, sh, sw, sh, t),
  ];
  let minX = Infinity;
  let maxX = -Infinity;
  let minY = Infinity;
  let maxY = -Infinity;
  for (const c of corners) {
    if (c.x < minX) minX = c.x;
    if (c.x > maxX) maxX = c.x;
    if (c.y < minY) minY = c.y;
    if (c.y > maxY) maxY = c.y;
  }

  const startX = Math.floor(minX / step) * step;
  const startY = Math.floor(minY / step) * step;
  const maxDots = 2400;
  const cols = Math.ceil((maxX - startX) / step) + 1;
  const rows = Math.ceil((maxY - startY) / step) + 1;
  if (cols * rows > maxDots) return;

  ctx.save();
  ctx.fillStyle = 'rgba(255, 255, 255, 0.11)';
  for (let y = startY; y <= maxY; y += step) {
    for (let x = startX; x <= maxX; x += step) {
      const p = boardPointToStagePoint(x, y, sw, sh, t);
      ctx.fillRect(p.x - 0.75, p.y - 0.75, 1.5, 1.5);
    }
  }
  ctx.restore();
}

export interface SubViewPanelProps {
  colorMode?: CanvasColorMode;
  themePreset?: ThemePreset;
}

interface FilteredCacheEntry {
  sig: string;
  srcCanvas: HTMLCanvasElement;
  filteredCanvas: HTMLCanvasElement;
}

type LiveCardPatch = {
  id: string;
  boardX: number;
  boardY: number;
  boardScale: number;
  boardRotation: number;
};

export const SubViewPanel: React.FC<SubViewPanelProps> = React.memo(
  ({ colorMode = 'color', themePreset = 'modern' }) => {
    const { t, tc } = useI18n();
    const items = useSubViewStore((s) => s.items);
    const activeId = useSubViewStore((s) => s.activeId);
    const viewMode = useSubViewStore((s) => s.viewMode);
    const boardTool = useSubViewStore((s) => s.boardTool);
    const boardTransform = useSubViewStore((s) => s.boardTransform);
    const boardNeedsInitialFit = useSubViewStore((s) => s.boardNeedsInitialFit);
    const studyFilter = useSubViewStore((s) => s.studyFilter);
    const sampleDisplayTone = useSubViewStore((s) => s.sampleDisplayTone);
    const autoEyedropper = useSubViewStore((s) => s.autoEyedropper);
    const manualEyedropper = useSubViewStore((s) => s.manualEyedropper);
    const showList = useSubViewStore((s) => s.showList);
    const showPalette = useSubViewStore((s) => s.showPalette);

    const activeIndex = useMemo(
      () => Math.max(0, items.findIndex((i) => i.id === activeId)),
      [items, activeId]
    );
    const activeItem: SubViewImageItem | null =
      items.length > 0 ? items[activeIndex] ?? items[0] : null;

    const panelRef = useRef<HTMLDivElement | null>(null);
    const stageRef = useRef<HTMLDivElement | null>(null);
    const displayCanvasRef = useRef<HTMLCanvasElement | null>(null);
    const fileInputRef = useRef<HTMLInputElement | null>(null);
    const reloadInputRef = useRef<HTMLInputElement | null>(null);

    // Owned offscreen decoded canvases keyed by item.id
    const sourceCanvasMapRef = useRef<Map<string, { src: string; canvas: HTMLCanvasElement }>>(
      new Map()
    );
    // Filtered canvas cache keyed by item.id (and separate split-bw B/W cache)
    const filteredCacheRef = useRef<Map<string, FilteredCacheEntry>>(new Map());
    const splitBwCacheRef = useRef<Map<string, FilteredCacheEntry>>(new Map());

    const [stageSize, setStageSize] = useState<{ width: number; height: number }>({
      width: 200,
      height: 140,
    });
    const [sourceVersion, setSourceVersion] = useState(0);
    const [isDragOverFiles, setIsDragOverFiles] = useState(false);
    const [isHoveringStage, setIsHoveringStage] = useState(false);
    const [isSpaceHeld, setIsSpaceHeld] = useState(false);
    const [isAltHeld, setIsAltHeld] = useState(false);
    const [sampledHex, setSampledHex] = useState<string | null>(null);
    const [loadError, setLoadError] = useState<string | null>(null);
    const [showTonePopover, setShowTonePopover] = useState(false);
    const [showArrangeMenu, setShowArrangeMenu] = useState(false);
    const [isDraggingSplit, setIsDraggingSplit] = useState(false);
    const [extractedSwatches, setExtractedSwatches] = useState<ExtractedSwatch[]>([]);
    const [activeInteractionKind, setActiveInteractionKind] = useState<
      'none' | 'pan' | 'eyedrop' | 'card-move' | 'card-resize' | 'card-rotate'
    >('none');

    // Live mutable transforms during drags/wheel for zero-lag 60fps interaction
    const liveSingleTransformRef = useRef<SubViewTransform>({
      zoom: 1,
      pan: { x: 0, y: 0 },
      rotation: 0,
      flipX: false,
    });
    const liveBoardTransformRef = useRef<SubViewTransform>({
      zoom: 1,
      pan: { x: 0, y: 0 },
      rotation: 0,
      flipX: false,
    });
    const liveCardPatchRef = useRef<LiveCardPatch | null>(null);

    const interactionRef = useRef<{
      mode: 'none' | 'pan' | 'eyedrop' | 'card-move' | 'card-resize' | 'card-rotate';
      pointerId: number | null;
      startClientX: number;
      startClientY: number;
      startPanX: number;
      startPanY: number;
      cardId: string | null;
      startCardX: number;
      startCardY: number;
      startCardScale: number;
      startCardRotation: number;
      startCardDist: number;
      startCardAngle: number;
      handleKind: CardHandleKind | null;
    }>({
      mode: 'none',
      pointerId: null,
      startClientX: 0,
      startClientY: 0,
      startPanX: 0,
      startPanY: 0,
      cardId: null,
      startCardX: 0,
      startCardY: 0,
      startCardScale: 1,
      startCardRotation: 0,
      startCardDist: 1,
      startCardAngle: 0,
      handleKind: null,
    });

    const splitDragRef = useRef<{
      active: boolean;
      pointerId: number | null;
      latestRatio: number;
    }>({
      active: false,
      pointerId: null,
      latestRatio: 0.5,
    });

    const itemsRef = useRef<SubViewImageItem[]>(items);
    itemsRef.current = items;
    const activeItemRef = useRef<SubViewImageItem | null>(activeItem);
    activeItemRef.current = activeItem;
    const viewModeRef = useRef(viewMode);
    viewModeRef.current = viewMode;
    const boardToolRef = useRef(boardTool);
    boardToolRef.current = boardTool;
    const studyFilterRef = useRef<SubViewStudyFilter>(studyFilter);
    studyFilterRef.current = studyFilter;
    const sampleDisplayToneRef = useRef(sampleDisplayTone);
    sampleDisplayToneRef.current = sampleDisplayTone;
    const stageSizeRef = useRef(stageSize);
    stageSizeRef.current = stageSize;
    const isHoveringStageRef = useRef(isHoveringStage);
    isHoveringStageRef.current = isHoveringStage;

    // Hydrate image data URLs from IndexedDB on mount
    useEffect(() => {
      void hydrateSubViewImages();
    }, []);

    // Sync live transform refs from store
    useEffect(() => {
      if (!activeItem) return;
      liveSingleTransformRef.current = {
        zoom: activeItem.zoom,
        pan: { x: activeItem.pan.x, y: activeItem.pan.y },
        rotation: activeItem.rotation,
        flipX: activeItem.flipX,
      };
    }, [activeItem]);

    useEffect(() => {
      liveBoardTransformRef.current = {
        zoom: boardTransform.zoom,
        pan: { x: boardTransform.pan.x, y: boardTransform.pan.y },
        rotation: boardTransform.rotation,
        flipX: boardTransform.flipX,
      };
    }, [boardTransform]);

    // Track stage dimensions via ResizeObserver
    useEffect(() => {
      const el = stageRef.current;
      if (!el) return;
      const sync = () => {
        const rect = el.getBoundingClientRect();
        if (rect.width > 0 && rect.height > 0) {
          setStageSize((prev) =>
            Math.abs(prev.width - rect.width) < 1 && Math.abs(prev.height - rect.height) < 1
              ? prev
              : { width: Math.round(rect.width), height: Math.round(rect.height) }
          );
        }
      };
      sync();
      const ro = typeof ResizeObserver !== 'undefined' ? new ResizeObserver(sync) : null;
      ro?.observe(el);
      return () => ro?.disconnect();
    }, []);

    // Decode all reference images into owned offscreen 2D canvases for CORS-safe sampling & fast board rendering
    const itemsSrcKey = useMemo(
      () => items.map((i) => `${i.id}:${i.src ? i.src.length : 0}:${i.width}x${i.height}`).join('|'),
      [items]
    );

    useEffect(() => {
      let cancelled = false;
      setLoadError(null);

      const currentIds = new Set(items.map((i) => i.id));
      for (const cachedId of Array.from(sourceCanvasMapRef.current.keys())) {
        if (!currentIds.has(cachedId)) {
          sourceCanvasMapRef.current.delete(cachedId);
          filteredCacheRef.current.delete(cachedId);
          splitBwCacheRef.current.delete(cachedId);
        }
      }

      let pendingDecodeCount = 0;

      for (const item of items) {
        if (!item.src) {
          sourceCanvasMapRef.current.delete(item.id);
          continue;
        }
        const existing = sourceCanvasMapRef.current.get(item.id);
        if (existing && existing.src === item.src) {
          // Already decoded; ensure initial fit in Single mode if needed
          if (item.id === activeItemRef.current?.id && item.needsInitialFit) {
            const { width: sw, height: sh } = stageSizeRef.current;
            const fitZoom = computeSubViewFitZoom(sw, sh, existing.canvas.width, existing.canvas.height);
            liveSingleTransformRef.current = {
              zoom: fitZoom,
              pan: { x: 0, y: 0 },
              rotation: 0,
              flipX: false,
            };
            subViewStoreActions.updateImageTransform(
              item.id,
              { zoom: fitZoom, pan: { x: 0, y: 0 }, rotation: 0, flipX: false, needsInitialFit: false },
              true
            );
          }
          continue;
        }

        pendingDecodeCount += 1;
        const itemId = item.id;
        const itemSrc = item.src;
        const itemW = item.width;
        const itemH = item.height;
        const itemNeedsFit = item.needsInitialFit;

        const img = new Image();
        img.crossOrigin = 'anonymous';
        img.onload = () => {
          if (cancelled) return;
          const w = Math.max(1, img.naturalWidth || img.width || itemW || 1);
          const h = Math.max(1, img.naturalHeight || img.height || itemH || 1);
          const off = document.createElement('canvas');
          off.width = w;
          off.height = h;
          const ctx = off.getContext('2d', { willReadFrequently: true });
          if (ctx) {
            ctx.clearRect(0, 0, w, h);
            ctx.drawImage(img, 0, 0, w, h);
          }
          sourceCanvasMapRef.current.set(itemId, { src: itemSrc, canvas: off });
          filteredCacheRef.current.delete(itemId);
          splitBwCacheRef.current.delete(itemId);
          setSourceVersion((v) => v + 1);

          if (itemNeedsFit) {
            const { width: sw, height: sh } = stageSizeRef.current;
            const fitZoom = computeSubViewFitZoom(sw, sh, w, h);
            if (activeItemRef.current?.id === itemId) {
              liveSingleTransformRef.current = {
                zoom: fitZoom,
                pan: { x: 0, y: 0 },
                rotation: 0,
                flipX: false,
              };
            }
            subViewStoreActions.updateImageTransform(
              itemId,
              { zoom: fitZoom, pan: { x: 0, y: 0 }, rotation: 0, flipX: false, needsInitialFit: false },
              true
            );
          }
        };
        img.onerror = () => {
          if (cancelled) return;
          sourceCanvasMapRef.current.delete(itemId);
          if (activeItemRef.current?.id === itemId) {
            setLoadError(translate('Failed to decode image'));
          }
          setSourceVersion((v) => v + 1);
        };
        img.src = itemSrc;
      }

      if (pendingDecodeCount === 0) {
        setSourceVersion((v) => v + 1);
      }

      return () => {
        cancelled = true;
      };
    }, [itemsSrcKey]);

    // Auto-fit PureRef board when first populated or after Auto-Arrange
    useEffect(() => {
      if (viewMode !== 'board' || !boardNeedsInitialFit || items.length === 0) return;
      const { width: sw, height: sh } = stageSizeRef.current;
      if (sw < 20 || sh < 20) return;
      const fit = computeBoardFitTransform(items, sw, sh, 18);
      liveBoardTransformRef.current = fit;
      subViewStoreActions.updateBoardTransform({ ...fit, needsInitialFit: false }, true);
    }, [viewMode, boardNeedsInitialFit, items, stageSize]);

    // Extract dominant color swatches whenever palette drawer is open and active item changes
    useEffect(() => {
      if (!showPalette || !activeItem) {
        setExtractedSwatches([]);
        return;
      }
      const entry = sourceCanvasMapRef.current.get(activeItem.id);
      if (!entry) {
        setExtractedSwatches([]);
        return;
      }
      setExtractedSwatches(extractDominantColorsFromCanvas(entry.canvas, 7));
    }, [showPalette, activeItem?.id, sourceVersion]);

    // Resolve cached filtered canvas for an item
    const getDrawableCanvasForItem = useCallback(
      (
        item: SubViewImageItem,
        filter: SubViewStudyFilter,
        forceGrayscaleOverride?: boolean
      ): HTMLCanvasElement | null => {
        const srcEntry = sourceCanvasMapRef.current.get(item.id);
        if (!srcEntry) return null;
        const srcCanvas = srcEntry.canvas;

        const effectiveFilter =
          forceGrayscaleOverride === undefined
            ? filter
            : { ...filter, grayscale: forceGrayscaleOverride };
        const itemGray = forceGrayscaleOverride === false ? false : item.grayscale;

        if (!isStudyFilterVisualActive(effectiveFilter, itemGray)) {
          return srcCanvas;
        }

        const cacheMap =
          forceGrayscaleOverride === true ? splitBwCacheRef.current : filteredCacheRef.current;
        const sig = getStudyFilterSignature(effectiveFilter, itemGray);
        const cached = cacheMap.get(item.id);
        if (cached && cached.sig === sig && cached.srcCanvas === srcCanvas) {
          return cached.filteredCanvas;
        }

        const filteredCanvas = buildFilteredReferenceCanvas(srcCanvas, effectiveFilter, itemGray);
        cacheMap.set(item.id, { sig, srcCanvas, filteredCanvas });
        return filteredCanvas;
      },
      []
    );

    const getEffectiveCards = useCallback((): SubViewImageItem[] => {
      const livePatch = liveCardPatchRef.current;
      if (!livePatch) return itemsRef.current;
      return itemsRef.current.map((it) =>
        it.id === livePatch.id
          ? {
              ...it,
              boardX: livePatch.boardX,
              boardY: livePatch.boardY,
              boardScale: livePatch.boardScale,
              boardRotation: livePatch.boardRotation,
            }
          : it
      );
    }, []);

    // Render Single OR PureRef Board display canvas (including Split Color | B/W and proportional grids)
    const renderDisplayCanvas = useCallback(
      (overrideTransform?: SubViewTransform, overrideSplitRatio?: number) => {
        const display = displayCanvasRef.current;
        if (!display) return;
        const ctx = display.getContext('2d');
        if (!ctx) return;

        const { width: sw, height: sh } = stageSizeRef.current;
        const dpr = typeof window !== 'undefined' ? Math.min(2, window.devicePixelRatio || 1) : 1;
        const targetW = Math.max(1, Math.round(sw * dpr));
        const targetH = Math.max(1, Math.round(sh * dpr));
        if (display.width !== targetW || display.height !== targetH) {
          display.width = targetW;
          display.height = targetH;
        }

        const filter = studyFilterRef.current;
        const mode = viewModeRef.current;

        ctx.save();
        ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
        ctx.clearRect(0, 0, sw, sh);

        if (mode === 'single') {
          const active = activeItemRef.current;
          if (!active) {
            ctx.restore();
            return;
          }
          const t = overrideTransform ?? liveSingleTransformRef.current;
          const srcEntry = sourceCanvasMapRef.current.get(active.id);
          if (!srcEntry) {
            ctx.restore();
            return;
          }
          const imgW = srcEntry.canvas.width;
          const imgH = srcEntry.canvas.height;

          const drawSinglePass = (drawable: HTMLCanvasElement) => {
            ctx.save();
            ctx.translate(sw / 2 + t.pan.x, sh / 2 + t.pan.y);
            ctx.rotate((t.rotation * Math.PI) / 180);
            ctx.scale(t.flipX ? -t.zoom : t.zoom, t.zoom);
            ctx.imageSmoothingEnabled = t.zoom < 2;
            ctx.drawImage(drawable, -imgW / 2, -imgH / 2, imgW, imgH);
            ctx.restore();
          };

          if (filter.splitBw) {
            const splitX = sw * clampNavigatorSplitRatio(overrideSplitRatio ?? filter.splitRatio);
            const colorCanvas = getDrawableCanvasForItem(active, filter, false);
            const bwCanvas = getDrawableCanvasForItem(active, filter, true);
            if (colorCanvas) {
              ctx.save();
              ctx.beginPath();
              ctx.rect(0, 0, splitX, sh);
              ctx.clip();
              drawSinglePass(colorCanvas);
              ctx.restore();
            }
            if (bwCanvas) {
              ctx.save();
              ctx.beginPath();
              ctx.rect(splitX, 0, Math.max(0, sw - splitX), sh);
              ctx.clip();
              drawSinglePass(bwCanvas);
              ctx.restore();
            }
          } else {
            const drawable = getDrawableCanvasForItem(active, filter);
            if (drawable) drawSinglePass(drawable);
          }

          if (filter.gridMode !== 'none') {
            ctx.save();
            ctx.translate(sw / 2 + t.pan.x, sh / 2 + t.pan.y);
            ctx.rotate((t.rotation * Math.PI) / 180);
            ctx.scale(t.flipX ? -t.zoom : t.zoom, t.zoom);
            drawProportionalGrid(ctx, imgW, imgH, filter.gridMode, t.zoom);
            ctx.restore();
          }

          ctx.restore();
          return;
        }

        // PureRef Board Mode
        const t = overrideTransform ?? liveBoardTransformRef.current;
        const cards = getEffectiveCards();

        drawBoardBackgroundDots(ctx, sw, sh, t);

        if (cards.length === 0) {
          ctx.restore();
          return;
        }

        const sortedCards = cards
          .map((card, idx) => ({ card, idx }))
          .sort((a, b) => a.card.zIndex - b.card.zIndex || a.idx - b.idx)
          .map((e) => e.card);

        const drawBoardCardsPass = (forceGrayscaleOverride?: boolean) => {
          ctx.save();
          ctx.translate(sw / 2 + t.pan.x, sh / 2 + t.pan.y);
          ctx.rotate((t.rotation * Math.PI) / 180);
          ctx.scale(t.flipX ? -t.zoom : t.zoom, t.zoom);

          for (const card of sortedCards) {
            const drawable = getDrawableCanvasForItem(card, filter, forceGrayscaleOverride);
            const w = Math.max(1, card.width);
            const h = Math.max(1, card.height);
            ctx.save();
            ctx.translate(card.boardX, card.boardY);
            ctx.rotate((card.boardRotation * Math.PI) / 180);
            ctx.scale(
              card.boardFlipX ? -card.boardScale : card.boardScale,
              card.boardFlipY ? -card.boardScale : card.boardScale
            );
            ctx.globalAlpha = card.opacity;
            ctx.imageSmoothingEnabled = t.zoom * card.boardScale < 2;

            if (drawable) {
              ctx.drawImage(drawable, -w / 2, -h / 2, w, h);
            } else {
              // Metadata-only placeholder card
              ctx.fillStyle = 'rgba(40, 40, 44, 0.9)';
              ctx.fillRect(-w / 2, -h / 2, w, h);
              ctx.strokeStyle = 'rgba(255, 255, 255, 0.25)';
              ctx.lineWidth = 1 / Math.max(0.1, t.zoom * card.boardScale);
              ctx.strokeRect(-w / 2, -h / 2, w, h);
            }

            if (filter.gridMode !== 'none' && card.id === activeItemRef.current?.id) {
              ctx.globalAlpha = 1;
              drawProportionalGrid(ctx, w, h, filter.gridMode, t.zoom * card.boardScale);
            }
            ctx.restore();
          }
          ctx.restore();
        };

        if (filter.splitBw) {
          const splitX = sw * clampNavigatorSplitRatio(overrideSplitRatio ?? filter.splitRatio);
          ctx.save();
          ctx.beginPath();
          ctx.rect(0, 0, splitX, sh);
          ctx.clip();
          drawBoardCardsPass(false);
          ctx.restore();

          ctx.save();
          ctx.beginPath();
          ctx.rect(splitX, 0, Math.max(0, sw - splitX), sh);
          ctx.clip();
          drawBoardCardsPass(true);
          ctx.restore();
        } else {
          drawBoardCardsPass(undefined);
        }

        // Draw crisp screen-space selection frame & handles for active card in Board mode
        const selectedCard = sortedCards.find((c) => c.id === activeItemRef.current?.id);
        if (selectedCard) {
          const ov = getCardStageOverlay(selectedCard, sw, sh, t);
          ctx.save();
          ctx.strokeStyle = selectedCard.locked
            ? 'rgba(225, 169, 72, 0.85)'
            : 'rgba(96, 165, 250, 0.92)';
          ctx.lineWidth = 1.25;
          ctx.beginPath();
          ctx.moveTo(ov.tl.x, ov.tl.y);
          ctx.lineTo(ov.tr.x, ov.tr.y);
          ctx.lineTo(ov.br.x, ov.br.y);
          ctx.lineTo(ov.bl.x, ov.bl.y);
          ctx.closePath();
          ctx.stroke();

          // Show interactive resize & rotate handles when in Arrange/Select mode and card is unlocked
          if (!selectedCard.locked && boardToolRef.current === 'select') {
            // Rotation stem + lollipop
            ctx.beginPath();
            ctx.moveTo(ov.topMid.x, ov.topMid.y);
            ctx.lineTo(ov.rotHandle.x, ov.rotHandle.y);
            ctx.stroke();

            ctx.fillStyle = '#18181b';
            if (typeof ctx.arc === 'function') {
              ctx.beginPath();
              ctx.arc(ov.rotHandle.x, ov.rotHandle.y, 4, 0, Math.PI * 2);
              ctx.fill();
              ctx.stroke();
            } else {
              ctx.fillRect(ov.rotHandle.x - 4, ov.rotHandle.y - 4, 8, 8);
              ctx.strokeRect(ov.rotHandle.x - 4, ov.rotHandle.y - 4, 8, 8);
            }

            // 4 corner handles
            for (const corner of [ov.tl, ov.tr, ov.br, ov.bl]) {
              ctx.fillStyle = '#ffffff';
              ctx.fillRect(corner.x - 3.5, corner.y - 3.5, 7, 7);
              ctx.strokeRect(corner.x - 3.5, corner.y - 3.5, 7, 7);
            }
          }
          ctx.restore();
        }

        ctx.restore();
      },
      [getDrawableCanvasForItem, getEffectiveCards]
    );

    useEffect(() => {
      renderDisplayCanvas();
    }, [
      items,
      activeItem,
      viewMode,
      boardTool,
      boardTransform,
      studyFilter,
      stageSize,
      sourceVersion,
      renderDisplayCanvas,
    ]);

    // Determine effective interaction mode on hover/click
    const isEyedropperActive = useMemo(() => {
      if (isSpaceHeld) return false;
      if (isAltHeld) return true;
      if (viewMode === 'board') {
        return boardTool === 'eyedrop';
      }
      return autoEyedropper || manualEyedropper;
    }, [viewMode, boardTool, autoEyedropper, manualEyedropper, isSpaceHeld, isAltHeld]);

    const sampleColorAtClientPos = useCallback(
      (clientX: number, clientY: number, commit: boolean): string | null => {
        const stage = stageRef.current;
        if (!stage) return null;
        const rect = stage.getBoundingClientRect();
        const localX = clientX - rect.left;
        const localY = clientY - rect.top;
        const sw = rect.width || stageSizeRef.current.width;
        const sh = rect.height || stageSizeRef.current.height;
        const filter = studyFilterRef.current;
        const useFiltered = sampleDisplayToneRef.current;

        if (viewModeRef.current === 'single') {
          const active = activeItemRef.current;
          if (!active) return null;
          const srcEntry = sourceCanvasMapRef.current.get(active.id);
          if (!srcEntry) return null;
          const src = srcEntry.canvas;
          const pxCoord = subViewPointToImagePixel(
            localX,
            localY,
            sw,
            sh,
            src.width,
            src.height,
            liveSingleTransformRef.current
          );
          if (!pxCoord) return null;
          const sampleCanvas = useFiltered
            ? getDrawableCanvasForItem(active, filter) ?? src
            : src;
          const sx = Math.min(
            sampleCanvas.width - 1,
            Math.max(0, Math.floor((pxCoord.x / src.width) * sampleCanvas.width))
          );
          const sy = Math.min(
            sampleCanvas.height - 1,
            Math.max(0, Math.floor((pxCoord.y / src.height) * sampleCanvas.height))
          );
          const hex = samplePixelHexFromCanvas(sampleCanvas, sx, sy);
          if (!hex) return null;
          setSampledHex(hex);
          toolStoreActions.setPrimaryColor(hex, commit, colorMode);
          return hex;
        }

        // PureRef Board mode: hit-test topmost card under pointer
        const hit = hitTestBoardCards(
          localX,
          localY,
          getEffectiveCards(),
          sw,
          sh,
          liveBoardTransformRef.current
        );
        if (!hit) return null;
        const srcEntry = sourceCanvasMapRef.current.get(hit.card.id);
        if (!srcEntry) return null;
        const src = srcEntry.canvas;
        const sampleCanvas = useFiltered
          ? getDrawableCanvasForItem(hit.card, filter) ?? src
          : src;
        const sx = Math.min(
          sampleCanvas.width - 1,
          Math.max(0, Math.floor((hit.pixel.x / Math.max(1, hit.card.width)) * sampleCanvas.width))
        );
        const sy = Math.min(
          sampleCanvas.height - 1,
          Math.max(0, Math.floor((hit.pixel.y / Math.max(1, hit.card.height)) * sampleCanvas.height))
        );
        const hex = samplePixelHexFromCanvas(sampleCanvas, sx, sy);
        if (!hex) return null;
        setSampledHex(hex);
        toolStoreActions.setPrimaryColor(hex, commit, colorMode);
        return hex;
      },
      [colorMode, getDrawableCanvasForItem, getEffectiveCards]
    );

    const handleFilesSelected = useCallback(
      async (fileList: FileList | File[], dropClientPos?: { x: number; y: number } | null) => {
        const files = Array.from(fileList).filter(isImageFile);
        if (files.length === 0) return;
        setLoadError(null);
        const loaded: Array<{ name: string; src: string; width: number; height: number }> = [];
        for (const file of files) {
          try {
            loaded.push(await readLocalImageFile(file));
          } catch {
            setLoadError(t('Could not load "{name}"', { name: file.name }));
          }
        }
        if (loaded.length > 0) {
          let dropBoardPoint = null;
          if (
            dropClientPos &&
            viewModeRef.current === 'board' &&
            itemsRef.current.length > 0 &&
            stageRef.current
          ) {
            const rect = stageRef.current.getBoundingClientRect();
            dropBoardPoint = stagePointToBoardPoint(
              dropClientPos.x - rect.left,
              dropClientPos.y - rect.top,
              rect.width || stageSizeRef.current.width,
              rect.height || stageSizeRef.current.height,
              liveBoardTransformRef.current
            );
          }
          subViewStoreActions.addImages(loaded, { dropBoardPoint });
        }
      },
      [t]
    );

    const handlePasteFromClipboard = useCallback(async () => {
      setLoadError(null);
      if (typeof navigator === 'undefined' || !navigator.clipboard?.read) {
        setLoadError(t('Use Ctrl+V while hovering References to paste an image'));
        return;
      }
      try {
        const clipItems = await navigator.clipboard.read();
        const files: File[] = [];
        let idx = 1;
        for (const clipItem of clipItems) {
          const imgType = clipItem.types.find((mt) => mt.startsWith('image/'));
          if (imgType) {
            const blob = await clipItem.getType(imgType);
            const ext = imgType.split('/')[1]?.replace(/[^a-z0-9]/gi, '') || 'png';
            files.push(
              new File([blob], `${t('Clipboard {n}', { n: idx++ })}.${ext}`, { type: imgType })
            );
          }
        }
        if (files.length === 0) {
          setLoadError(t('No image found in clipboard'));
          return;
        }
        await handleFilesSelected(files);
      } catch {
        setLoadError(t('Clipboard image read blocked — press Ctrl+V over References'));
      }
    }, [handleFilesSelected, t]);

    // Clipboard Ctrl+V listener scoped to when the References panel is hovered or focused
    useEffect(() => {
      const onPaste = (e: ClipboardEvent) => {
        const panel = panelRef.current;
        const activeEl = document.activeElement;
        const isFocusedInside = Boolean(panel && activeEl && panel.contains(activeEl));
        if (!isHoveringStageRef.current && !isFocusedInside) return;
        const cd = e.clipboardData;
        if (!cd) return;
        const imageFiles: File[] = [];
        for (let i = 0; i < cd.items.length; i++) {
          const it = cd.items[i];
          if (it.kind === 'file' && it.type.startsWith('image/')) {
            const f = it.getAsFile();
            if (f) imageFiles.push(f);
          }
        }
        if (imageFiles.length > 0) {
          e.preventDefault();
          e.stopPropagation();
          void handleFilesSelected(imageFiles);
        }
      };
      window.addEventListener('paste', onPaste);
      return () => window.removeEventListener('paste', onPaste);
    }, [handleFilesSelected]);

    const handleReloadActiveFile = useCallback(async (file: File | undefined) => {
      const item = activeItemRef.current;
      if (!file || !item || !isImageFile(file)) return;
      try {
        const loaded = await readLocalImageFile(file);
        subViewStoreActions.replaceImageSrc(item.id, loaded.src, loaded.width, loaded.height);
      } catch {
        setLoadError(t('Could not load "{name}"', { name: file.name }));
      }
    }, [t]);

    // Viewport control actions (board camera in Board mode, active image in Single mode)
    const handleSubZoomBy = useCallback((factor: number) => {
      if (viewModeRef.current === 'board') {
        const nextZoom = clampSubViewZoom(liveBoardTransformRef.current.zoom * factor);
        subViewStoreActions.updateBoardTransform({ zoom: nextZoom, needsInitialFit: false }, true);
        return;
      }
      const item = activeItemRef.current;
      if (!item) return;
      const nextZoom = clampSubViewZoom(liveSingleTransformRef.current.zoom * factor);
      subViewStoreActions.updateImageTransform(
        item.id,
        { zoom: nextZoom, needsInitialFit: false },
        true
      );
    }, []);

    const handleSubFit = useCallback(() => {
      const { width: sw, height: sh } = stageSizeRef.current;
      if (viewModeRef.current === 'board') {
        const cards = itemsRef.current;
        if (cards.length === 0) return;
        const fit = computeBoardFitTransform(cards, sw, sh, 18);
        liveBoardTransformRef.current = fit;
        subViewStoreActions.updateBoardTransform({ ...fit, needsInitialFit: false }, true);
        return;
      }
      const item = activeItemRef.current;
      if (!item) return;
      const src = sourceCanvasMapRef.current.get(item.id)?.canvas;
      const w = src?.width || item.width || 1;
      const h = src?.height || item.height || 1;
      const fitZoom = computeSubViewFitZoom(sw, sh, w, h);
      subViewStoreActions.updateImageTransform(
        item.id,
        { zoom: fitZoom, pan: { x: 0, y: 0 }, rotation: 0, flipX: false, needsInitialFit: false },
        true
      );
    }, []);

    const handleFitSelectedCard = useCallback((cardId?: string) => {
      const targetId = cardId ?? activeItemRef.current?.id;
      if (!targetId) return;
      const card = itemsRef.current.find((i) => i.id === targetId);
      if (!card) return;
      const { width: sw, height: sh } = stageSizeRef.current;
      const fit = computeBoardFitTransform([card], sw, sh, 18);
      liveBoardTransformRef.current = fit;
      subViewStoreActions.updateBoardTransform({ ...fit, needsInitialFit: false }, true);
    }, []);

    const handleSubRotateBy = useCallback((deltaDeg: number) => {
      if (viewModeRef.current === 'board') {
        subViewStoreActions.updateBoardTransform(
          { rotation: liveBoardTransformRef.current.rotation + deltaDeg },
          true
        );
        return;
      }
      const item = activeItemRef.current;
      if (!item) return;
      subViewStoreActions.updateImageTransform(
        item.id,
        { rotation: liveSingleTransformRef.current.rotation + deltaDeg },
        true
      );
    }, []);

    const handleSubResetRotation = useCallback(() => {
      if (viewModeRef.current === 'board') {
        subViewStoreActions.updateBoardTransform({ rotation: 0 }, true);
        return;
      }
      const item = activeItemRef.current;
      if (!item) return;
      subViewStoreActions.updateImageTransform(item.id, { rotation: 0 }, true);
    }, []);

    const handleSubToggleFlipX = useCallback(() => {
      if (viewModeRef.current === 'board') {
        subViewStoreActions.updateBoardTransform(
          { flipX: !liveBoardTransformRef.current.flipX },
          true
        );
        return;
      }
      const item = activeItemRef.current;
      if (!item) return;
      subViewStoreActions.updateImageTransform(
        item.id,
        { flipX: !liveSingleTransformRef.current.flipX },
        true
      );
    }, []);

    // Track Space / Alt and quick local study hotkeys (G = B/W, F = Fit, H = Flip H) while hovering stage
    useEffect(() => {
      if (!isHoveringStage) {
        setIsSpaceHeld(false);
        setIsAltHeld(false);
        return;
      }
      const onKeyDown = (e: KeyboardEvent) => {
        if (isImeComposing(e)) return;
        const tag = (e.target as HTMLElement | null)?.tagName;
        if (tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT') return;
        if (e.code === 'Space' || e.key === ' ') setIsSpaceHeld(true);
        if (e.key === 'Alt') setIsAltHeld(true);
        if (!e.ctrlKey && !e.metaKey && !e.altKey) {
          const lower = e.key.toLowerCase();
          if (lower === 'g') {
            e.preventDefault();
            e.stopPropagation();
            subViewStoreActions.toggleGrayscale();
          } else if (lower === 'f') {
            e.preventDefault();
            e.stopPropagation();
            handleSubFit();
          } else if (lower === 'h') {
            e.preventDefault();
            e.stopPropagation();
            handleSubToggleFlipX();
          }
        }
      };
      const onKeyUp = (e: KeyboardEvent) => {
        if (e.code === 'Space' || e.key === ' ') setIsSpaceHeld(false);
        if (e.key === 'Alt') setIsAltHeld(false);
      };
      const onBlur = () => {
        setIsSpaceHeld(false);
        setIsAltHeld(false);
      };
      window.addEventListener('keydown', onKeyDown);
      window.addEventListener('keyup', onKeyUp, true);
      window.addEventListener('blur', onBlur);
      return () => {
        window.removeEventListener('keydown', onKeyDown);
        window.removeEventListener('keyup', onKeyUp, true);
        window.removeEventListener('blur', onBlur);
      };
    }, [isHoveringStage, handleSubFit, handleSubToggleFlipX]);

    const handleStagePointerDown = useCallback(
      (e: React.PointerEvent<HTMLDivElement>) => {
        if (itemsRef.current.length === 0) return;
        e.preventDefault();
        e.stopPropagation();
        setShowArrangeMenu(false);

        const stage = stageRef.current;
        const rect = stage?.getBoundingClientRect();
        const localX = rect ? e.clientX - rect.left : e.clientX;
        const localY = rect ? e.clientY - rect.top : e.clientY;
        const sw = rect?.width || stageSizeRef.current.width;
        const sh = rect?.height || stageSizeRef.current.height;

        const forcePan = e.button === 1 || isSpaceHeld;
        const forceEyedrop = !forcePan && e.button === 0 && e.altKey;

        if (viewModeRef.current === 'single') {
          const item = activeItemRef.current;
          if (!item || !item.src) return;
          const shouldEyedrop = forceEyedrop || (!forcePan && e.button === 0 && isEyedropperActive);

          if (shouldEyedrop) {
            interactionRef.current = {
              ...interactionRef.current,
              mode: 'eyedrop',
              pointerId: e.pointerId,
              startClientX: e.clientX,
              startClientY: e.clientY,
            };
            setActiveInteractionKind('eyedrop');
            sampleColorAtClientPos(e.clientX, e.clientY, true);
          } else if (e.button === 0 || e.button === 1) {
            interactionRef.current = {
              ...interactionRef.current,
              mode: 'pan',
              pointerId: e.pointerId,
              startClientX: e.clientX,
              startClientY: e.clientY,
              startPanX: liveSingleTransformRef.current.pan.x,
              startPanY: liveSingleTransformRef.current.pan.y,
            };
            setActiveInteractionKind('pan');
          }
        } else {
          // PureRef Board Mode
          const bt = liveBoardTransformRef.current;
          const cards = itemsRef.current;

          if (forcePan || (e.button === 0 && !forceEyedrop && boardToolRef.current === 'pan')) {
            interactionRef.current = {
              ...interactionRef.current,
              mode: 'pan',
              pointerId: e.pointerId,
              startClientX: e.clientX,
              startClientY: e.clientY,
              startPanX: bt.pan.x,
              startPanY: bt.pan.y,
            };
            setActiveInteractionKind('pan');
          } else if (forceEyedrop || (e.button === 0 && boardToolRef.current === 'eyedrop')) {
            const hit = hitTestBoardCards(localX, localY, cards, sw, sh, bt);
            if (hit) {
              interactionRef.current = {
                ...interactionRef.current,
                mode: 'eyedrop',
                pointerId: e.pointerId,
                startClientX: e.clientX,
                startClientY: e.clientY,
              };
              setActiveInteractionKind('eyedrop');
              sampleColorAtClientPos(e.clientX, e.clientY, true);
            } else {
              // Clicking empty space around references in Eyedropper mode pans the board smoothly
              interactionRef.current = {
                ...interactionRef.current,
                mode: 'pan',
                pointerId: e.pointerId,
                startClientX: e.clientX,
                startClientY: e.clientY,
                startPanX: bt.pan.x,
                startPanY: bt.pan.y,
              };
              setActiveInteractionKind('pan');
            }
          } else if (e.button === 0 && boardToolRef.current === 'select') {
            // 1. Check active card's resize / rotate handles first
            const active = activeItemRef.current;
            const handle = active ? hitTestCardHandle(localX, localY, active, sw, sh, bt) : null;
            if (active && handle) {
              const bp = stagePointToBoardPoint(localX, localY, sw, sh, bt);
              const dx = bp.x - active.boardX;
              const dy = bp.y - active.boardY;
              const dist = Math.max(4, Math.hypot(dx, dy));
              const angle = (Math.atan2(dy, dx) * 180) / Math.PI;
              const nextMode = handle === 'rotate' ? 'card-rotate' : 'card-resize';
              liveCardPatchRef.current = {
                id: active.id,
                boardX: active.boardX,
                boardY: active.boardY,
                boardScale: active.boardScale,
                boardRotation: active.boardRotation,
              };
              interactionRef.current = {
                mode: nextMode,
                pointerId: e.pointerId,
                startClientX: e.clientX,
                startClientY: e.clientY,
                startPanX: bt.pan.x,
                startPanY: bt.pan.y,
                cardId: active.id,
                startCardX: active.boardX,
                startCardY: active.boardY,
                startCardScale: active.boardScale,
                startCardRotation: active.boardRotation,
                startCardDist: dist,
                startCardAngle: angle,
                handleKind: handle,
              };
              setActiveInteractionKind(nextMode);
            } else {
              // 2. Hit-test board cards
              const hit = hitTestBoardCards(localX, localY, cards, sw, sh, bt);
              if (hit) {
                subViewStoreActions.selectImage(hit.card.id);
                if (!hit.card.locked) {
                  subViewStoreActions.bringCardToFront(hit.card.id);
                  liveCardPatchRef.current = {
                    id: hit.card.id,
                    boardX: hit.card.boardX,
                    boardY: hit.card.boardY,
                    boardScale: hit.card.boardScale,
                    boardRotation: hit.card.boardRotation,
                  };
                  interactionRef.current = {
                    ...interactionRef.current,
                    mode: 'card-move',
                    pointerId: e.pointerId,
                    startClientX: e.clientX,
                    startClientY: e.clientY,
                    cardId: hit.card.id,
                    startCardX: hit.card.boardX,
                    startCardY: hit.card.boardY,
                    startCardScale: hit.card.boardScale,
                    startCardRotation: hit.card.boardRotation,
                    handleKind: null,
                  };
                  setActiveInteractionKind('card-move');
                } else {
                  // Locked card: drag pans the board instead of moving the locked card
                  interactionRef.current = {
                    ...interactionRef.current,
                    mode: 'pan',
                    pointerId: e.pointerId,
                    startClientX: e.clientX,
                    startClientY: e.clientY,
                    startPanX: bt.pan.x,
                    startPanY: bt.pan.y,
                  };
                  setActiveInteractionKind('pan');
                }
              } else {
                // Empty space: pan the PureRef board
                interactionRef.current = {
                  ...interactionRef.current,
                  mode: 'pan',
                  pointerId: e.pointerId,
                  startClientX: e.clientX,
                  startClientY: e.clientY,
                  startPanX: bt.pan.x,
                  startPanY: bt.pan.y,
                };
                setActiveInteractionKind('pan');
              }
            }
          }
        }

        try {
          e.currentTarget.setPointerCapture?.(e.pointerId);
        } catch {
          // Ignore in synthetic events
        }
      },
      [isEyedropperActive, isSpaceHeld, sampleColorAtClientPos]
    );

    const handleStagePointerMove = useCallback(
      (e: React.PointerEvent<HTMLDivElement>) => {
        const state = interactionRef.current;
        if (state.mode === 'none') return;

        if (state.mode === 'eyedrop') {
          sampleColorAtClientPos(e.clientX, e.clientY, false);
          return;
        }

        if (state.mode === 'pan') {
          const dx = e.clientX - state.startClientX;
          const dy = e.clientY - state.startClientY;
          if (viewModeRef.current === 'single') {
            const next: SubViewTransform = {
              ...liveSingleTransformRef.current,
              pan: { x: state.startPanX + dx, y: state.startPanY + dy },
            };
            liveSingleTransformRef.current = next;
            renderDisplayCanvas(next);
          } else {
            const next: SubViewTransform = {
              ...liveBoardTransformRef.current,
              pan: { x: state.startPanX + dx, y: state.startPanY + dy },
            };
            liveBoardTransformRef.current = next;
            renderDisplayCanvas(next);
          }
          return;
        }

        if (state.mode === 'card-move' && state.cardId) {
          const dx = e.clientX - state.startClientX;
          const dy = e.clientY - state.startClientY;
          const deltaBoard = stageDeltaToBoardDelta(dx, dy, liveBoardTransformRef.current);
          liveCardPatchRef.current = {
            id: state.cardId,
            boardX: state.startCardX + deltaBoard.x,
            boardY: state.startCardY + deltaBoard.y,
            boardScale: state.startCardScale,
            boardRotation: state.startCardRotation,
          };
          renderDisplayCanvas();
          return;
        }

        if ((state.mode === 'card-resize' || state.mode === 'card-rotate') && state.cardId) {
          const stage = stageRef.current;
          if (!stage) return;
          const rect = stage.getBoundingClientRect();
          const localX = e.clientX - rect.left;
          const localY = e.clientY - rect.top;
          const bp = stagePointToBoardPoint(
            localX,
            localY,
            rect.width || stageSizeRef.current.width,
            rect.height || stageSizeRef.current.height,
            liveBoardTransformRef.current
          );
          const dx = bp.x - state.startCardX;
          const dy = bp.y - state.startCardY;

          if (state.mode === 'card-resize') {
            const dist = Math.max(4, Math.hypot(dx, dy));
            const ratio = dist / Math.max(4, state.startCardDist);
            const nextScale = clampBoardCardScale(state.startCardScale * ratio);
            liveCardPatchRef.current = {
              id: state.cardId,
              boardX: state.startCardX,
              boardY: state.startCardY,
              boardScale: nextScale,
              boardRotation: state.startCardRotation,
            };
          } else {
            const angle = (Math.atan2(dy, dx) * 180) / Math.PI;
            let nextRot = state.startCardRotation + (angle - state.startCardAngle);
            if (e.shiftKey) {
              nextRot = Math.round(nextRot / 15) * 15;
            }
            liveCardPatchRef.current = {
              id: state.cardId,
              boardX: state.startCardX,
              boardY: state.startCardY,
              boardScale: state.startCardScale,
              boardRotation: nextRot,
            };
          }
          renderDisplayCanvas();
        }
      },
      [renderDisplayCanvas, sampleColorAtClientPos]
    );

    const finishStageInteraction = useCallback(
      (e?: React.PointerEvent<HTMLDivElement>) => {
        const state = interactionRef.current;
        if (state.mode === 'none') return;
        const prevMode = state.mode;
        const pid = state.pointerId;
        interactionRef.current.mode = 'none';
        interactionRef.current.pointerId = null;
        setActiveInteractionKind('none');

        if (e && pid !== null) {
          try {
            e.currentTarget.releasePointerCapture?.(pid);
          } catch {
            // Ignore in synthetic events
          }
        }

        if (prevMode === 'pan') {
          if (viewModeRef.current === 'single') {
            const item = activeItemRef.current;
            if (item) {
              subViewStoreActions.updateImageTransform(
                item.id,
                { pan: liveSingleTransformRef.current.pan, needsInitialFit: false },
                true
              );
            }
          } else {
            subViewStoreActions.updateBoardTransform(
              { pan: liveBoardTransformRef.current.pan, needsInitialFit: false },
              true
            );
          }
        } else if (prevMode === 'eyedrop' && e) {
          sampleColorAtClientPos(e.clientX, e.clientY, true);
        } else if (
          (prevMode === 'card-move' || prevMode === 'card-resize' || prevMode === 'card-rotate') &&
          liveCardPatchRef.current
        ) {
          const patch = liveCardPatchRef.current;
          liveCardPatchRef.current = null;
          subViewStoreActions.updateCardBoardProps(
            patch.id,
            {
              boardX: patch.boardX,
              boardY: patch.boardY,
              boardScale: patch.boardScale,
              boardRotation: patch.boardRotation,
            },
            true
          );
        }
      },
      [sampleColorAtClientPos]
    );

    const handleStageDoubleClick = useCallback(
      (e: React.MouseEvent<HTMLDivElement>) => {
        if (viewModeRef.current !== 'board' || itemsRef.current.length === 0) return;
        if (boardToolRef.current === 'eyedrop') return;
        const stage = stageRef.current;
        if (!stage) return;
        const rect = stage.getBoundingClientRect();
        const localX = e.clientX - rect.left;
        const localY = e.clientY - rect.top;
        const hit = hitTestBoardCards(
          localX,
          localY,
          itemsRef.current,
          rect.width || stageSizeRef.current.width,
          rect.height || stageSizeRef.current.height,
          liveBoardTransformRef.current
        );
        if (hit) {
          subViewStoreActions.selectImage(hit.card.id);
          handleFitSelectedCard(hit.card.id);
        } else {
          handleSubFit();
        }
      },
      [handleFitSelectedCard, handleSubFit]
    );

    // Split Color | B/W Curtain Handle Dragging
    const handleSplitPointerDown = useCallback(
      (e: React.PointerEvent<HTMLDivElement>) => {
        if (e.button !== 0) return;
        e.stopPropagation();
        e.preventDefault();
        const stage = stageRef.current;
        if (!stage) return;
        const rect = stage.getBoundingClientRect();
        const nextRatio = clampNavigatorSplitRatio(
          (e.clientX - rect.left) / Math.max(1, rect.width || stageSizeRef.current.width)
        );
        splitDragRef.current = { active: true, pointerId: e.pointerId, latestRatio: nextRatio };
        setIsDraggingSplit(true);
        renderDisplayCanvas(undefined, nextRatio);
        subViewStoreActions.updateStudyFilter({ splitRatio: nextRatio }, false);
        try {
          e.currentTarget.setPointerCapture?.(e.pointerId);
        } catch {
          // Ignore in synthetic events
        }
      },
      [renderDisplayCanvas]
    );

    const handleSplitPointerMove = useCallback(
      (e: React.PointerEvent<HTMLDivElement>) => {
        if (!splitDragRef.current.active) return;
        e.stopPropagation();
        const stage = stageRef.current;
        if (!stage) return;
        const rect = stage.getBoundingClientRect();
        const nextRatio = clampNavigatorSplitRatio(
          (e.clientX - rect.left) / Math.max(1, rect.width || stageSizeRef.current.width)
        );
        splitDragRef.current.latestRatio = nextRatio;
        renderDisplayCanvas(undefined, nextRatio);
        subViewStoreActions.updateStudyFilter({ splitRatio: nextRatio }, false);
      },
      [renderDisplayCanvas]
    );

    const finishSplitDrag = useCallback((e?: React.PointerEvent<HTMLDivElement>) => {
      if (!splitDragRef.current.active) return;
      e?.stopPropagation();
      const pid = splitDragRef.current.pointerId;
      const finalRatio = splitDragRef.current.latestRatio;
      splitDragRef.current.active = false;
      splitDragRef.current.pointerId = null;
      setIsDraggingSplit(false);
      if (e && pid !== null) {
        try {
          e.currentTarget.releasePointerCapture?.(pid);
        } catch {
          // Ignore in synthetic events
        }
      }
      subViewStoreActions.updateStudyFilter({ splitRatio: finalRatio }, true);
    }, []);

    // Independent mouse wheel zoom (and Shift+Wheel smooth rotation!) strictly inside References stage
    useEffect(() => {
      const el = stageRef.current;
      if (!el) return;
      const handleWheel = (e: WheelEvent) => {
        if (itemsRef.current.length === 0) return;
        if (viewModeRef.current === 'single' && !activeItemRef.current?.src) return;
        e.preventDefault();
        e.stopPropagation();

        // Shift + Wheel rotates smoothly by 5° steps
        if (e.shiftKey) {
          const deltaDeg = e.deltaY > 0 ? 5 : -5;
          if (viewModeRef.current === 'board') {
            const next: SubViewTransform = {
              ...liveBoardTransformRef.current,
              rotation: liveBoardTransformRef.current.rotation + deltaDeg,
            };
            liveBoardTransformRef.current = next;
            renderDisplayCanvas(next);
            subViewStoreActions.updateBoardTransform({ rotation: next.rotation }, true);
          } else if (activeItemRef.current) {
            const next: SubViewTransform = {
              ...liveSingleTransformRef.current,
              rotation: liveSingleTransformRef.current.rotation + deltaDeg,
            };
            liveSingleTransformRef.current = next;
            renderDisplayCanvas(next);
            subViewStoreActions.updateImageTransform(
              activeItemRef.current.id,
              { rotation: next.rotation },
              true
            );
          }
          return;
        }

        const rect = el.getBoundingClientRect();
        const localX = e.clientX - rect.left;
        const localY = e.clientY - rect.top;
        const cx = (rect.width || stageSizeRef.current.width) / 2;
        const cy = (rect.height || stageSizeRef.current.height) / 2;

        const factor = Math.exp(-e.deltaY * 0.002);
        const cur =
          viewModeRef.current === 'board'
            ? liveBoardTransformRef.current
            : liveSingleTransformRef.current;
        const nextZoom = Math.max(SUB_VIEW_MIN_ZOOM, Math.min(SUB_VIEW_MAX_ZOOM, cur.zoom * factor));
        const ratio = nextZoom / cur.zoom;

        const nextPanX = localX - cx - (localX - cx - cur.pan.x) * ratio;
        const nextPanY = localY - cy - (localY - cy - cur.pan.y) * ratio;

        const next: SubViewTransform = {
          ...cur,
          zoom: nextZoom,
          pan: { x: nextPanX, y: nextPanY },
        };

        if (viewModeRef.current === 'board') {
          liveBoardTransformRef.current = next;
          renderDisplayCanvas(next);
          subViewStoreActions.updateBoardTransform(
            { zoom: nextZoom, pan: next.pan, needsInitialFit: false },
            true
          );
        } else if (activeItemRef.current) {
          liveSingleTransformRef.current = next;
          renderDisplayCanvas(next);
          subViewStoreActions.updateImageTransform(
            activeItemRef.current.id,
            { zoom: nextZoom, pan: next.pan, needsInitialFit: false },
            true
          );
        }
      };
      el.addEventListener('wheel', handleWheel, { passive: false });
      return () => el.removeEventListener('wheel', handleWheel);
    }, [renderDisplayCanvas]);

    const handleDragOver = (e: React.DragEvent<HTMLDivElement>) => {
      if (e.dataTransfer.types.includes(DND_PANEL_MIME)) return;
      e.preventDefault();
      e.stopPropagation();
      e.dataTransfer.dropEffect = 'copy';
      setIsDragOverFiles(true);
    };

    const handleDragLeave = () => {
      setIsDragOverFiles(false);
    };

    const handleDrop = (e: React.DragEvent<HTMLDivElement>) => {
      if (e.dataTransfer.types.includes(DND_PANEL_MIME)) return;
      e.preventDefault();
      e.stopPropagation();
      setIsDragOverFiles(false);
      if (e.dataTransfer.files && e.dataTransfer.files.length > 0) {
        void handleFilesSelected(e.dataTransfer.files, { x: e.clientX, y: e.clientY });
      }
    };

    const handleArrangeBoard = (layout: SubViewBoardLayoutMode) => {
      subViewStoreActions.arrangeBoard(layout);
      setShowArrangeMenu(false);
    };

    const btnBase =
      'h-5 px-1 rounded-ui-xs text-[10px] flex items-center justify-center text-ui-icon-muted hover:text-ui-primary hover:bg-ui-control-hover disabled:opacity-35 disabled:pointer-events-none transition-colors cursor-pointer';

    const btnActive =
      'bg-ui-accent-subtle text-ui-accent ring-1 ring-inset ring-ui-accent-border';

    const stageCursorClass =
      items.length === 0
        ? 'cursor-default'
        : isDraggingSplit
          ? 'cursor-ew-resize'
          : isEyedropperActive
            ? 'cursor-crosshair'
            : activeInteractionKind === 'pan' || activeInteractionKind === 'card-move'
              ? 'cursor-grabbing'
              : viewMode === 'board' && boardTool === 'select'
                ? 'cursor-default'
                : 'cursor-grab';

    const activeTransform =
      viewMode === 'board'
        ? boardTransform
        : activeItem
          ? {
              zoom: activeItem.zoom,
              pan: activeItem.pan,
              rotation: activeItem.rotation,
              flipX: activeItem.flipX,
            }
          : null;

    const hasToneAdjust =
      studyFilter.brightness !== 0 ||
      studyFilter.contrast !== 0 ||
      studyFilter.valueSteps > 0 ||
      sampleDisplayTone;

    const sampledValuePct = sampledHex ? hexToPerceptualValuePercent(sampledHex) : null;
    const isBwActive = studyFilter.grayscale || studyFilter.valueSteps > 0;
    const splitLineLeft = stageSize.width * clampNavigatorSplitRatio(studyFilter.splitRatio);

    return (
      <div
        ref={panelRef}
        tabIndex={-1}
        data-testid="sub-view-panel"
        data-view-mode={viewMode}
        data-theme-preset={themePreset}
        onDragOver={handleDragOver}
        onDragLeave={handleDragLeave}
        onDrop={handleDrop}
        className="flex flex-col h-full min-h-0 select-none relative bg-ui-panel text-ui-primary focus:outline-none"
      >
        {/* Hidden Local Image Inputs */}
        <input
          ref={fileInputRef}
          data-testid="subview-file-input"
          type="file"
          accept="image/*"
          multiple
          className="hidden"
          onChange={(e) => {
            if (e.target.files && e.target.files.length > 0) {
              void handleFilesSelected(e.target.files);
            }
            e.target.value = '';
          }}
        />
        <input
          ref={reloadInputRef}
          type="file"
          accept="image/*"
          className="hidden"
          onChange={(e) => {
            void handleReloadActiveFile(e.target.files?.[0]);
            e.target.value = '';
          }}
        />

        {/* Top Bar: Reference Import / Paste / Cycling + PureRef Board vs Single Switcher + Palette / List / Delete */}
        <div className="h-6 px-1 flex items-center justify-between gap-1 shrink-0 border-b bg-ui-header border-ui-subtle">
          <div className="flex items-center gap-0.5 min-w-0">
            <button
              type="button"
              data-testid="subview-add-btn"
              onClick={() => fileInputRef.current?.click()}
              title={t('Import Reference Image(s)')}
              className={`${btnBase} w-5 shrink-0`}
            >
              <Plus className="w-3 h-3" />
            </button>
            <button
              type="button"
              data-testid="subview-paste-btn"
              onClick={() => void handlePasteFromClipboard()}
              title={t('Paste Reference from Clipboard (Ctrl+V while hovering)')}
              className={`${btnBase} w-5 shrink-0`}
            >
              <ClipboardPaste className="w-3 h-3" />
            </button>
            <button
              type="button"
              data-testid="subview-prev-btn"
              disabled={items.length <= 1}
              onClick={() => subViewStoreActions.stepActive(-1)}
              title={t('Previous Reference')}
              className={`${btnBase} w-4 shrink-0`}
            >
              <ChevronLeft className="w-3 h-3" />
            </button>
            <span
              data-testid="subview-counter"
              className="text-[10px] font-ui-mono tabular-nums text-ui-muted px-0.5 shrink-0"
            >
              {items.length > 0 ? `${activeIndex + 1}/${items.length}` : '0/0'}
            </span>
            <button
              type="button"
              data-testid="subview-next-btn"
              disabled={items.length <= 1}
              onClick={() => subViewStoreActions.stepActive(1)}
              title={t('Next Reference')}
              className={`${btnBase} w-4 shrink-0`}
            >
              <ChevronRight className="w-3 h-3" />
            </button>
          </div>

          {/* PureRef Board vs Single Focus Mode Toggle */}
          <div
            role="group"
            aria-label={t('Reference View Mode')}
            className="flex items-center rounded-ui-xs bg-ui-input border border-ui-subtle p-[1px] shrink-0"
          >
            <button
              type="button"
              data-testid="subview-mode-board"
              aria-pressed={viewMode === 'board'}
              onClick={() => subViewStoreActions.setViewMode('board')}
              title={t('PureRef Board Mode (multiple simultaneous references in one zoomable & rotatable area)')}
              className={`h-4 px-1 rounded-[2px] text-[9px] flex items-center gap-0.5 transition-colors cursor-pointer ${
                viewMode === 'board'
                  ? 'bg-ui-accent-subtle text-ui-accent font-medium'
                  : 'text-ui-muted hover:text-ui-primary'
              }`}
            >
              <LayoutGrid className="w-2.5 h-2.5" />
              <span>{t('Board')}</span>
            </button>
            <button
              type="button"
              data-testid="subview-mode-single"
              aria-pressed={viewMode === 'single'}
              onClick={() => subViewStoreActions.setViewMode('single')}
              title={t('Single Focus Mode (cycle one reference at a time)')}
              className={`h-4 px-1 rounded-[2px] text-[9px] flex items-center gap-0.5 transition-colors cursor-pointer ${
                viewMode === 'single'
                  ? 'bg-ui-accent-subtle text-ui-accent font-medium'
                  : 'text-ui-muted hover:text-ui-primary'
              }`}
            >
              <Square className="w-2.5 h-2.5" />
              <span>1×</span>
            </button>
          </div>

          <div className="flex items-center gap-0.5 shrink-0">
            <button
              type="button"
              data-testid="subview-palette-toggle"
              disabled={!activeItem}
              onClick={() => subViewStoreActions.toggleShowPalette()}
              aria-pressed={showPalette}
              title={t('Extract Dominant Color Palette')}
              className={`${btnBase} w-5 ${showPalette && activeItem ? btnActive : ''}`}
            >
              <Palette className="w-3 h-3" />
            </button>
            <button
              type="button"
              data-testid="subview-list-toggle"
              disabled={items.length === 0}
              onClick={() => subViewStoreActions.toggleShowList()}
              aria-pressed={showList}
              title={t('Reference List')}
              className={`${btnBase} w-5 ${showList && items.length > 0 ? btnActive : ''}`}
            >
              <List className="w-3 h-3" />
            </button>
            <button
              type="button"
              data-testid="subview-delete-btn"
              disabled={!activeItem}
              onClick={() => activeItem && subViewStoreActions.removeImage(activeItem.id)}
              title={t('Remove Current Reference')}
              className={`${btnBase} w-5 hover:text-ui-danger`}
            >
              <Trash2 className="w-3 h-3" />
            </button>
          </div>
        </div>

        {/* Optional Reference List Strip */}
        {showList && items.length > 0 && (
          <div
            data-testid="subview-list-drawer"
            className="max-h-28 overflow-y-auto shrink-0 border-b px-1 py-0.5 flex flex-col gap-0.5 bg-ui-input border-ui-subtle"
          >
            {items.map((item, idx) => {
              const isSelected = item.id === activeItem?.id;
              return (
                <div
                  key={item.id}
                  data-testid={`subview-list-item-${item.id}`}
                  onClick={() => subViewStoreActions.selectImage(item.id)}
                  onDoubleClick={() => {
                    subViewStoreActions.selectImage(item.id);
                    if (viewMode === 'board') handleFitSelectedCard(item.id);
                  }}
                  className={`flex items-center gap-1 px-1 py-0.5 rounded-ui-xs text-[10px] cursor-pointer transition-colors ${
                    isSelected
                      ? 'bg-ui-control-active text-ui-primary'
                      : 'text-ui-secondary hover:bg-ui-control-hover hover:text-ui-primary'
                  }`}
                >
                  {item.src ? (
                    <img
                      src={item.src}
                      alt=""
                      style={{ filter: item.grayscale ? 'grayscale(100%)' : undefined }}
                      className="w-4 h-4 object-cover rounded-ui-xs shrink-0 bg-ui-void"
                    />
                  ) : (
                    <div className="w-4 h-4 rounded-ui-xs shrink-0 bg-ui-control flex items-center justify-center text-[8px] font-ui-mono tabular-nums">
                      {idx + 1}
                    </div>
                  )}
                  <span className="truncate flex-1" title={item.name}>
                    {item.name}
                  </span>
                  <button
                    type="button"
                    onClick={(e) => {
                      e.stopPropagation();
                      subViewStoreActions.updateCardBoardProps(item.id, {
                        grayscale: !item.grayscale,
                      });
                    }}
                    title={item.grayscale ? t('Disable Card B/W') : t('Per-Card B/W')}
                    className={`px-1 h-4 rounded-ui-xs text-[8.5px] font-ui-mono cursor-pointer ${
                      item.grayscale
                        ? 'bg-ui-accent-subtle text-ui-accent'
                        : 'text-ui-muted hover:text-ui-primary'
                    }`}
                  >
                    {t('BW')}
                  </button>
                  {viewMode === 'board' && (
                    <button
                      type="button"
                      onClick={(e) => {
                        e.stopPropagation();
                        subViewStoreActions.updateCardBoardProps(item.id, {
                          locked: !item.locked,
                        });
                      }}
                      title={item.locked ? t('Unlock Card') : t('Lock Card Position')}
                      className={`w-4 h-4 flex items-center justify-center rounded-ui-xs cursor-pointer ${
                        item.locked
                          ? 'text-ui-warning'
                          : 'text-ui-muted hover:text-ui-primary'
                      }`}
                    >
                      {item.locked ? (
                        <Lock className="w-2.5 h-2.5" />
                      ) : (
                        <Unlock className="w-2.5 h-2.5" />
                      )}
                    </button>
                  )}
                  <span className="text-[8.5px] text-ui-muted font-ui-mono tabular-nums shrink-0">
                    {item.width}×{item.height}
                  </span>
                </div>
              );
            })}
            {items.length > 1 && (
              <div className="flex items-center justify-between pt-0.5 mt-0.5 border-t border-ui-subtle px-0.5">
                <span className="text-[9px] text-ui-muted" data-testid="subview-active-name">
                  {activeItem?.name || t('No reference')}
                </span>
                <button
                  type="button"
                  data-testid="subview-clear-all-btn"
                  onClick={() => subViewStoreActions.clearAll()}
                  className="text-[9px] text-ui-muted hover:text-ui-danger transition-colors cursor-pointer"
                >
                  {t('Clear All')}
                </button>
              </div>
            )}
          </div>
        )}

        {/* Dominant Color Palette Extractor Strip */}
        {showPalette && activeItem && (
          <div
            data-testid="subview-palette-strip"
            className="shrink-0 px-1.5 py-1 border-b border-ui-subtle bg-ui-input flex items-center gap-1"
          >
            <span className="text-[9px] text-ui-muted shrink-0">{t('Key')}</span>
            <div className="flex items-center gap-1 flex-1 min-w-0">
              {extractedSwatches.length > 0 ? (
                extractedSwatches.map((sw) => (
                  <button
                    key={sw.hex}
                    type="button"
                    data-testid={`subview-palette-swatch-${sw.hex}`}
                    onClick={() => {
                      setSampledHex(sw.hex);
                      toolStoreActions.setPrimaryColor(sw.hex, true, colorMode);
                    }}
                    title={t('{hex} · Value {percent}% (Click to pick)', {
                      hex: sw.hex.toUpperCase(),
                      percent: sw.luminance,
                    })}
                    style={{ backgroundColor: sw.hex }}
                    className="flex-1 h-4 min-w-[14px] rounded-ui-xs border border-ui-strong/60 hover:scale-110 transition-transform cursor-pointer"
                  />
                ))
              ) : (
                <span className="text-[9px] text-ui-muted italic">{t('No swatches')}</span>
              )}
            </div>
          </div>
        )}

        {/* Reference Viewport Stage */}
        <div
          ref={stageRef}
          data-testid="subview-stage"
          onPointerEnter={() => setIsHoveringStage(true)}
          onPointerLeave={() => {
            setIsHoveringStage(false);
            setSampledHex(null);
          }}
          onPointerDown={handleStagePointerDown}
          onPointerMove={handleStagePointerMove}
          onPointerUp={finishStageInteraction}
          onPointerCancel={finishStageInteraction}
          onDoubleClick={handleStageDoubleClick}
          className={`relative flex-1 min-h-[96px] overflow-hidden flex items-center justify-center ${stageCursorClass} ${
            isDragOverFiles
              ? 'ring-2 ring-inset ring-ui-accent bg-ui-accent-subtle'
              : 'bg-ui-void'
          }`}
        >
          <canvas
            ref={displayCanvasRef}
            data-testid="subview-canvas"
            className="absolute inset-0 w-full h-full pointer-events-none"
          />

          {/* Floating Study Bar RIGHT ON TOP OF THE REFERENCE (B/W, Split B/W, Value Notan, Squint, Grid, Tone) */}
          {items.length > 0 && (
            <div
              data-testid="subview-study-overlay"
              onPointerDown={(e) => e.stopPropagation()}
              onClick={(e) => e.stopPropagation()}
              onDoubleClick={(e) => e.stopPropagation()}
              className="absolute top-1.5 left-1.5 z-20 flex flex-col items-start gap-1 max-w-[calc(100%-12px)]"
            >
              <div className="flex items-center gap-0.5 px-1 py-0.5 rounded-ui-sm bg-ui-floating/95 backdrop-blur-sm border border-ui-default shadow-ui-floating flex-wrap">
                {/* Primary B/W Perceptual Value Toggle */}
                <button
                  type="button"
                  data-testid="subview-bw-toggle"
                  aria-pressed={isBwActive}
                  onClick={() => subViewStoreActions.toggleGrayscale()}
                  title={t('Toggle Perceptual Black & White Value Study (Shortcut: G)')}
                  className={`h-4 px-1.5 rounded-ui-xs text-[9.5px] font-medium flex items-center gap-1 transition-colors cursor-pointer ${
                    isBwActive
                      ? 'bg-ui-accent text-ui-accent-contrast'
                      : 'text-ui-secondary hover:text-ui-primary hover:bg-ui-control-hover'
                  }`}
                >
                  <Contrast className="w-2.5 h-2.5" />
                  <span>{t('B/W')}</span>
                </button>

                {/* Split Color | B/W Curtain Toggle */}
                <button
                  type="button"
                  data-testid="subview-split-bw-toggle"
                  aria-pressed={studyFilter.splitBw}
                  onClick={() => subViewStoreActions.toggleSplitBw()}
                  title={t('Split Compare: Color | Perceptual B/W')}
                  className={`h-4 px-1 rounded-ui-xs text-[9px] flex items-center justify-center transition-colors cursor-pointer ${
                    studyFilter.splitBw
                      ? 'bg-ui-accent-subtle text-ui-accent ring-1 ring-inset ring-ui-accent-border'
                      : 'text-ui-icon-muted hover:text-ui-primary hover:bg-ui-control-hover'
                  }`}
                >
                  <Columns2 className="w-2.5 h-2.5" />
                </button>

                {/* Notan / Value Posterize Grouping (Off -> 2V Notan -> 3V -> 5V) */}
                <button
                  type="button"
                  data-testid="subview-value-steps"
                  aria-pressed={studyFilter.valueSteps > 0}
                  onClick={() => subViewStoreActions.cycleValueSteps()}
                  title={t('Light & Shape Study Value Grouping (Off → 2-Value Notan → 3-Value → 5-Value)')}
                  className={`h-4 px-1 rounded-ui-xs text-[9px] font-ui-mono tabular-nums flex items-center justify-center transition-colors cursor-pointer ${
                    studyFilter.valueSteps > 0
                      ? 'bg-ui-accent-subtle text-ui-accent ring-1 ring-inset ring-ui-accent-border'
                      : 'text-ui-icon-muted hover:text-ui-primary hover:bg-ui-control-hover'
                  }`}
                >
                  {t(VALUE_STEP_LABELS[studyFilter.valueSteps])}
                </button>

                {/* Squint Blur Toggle */}
                <button
                  type="button"
                  data-testid="subview-squint-toggle"
                  aria-pressed={studyFilter.squintBlur}
                  onClick={() => subViewStoreActions.toggleSquintBlur()}
                  title={t('Squint Blur (Simplify fine details to read big shapes & masses)')}
                  className={`h-4 px-1 rounded-ui-xs text-[9px] flex items-center justify-center transition-colors cursor-pointer ${
                    studyFilter.squintBlur
                      ? 'bg-ui-accent-subtle text-ui-accent ring-1 ring-inset ring-ui-accent-border'
                      : 'text-ui-icon-muted hover:text-ui-primary hover:bg-ui-control-hover'
                  }`}
                >
                  <Sparkles className="w-2.5 h-2.5" />
                </button>

                {/* Proportional Measuring Grid Overlay */}
                <button
                  type="button"
                  data-testid="subview-grid-toggle"
                  aria-pressed={studyFilter.gridMode !== 'none'}
                  onClick={() => subViewStoreActions.cycleGridMode()}
                  title={t('Proportional Grid Overlay: {mode} (Click to cycle)', {
                    mode: t(GRID_MODE_LABELS[studyFilter.gridMode]),
                  })}
                  className={`h-4 px-1 rounded-ui-xs text-[9px] font-ui-mono flex items-center gap-0.5 transition-colors cursor-pointer ${
                    studyFilter.gridMode !== 'none'
                      ? 'bg-ui-accent-subtle text-ui-accent ring-1 ring-inset ring-ui-accent-border'
                      : 'text-ui-icon-muted hover:text-ui-primary hover:bg-ui-control-hover'
                  }`}
                >
                  <Grid3x3 className="w-2.5 h-2.5" />
                  {studyFilter.gridMode !== 'none' && (
                    <span>{GRID_MODE_LABELS[studyFilter.gridMode]}</span>
                  )}
                </button>

                {/* Light / Tone Fine-Tuning Popover Toggle */}
                <button
                  type="button"
                  data-testid="subview-tone-toggle"
                  aria-pressed={showTonePopover || hasToneAdjust}
                  onClick={() => setShowTonePopover((p) => !p)}
                  title={t('Light & Shape Study Settings (Notan Threshold, Brightness, Contrast)')}
                  className={`h-4 w-4 rounded-ui-xs flex items-center justify-center transition-colors cursor-pointer ${
                    showTonePopover || hasToneAdjust
                      ? 'bg-ui-accent-subtle text-ui-accent'
                      : 'text-ui-icon-muted hover:text-ui-primary hover:bg-ui-control-hover'
                  }`}
                >
                  <SlidersHorizontal className="w-2.5 h-2.5" />
                </button>
              </div>

              {/* Light & Shape Study Popover */}
              {showTonePopover && (
                <div
                  data-testid="subview-tone-popover"
                  className="w-44 p-2 rounded-ui-md bg-ui-elevated/95 backdrop-blur-sm border border-ui-default shadow-ui-popover space-y-1.5 text-[10px]"
                >
                  <div className="flex items-center justify-between">
                    <span className="text-[9.5px] font-medium text-ui-primary">{t('Light & Shape Study')}</span>
                    <button
                      type="button"
                      onClick={() => setShowTonePopover(false)}
                      className="text-ui-muted hover:text-ui-primary cursor-pointer"
                    >
                      <X className="w-3 h-3" />
                    </button>
                  </div>

                  {/* Quick Value Step Pills */}
                  <div className="flex items-center gap-1">
                    {([0, 2, 3, 5] as const).map((steps) => (
                      <button
                        key={steps}
                        type="button"
                        onClick={() => subViewStoreActions.setValueSteps(steps)}
                        className={`flex-1 h-4 rounded-ui-xs text-[9px] font-ui-mono cursor-pointer transition-colors ${
                          studyFilter.valueSteps === steps
                            ? 'bg-ui-accent text-ui-accent-contrast font-medium'
                            : 'bg-ui-input text-ui-secondary hover:text-ui-primary border border-ui-subtle'
                        }`}
                      >
                        {steps === 0 ? tc('subView', 'Full') : t(VALUE_STEP_LABELS[steps])}
                      </button>
                    ))}
                  </div>

                  {studyFilter.valueSteps > 0 && (
                    <label className="block space-y-0.5">
                      <div className="flex justify-between text-[9px] text-ui-muted">
                        <span>{t('Notan Pivot')}</span>
                        <span className="font-ui-mono tabular-nums">{studyFilter.notanThreshold}</span>
                      </div>
                      <input
                        type="range"
                        data-testid="subview-notan-slider"
                        min={16}
                        max={240}
                        value={studyFilter.notanThreshold}
                        onChange={(e) =>
                          subViewStoreActions.updateStudyFilter({
                            notanThreshold: Number(e.target.value),
                          })
                        }
                        className="w-full h-1 accent-[var(--ui-accent)] cursor-pointer"
                      />
                    </label>
                  )}

                  <label className="block space-y-0.5">
                    <div className="flex justify-between text-[9px] text-ui-muted">
                      <span>{t('Brightness')}</span>
                      <span className="font-ui-mono tabular-nums">
                        {studyFilter.brightness > 0
                          ? `+${studyFilter.brightness}`
                          : studyFilter.brightness}
                      </span>
                    </div>
                    <input
                      type="range"
                      data-testid="subview-brightness-slider"
                      min={-100}
                      max={100}
                      value={studyFilter.brightness}
                      onChange={(e) =>
                        subViewStoreActions.updateStudyFilter({
                          brightness: Number(e.target.value),
                        })
                      }
                      className="w-full h-1 accent-[var(--ui-accent)] cursor-pointer"
                    />
                  </label>

                  <label className="block space-y-0.5">
                    <div className="flex justify-between text-[9px] text-ui-muted">
                      <span>{t('Contrast')}</span>
                      <span className="font-ui-mono tabular-nums">
                        {studyFilter.contrast > 0
                          ? `+${studyFilter.contrast}`
                          : studyFilter.contrast}
                      </span>
                    </div>
                    <input
                      type="range"
                      data-testid="subview-contrast-slider"
                      min={-100}
                      max={100}
                      value={studyFilter.contrast}
                      onChange={(e) =>
                        subViewStoreActions.updateStudyFilter({
                          contrast: Number(e.target.value),
                        })
                      }
                      className="w-full h-1 accent-[var(--ui-accent)] cursor-pointer"
                    />
                  </label>

                  <div className="flex items-center justify-between pt-0.5 border-t border-ui-subtle">
                    <button
                      type="button"
                      data-testid="subview-sample-tone-toggle"
                      onClick={() => subViewStoreActions.toggleSampleDisplayTone()}
                      title={t('When enabled, eyedropper picks the filtered B/W or Notan tone instead of the original color')}
                      className={`text-[9px] px-1.5 py-0.5 rounded-ui-xs cursor-pointer transition-colors ${
                        sampleDisplayTone
                          ? 'bg-ui-accent-subtle text-ui-accent'
                          : 'text-ui-muted hover:text-ui-primary'
                      }`}
                    >
                      {sampleDisplayTone ? t('Pick: Study Tone') : t('Pick: Original')}
                    </button>
                    <button
                      type="button"
                      data-testid="subview-reset-study-btn"
                      onClick={() => subViewStoreActions.resetStudyFilter()}
                      className="text-[9px] text-ui-muted hover:text-ui-primary cursor-pointer"
                    >
                      {t('Reset')}
                    </button>
                  </div>
                </div>
              )}
            </div>
          )}

          {/* Split Color | B/W Draggable Divider Handle */}
          {items.length > 0 && studyFilter.splitBw && (
            <>
              <span className="pointer-events-none absolute bottom-1.5 left-1.5 z-10 px-1 py-[1px] rounded-ui-xs bg-ui-floating border border-ui-default text-[8px] font-ui-mono uppercase text-ui-primary">
                {t('CLR')}
              </span>
              <span className="pointer-events-none absolute bottom-1.5 right-1.5 z-10 px-1 py-[1px] rounded-ui-xs bg-ui-floating border border-ui-default text-[8px] font-ui-mono uppercase text-ui-primary">
                {t('B/W')}
              </span>
              <div
                role="slider"
                tabIndex={0}
                data-testid="subview-split-handle"
                aria-label={t('Reference Color and B/W Split Position')}
                aria-valuemin={5}
                aria-valuemax={95}
                aria-valuenow={Math.round(studyFilter.splitRatio * 100)}
                onPointerDown={handleSplitPointerDown}
                onPointerMove={handleSplitPointerMove}
                onPointerUp={finishSplitDrag}
                onPointerCancel={finishSplitDrag}
                onDoubleClick={(e) => {
                  e.stopPropagation();
                  subViewStoreActions.updateStudyFilter({ splitRatio: 0.5 }, true);
                }}
                style={{ left: `${splitLineLeft}px` }}
                title={t('Drag to compare Color | B/W (Double-click to center)')}
                className="absolute top-0 bottom-0 z-20 w-3 -ml-1.5 flex items-center justify-center cursor-ew-resize group"
              >
                <div className="w-[1.5px] h-full bg-white/85 shadow-[0_0_2px_rgba(0,0,0,0.85)] group-hover:bg-ui-accent transition-colors" />
                <div className="absolute w-3.5 h-3.5 rounded-full bg-ui-floating border border-ui-strong shadow-ui-floating flex items-center justify-center">
                  <Columns2 className="w-2 h-2 text-ui-primary" />
                </div>
              </div>
            </>
          )}

          {/* PureRef Selected Card Quick Floating Micro-Toolbar */}
          {viewMode === 'board' && activeItem && !studyFilter.splitBw && (
            <div
              data-testid="subview-card-toolbar"
              onPointerDown={(e) => e.stopPropagation()}
              onClick={(e) => e.stopPropagation()}
              onDoubleClick={(e) => e.stopPropagation()}
              className="absolute bottom-1.5 left-1.5 z-20 flex items-center gap-0.5 px-1 py-0.5 rounded-ui-sm bg-ui-floating/90 backdrop-blur-sm border border-ui-default shadow-ui-floating max-w-[calc(100%-12px)]"
            >
              <button
                type="button"
                data-testid="subview-card-bw-toggle"
                aria-pressed={activeItem.grayscale}
                onClick={() =>
                  subViewStoreActions.updateCardBoardProps(activeItem.id, {
                    grayscale: !activeItem.grayscale,
                  })
                }
                title={t('Toggle Per-Card B/W (independent of other references)')}
                className={`h-4 px-1 rounded-ui-xs text-[8.5px] font-ui-mono cursor-pointer transition-colors ${
                  activeItem.grayscale
                    ? 'bg-ui-accent text-ui-accent-contrast font-medium'
                    : 'text-ui-icon-muted hover:text-ui-primary hover:bg-ui-control-hover'
                }`}
              >
                {t('BW')}
              </button>
              <button
                type="button"
                data-testid="subview-card-flip-h"
                aria-pressed={activeItem.boardFlipX}
                onClick={() =>
                  subViewStoreActions.updateCardBoardProps(activeItem.id, {
                    boardFlipX: !activeItem.boardFlipX,
                  })
                }
                title={t('Flip Selected Reference Horizontally')}
                className={`h-4 w-4 rounded-ui-xs flex items-center justify-center cursor-pointer transition-colors ${
                  activeItem.boardFlipX
                    ? 'bg-ui-accent-subtle text-ui-accent'
                    : 'text-ui-icon-muted hover:text-ui-primary hover:bg-ui-control-hover'
                }`}
              >
                <FlipHorizontal className="w-2.5 h-2.5" />
              </button>
              <button
                type="button"
                data-testid="subview-card-flip-v"
                aria-pressed={activeItem.boardFlipY}
                onClick={() =>
                  subViewStoreActions.updateCardBoardProps(activeItem.id, {
                    boardFlipY: !activeItem.boardFlipY,
                  })
                }
                title={t('Flip Selected Reference Vertically')}
                className={`h-4 w-4 rounded-ui-xs flex items-center justify-center cursor-pointer transition-colors ${
                  activeItem.boardFlipY
                    ? 'bg-ui-accent-subtle text-ui-accent'
                    : 'text-ui-icon-muted hover:text-ui-primary hover:bg-ui-control-hover'
                }`}
              >
                <FlipVertical className="w-2.5 h-2.5" />
              </button>
              <button
                type="button"
                data-testid="subview-card-opacity"
                onClick={() => {
                  const nextOp =
                    activeItem.opacity > 0.85 ? 0.65 : activeItem.opacity > 0.45 ? 0.35 : 1;
                  subViewStoreActions.updateCardBoardProps(activeItem.id, { opacity: nextOp });
                }}
                title={t('Card Opacity: {percent}% (Click to cycle)', {
                  percent: Math.round(activeItem.opacity * 100),
                })}
                className="h-4 px-1 rounded-ui-xs text-[8.5px] font-ui-mono tabular-nums text-ui-icon-muted hover:text-ui-primary hover:bg-ui-control-hover cursor-pointer"
              >
                {`${Math.round(activeItem.opacity * 100)}%`}
              </button>
              <button
                type="button"
                data-testid="subview-card-front"
                onClick={() => subViewStoreActions.bringCardToFront(activeItem.id)}
                title={t('Bring Card to Front')}
                className="h-4 w-4 rounded-ui-xs flex items-center justify-center text-ui-icon-muted hover:text-ui-primary hover:bg-ui-control-hover cursor-pointer"
              >
                <BringToFront className="w-2.5 h-2.5" />
              </button>
              <button
                type="button"
                data-testid="subview-card-back"
                onClick={() => subViewStoreActions.sendCardToBack(activeItem.id)}
                title={t('Send Card to Back')}
                className="h-4 w-4 rounded-ui-xs flex items-center justify-center text-ui-icon-muted hover:text-ui-primary hover:bg-ui-control-hover cursor-pointer"
              >
                <SendToBack className="w-2.5 h-2.5" />
              </button>
              <button
                type="button"
                data-testid="subview-card-duplicate"
                onClick={() => subViewStoreActions.duplicateCard(activeItem.id)}
                title={t('Duplicate Reference Card')}
                className="h-4 w-4 rounded-ui-xs flex items-center justify-center text-ui-icon-muted hover:text-ui-primary hover:bg-ui-control-hover cursor-pointer"
              >
                <Copy className="w-2.5 h-2.5" />
              </button>
              <button
                type="button"
                data-testid="subview-card-lock"
                aria-pressed={activeItem.locked}
                onClick={() =>
                  subViewStoreActions.updateCardBoardProps(activeItem.id, {
                    locked: !activeItem.locked,
                  })
                }
                title={activeItem.locked ? t('Unlock Card') : t('Lock Card')}
                className={`h-4 w-4 rounded-ui-xs flex items-center justify-center cursor-pointer transition-colors ${
                  activeItem.locked
                    ? 'text-ui-warning bg-ui-warning/15'
                    : 'text-ui-icon-muted hover:text-ui-primary hover:bg-ui-control-hover'
                }`}
              >
                {activeItem.locked ? (
                  <Lock className="w-2.5 h-2.5" />
                ) : (
                  <Unlock className="w-2.5 h-2.5" />
                )}
              </button>
              <button
                type="button"
                data-testid="subview-card-focus"
                onClick={() => handleFitSelectedCard(activeItem.id)}
                title={t('Focus / Fit Selected Card')}
                className="h-4 w-4 rounded-ui-xs flex items-center justify-center text-ui-icon-muted hover:text-ui-primary hover:bg-ui-control-hover cursor-pointer"
              >
                <Focus className="w-2.5 h-2.5" />
              </button>
            </div>
          )}

          {/* Empty State / Drop Target */}
          {items.length === 0 && (
            <div className="z-10 flex flex-col items-center gap-1.5 px-3 text-center">
              <button
                type="button"
                data-testid="subview-empty-dropzone"
                onClick={() => fileInputRef.current?.click()}
                className="flex flex-col items-center gap-1 px-3 py-2 rounded-ui-sm border border-dashed border-ui-default hover:border-ui-accent text-ui-muted hover:text-ui-primary transition-colors cursor-pointer"
              >
                <ImagePlus className="w-4 h-4 opacity-75" />
                <span className="text-[10px]">{t('Drop images, click +, or Ctrl+V')}</span>
              </button>
              <span className="text-[9px] text-ui-muted/80">
                {t('PureRef Board · Multi-ref · B/W & Notan Study')}
              </span>
            </div>
          )}

          {/* Persisted Metadata-Only Slot (Single mode) */}
          {viewMode === 'single' && activeItem && !activeItem.src && (
            <div className="z-10 flex flex-col items-center gap-1 px-2 text-center">
              <span className="text-[10px] text-ui-secondary">
                {t('{name} (reload file)', { name: activeItem.name })}
              </span>
              <button
                type="button"
                onClick={() => reloadInputRef.current?.click()}
                className="h-5 px-2 rounded-ui-sm bg-ui-control hover:bg-ui-control-hover border border-ui-subtle text-[10px] text-ui-primary flex items-center gap-1 cursor-pointer transition-colors"
              >
                <RefreshCw className="w-3 h-3" />
                <span>{t('Re-open')}</span>
              </button>
            </div>
          )}

          {/* Error Pill */}
          {loadError && (
            <div className="absolute bottom-7 left-1.5 right-1.5 z-30 px-1.5 py-0.5 rounded-ui-xs bg-ui-elevated border border-ui-danger/50 text-[9px] text-ui-danger flex items-center justify-between gap-1">
              <span className="truncate">{loadError}</span>
              <button
                type="button"
                onClick={() => setLoadError(null)}
                className="shrink-0 hover:text-ui-primary cursor-pointer"
              >
                <X className="w-2.5 h-2.5" />
              </button>
            </div>
          )}

          {/* Live Sampled Color Swatch Pill (with Perceptual Value %) */}
          {sampledHex && (
            <div
              data-testid="subview-sampled-pill"
              className="absolute top-1.5 right-1.5 z-20 px-1.5 py-0.5 rounded-ui-sm bg-ui-floating border border-ui-default flex items-center gap-1 pointer-events-none shadow-ui-floating"
            >
              <span
                className="w-2.5 h-2.5 rounded-ui-xs border border-ui-strong shrink-0"
                style={{ backgroundColor: sampledHex }}
              />
              <span className="text-[9px] font-ui-mono tabular-nums text-ui-primary uppercase">
                {sampledHex}
              </span>
              {sampledValuePct !== null && (
                <span className="text-[8.5px] font-ui-mono tabular-nums text-ui-muted">
                  V{sampledValuePct}
                </span>
              )}
            </div>
          )}
        </div>

        {/* Bottom Compact Control Bar (Strictly Local Viewport Transforms + Auto-Arrange + Tools) */}
        <div className="shrink-0 px-1.5 py-1 flex items-center justify-between gap-0.5 flex-wrap border-t bg-ui-header border-ui-subtle relative">
          {/* Zoom + Fit + Auto-Arrange (Board mode) */}
          <div className="flex items-center gap-0.5">
            <button
              type="button"
              data-testid="subview-zoom-out"
              disabled={items.length === 0}
              onClick={() => handleSubZoomBy(1 / 1.25)}
              title={t('References Zoom Out')}
              className={`${btnBase} w-5`}
            >
              <ZoomOut className="w-3 h-3" />
            </button>
            <button
              type="button"
              data-testid="subview-zoom-in"
              disabled={items.length === 0}
              onClick={() => handleSubZoomBy(1.25)}
              title={t('References Zoom In')}
              className={`${btnBase} w-5`}
            >
              <ZoomIn className="w-3 h-3" />
            </button>
            <button
              type="button"
              data-testid="subview-fit"
              disabled={items.length === 0}
              onClick={handleSubFit}
              title={
                viewMode === 'board'
                  ? t('Fit All References & Reset Board View (Shortcut: F)')
                  : t('Reset Reference View (Fit, 0°, Unflip)')
              }
              className={`${btnBase} w-5`}
            >
              <Maximize className="w-3 h-3" />
            </button>

            {viewMode === 'board' && (
              <div className="relative">
                <button
                  type="button"
                  data-testid="subview-arrange-btn"
                  disabled={items.length === 0}
                  onClick={() => setShowArrangeMenu((p) => !p)}
                  title={t('Auto-Arrange PureRef Board (Pack Grid, Row, Column)')}
                  className={`${btnBase} w-5 ${showArrangeMenu ? btnActive : ''}`}
                >
                  <LayoutGrid className="w-3 h-3" />
                </button>
                {showArrangeMenu && (
                  <div
                    data-testid="subview-arrange-menu"
                    className="absolute bottom-6 left-0 z-30 min-w-28 p-1 rounded-ui-md bg-ui-elevated border border-ui-default shadow-ui-popover flex flex-col gap-0.5 text-[10px]"
                  >
                    <button
                      type="button"
                      data-testid="subview-arrange-grid"
                      onClick={() => handleArrangeBoard('grid')}
                      className="flex items-center gap-1.5 px-1.5 py-1 rounded-ui-xs text-left hover:bg-ui-control-hover cursor-pointer"
                    >
                      <LayoutGrid className="w-3 h-3 text-ui-icon-muted" />
                      <span>{t('Pack Grid')}</span>
                    </button>
                    <button
                      type="button"
                      data-testid="subview-arrange-row"
                      onClick={() => handleArrangeBoard('row')}
                      className="flex items-center gap-1.5 px-1.5 py-1 rounded-ui-xs text-left hover:bg-ui-control-hover cursor-pointer"
                    >
                      <Columns3 className="w-3 h-3 text-ui-icon-muted" />
                      <span>{t('Horizontal Strip')}</span>
                    </button>
                    <button
                      type="button"
                      data-testid="subview-arrange-column"
                      onClick={() => handleArrangeBoard('column')}
                      className="flex items-center gap-1.5 px-1.5 py-1 rounded-ui-xs text-left hover:bg-ui-control-hover cursor-pointer"
                    >
                      <Rows3 className="w-3 h-3 text-ui-icon-muted" />
                      <span>{t('Vertical Stack')}</span>
                    </button>
                  </div>
                )}
              </div>
            )}
          </div>

          {/* Rotate + Flip H */}
          <div className="flex items-center gap-0.5">
            <button
              type="button"
              data-testid="subview-rotate-left"
              disabled={items.length === 0}
              onClick={() => handleSubRotateBy(-15)}
              title={t('Rotate Left (-15°, or Shift+Wheel)')}
              className={`${btnBase} w-5`}
            >
              <RotateCcw className="w-3 h-3" />
            </button>
            <button
              type="button"
              data-testid="subview-reset-rotation"
              disabled={items.length === 0}
              onClick={handleSubResetRotation}
              title={t('Reset Rotation (0°)')}
              className={`${btnBase} px-1 font-ui-mono tabular-nums`}
            >
              {`${Math.round(activeTransform?.rotation ?? 0)}°`}
            </button>
            <button
              type="button"
              data-testid="subview-rotate-right"
              disabled={items.length === 0}
              onClick={() => handleSubRotateBy(15)}
              title={t('Rotate Right (+15°, or Shift+Wheel)')}
              className={`${btnBase} w-5`}
            >
              <RotateCw className="w-3 h-3" />
            </button>
            <button
              type="button"
              data-testid="subview-flip-h"
              disabled={items.length === 0}
              aria-pressed={Boolean(activeTransform?.flipX)}
              onClick={handleSubToggleFlipX}
              title={t('Flip View Horizontally (Shortcut: H)')}
              className={`${btnBase} w-5 ${activeTransform?.flipX ? btnActive : ''}`}
            >
              <FlipHorizontal className="w-3 h-3" />
            </button>
          </div>

          {/* Tool Controls: Board (Arrange / Pan / Eyedropper) vs Single (Auto Eyedropper / Pan) */}
          <div className="flex items-center gap-0.5">
            {viewMode === 'board' ? (
              <>
                <button
                  type="button"
                  data-testid="subview-tool-select"
                  aria-pressed={boardTool === 'select'}
                  onClick={() => subViewStoreActions.setBoardTool('select')}
                  title={t('Arrange Cards (Drag cards to move, drag corners to resize, top handle to rotate; drag empty space to pan)')}
                  className={`${btnBase} w-5 ${boardTool === 'select' ? btnActive : ''}`}
                >
                  <MousePointer2 className="w-3 h-3" />
                </button>
                <button
                  type="button"
                  data-testid="subview-tool-pan"
                  aria-pressed={boardTool === 'pan'}
                  onClick={() => subViewStoreActions.setBoardTool('pan')}
                  title={t('Pan Board (or hold Space / Middle-click anywhere)')}
                  className={`${btnBase} w-5 ${boardTool === 'pan' ? btnActive : ''}`}
                >
                  <Hand className="w-3 h-3" />
                </button>
                <button
                  type="button"
                  data-testid="subview-auto-eyedropper"
                  aria-pressed={boardTool === 'eyedrop'}
                  onClick={() =>
                    subViewStoreActions.setBoardTool(boardTool === 'eyedrop' ? 'select' : 'eyedrop')
                  }
                  title={t('Eyedropper Mode (Click any reference to pick color; Alt+Click works from any tool)')}
                  className={`${btnBase} gap-0.5 px-1 ${boardTool === 'eyedrop' ? btnActive : ''}`}
                >
                  <Pipette className="w-3 h-3" />
                  <span>{t('Pick')}</span>
                </button>
              </>
            ) : (
              <>
                <button
                  type="button"
                  data-testid="subview-auto-eyedropper"
                  aria-pressed={autoEyedropper}
                  onClick={() => subViewStoreActions.toggleAutoEyedropper()}
                  title={t('Switch to Eyedropper Automatically on Hover/Click (CSP mode)')}
                  className={`${btnBase} gap-0.5 px-1 ${autoEyedropper ? btnActive : ''}`}
                >
                  <Pipette className="w-3 h-3" />
                  <span>{t('Auto')}</span>
                </button>
                {!autoEyedropper && (
                  <button
                    type="button"
                    data-testid="subview-mode-toggle"
                    aria-pressed={manualEyedropper}
                    onClick={() => subViewStoreActions.setManualEyedropper(!manualEyedropper)}
                    title={
                      manualEyedropper
                        ? t('Eyedropper Active (click for Pan)')
                        : t('Pan Active (click for Eyedropper)')
                    }
                    className={`${btnBase} w-5 ${manualEyedropper ? btnActive : ''}`}
                  >
                    {manualEyedropper ? (
                      <Pipette className="w-3 h-3" />
                    ) : (
                      <Hand className="w-3 h-3" />
                    )}
                  </button>
                )}
              </>
            )}
          </div>
        </div>
      </div>
    );
  }
);

SubViewPanel.displayName = 'SubViewPanel';