Skip to content

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

118 KB
Raw Blame
import React, { useState, useRef, useEffect, useCallback } from 'react';
import { createPortal } from 'react-dom';
import {
  ChevronsLeft,
  ChevronsRight,
  ChevronUp,
  ChevronDown,
  Paintbrush,
  Sliders,
  SlidersHorizontal,
  CircleDot,
  Palette,
  SwatchBook,
  Clock,
  Layers,
  History,
  Zap,
  Wrench,
  MoreHorizontal,
  ArrowLeftToLine,
  ArrowRightToLine,
  ArrowDownToLine,
  Columns2,
  X,
  PanelLeft,
  PanelRight,
  Compass,
  Images,
  Info,
  Play,
  PinOff,
  Minus,
} from 'lucide-react';
import { CanvasColorMode, CspBrush } from '../types/editor';
import { ThemePreset } from '../types/settings';
import {
  BOTTOM_DOCK_COL_ID,
  DOCK_PANEL_META,
  DockBottomZone,
  DockColumn,
  DockGroup,
  DockPanelId,
  DockSide,
  DockSplitCell,
  WorkspaceLayout,
} from '../types/workspace';
import { getGroupCells } from '../utils/workspacePresets';
import {
  acquireWorkspaceInteractionLock,
  ensureGlobalChromeScrollbarGuard,
} from '../utils/workspacePointerGuard';
import {
  CUSTOM_BRUSHES_CHANGED_EVENT,
  getCachedCustomBrushes,
  loadCustomBrushes,
  preloadTipImage,
} from '../utils/brushStorage';
import {
  DEFAULT_BRUSH_PRESET_ID,
  ERASER_PRESET_ID,
  getEffectiveBrushSettings,
  resetBrushSettingsToDefault,
} from '../utils/brushPresetManager';
import {
  toolStoreActions,
  useToolStore,
  useWorkspaceStore,
  workspaceStoreActions,
} from '../stores';
import { ToolStrip } from './ToolStrip';
import { SubToolList } from './SubToolList';
import { ToolPropertyInspector } from './ToolPropertyInspector';
import { BrushSizePalette } from './BrushSizePalette';
import { RightSidebar, RightSidebarColorSection, RightSidebarProps } from './RightSidebar';
import { ColorSlider } from './ColorSlider';
import { ColorSetsPanel } from './ColorSetsPanel';
import { ColorHistoryPanel } from './ColorHistoryPanel';
import { QuickAccessPanel } from './QuickAccessPanel';
import { QuickBrushPanel } from './QuickBrushPanel';
import { NavigatorPanel, NavigatorPanelProps } from './NavigatorPanel';
import { SubViewPanel } from './SubViewPanel';
import { InfoPanel } from './InfoPanel';
import { AutoActionPanel, AutoActionPanelProps } from './AutoActionPanel';
import { WorkspaceCommandHandlers } from './CommandBar';
import { FloatingPanelWindow, FLOATING_HEADER_HEIGHT } from './FloatingPanelWindow';
import { FocusModeOverlay } from './focus';
import { isImeComposing, t as translate, td as translateData, useI18n } from '../i18n';

const DND_PANEL_MIME = 'application/x-inkstudio-panel';

export function renderPanelIcon(panelId: DockPanelId, className = 'w-3.5 h-3.5'): React.ReactNode {
  switch (panelId) {
    case 'tools':
      return <Wrench className={className} />;
    case 'subtool':
      return <Paintbrush className={className} />;
    case 'tool-property':
      return <Sliders className={className} />;
    case 'brush-size':
      return <CircleDot className={className} />;
    case 'navigator':
      return <Compass className={className} />;
    case 'sub-view':
      return <Images className={className} />;
    case 'info':
      return <Info className={className} />;
    case 'color':
      return <Palette className={className} />;
    case 'color-sliders':
      return <SlidersHorizontal className={className} />;
    case 'color-sets':
      return <SwatchBook className={className} />;
    case 'color-history':
      return <Clock className={className} />;
    case 'layers':
      return <Layers className={className} />;
    case 'history':
      return <History className={className} />;
    case 'quick-access':
      return <Zap className={className} />;
    case 'auto-actions':
      return <Play className={className} />;
  }
}

function useSharedCustomBrushes(): [CspBrush[], React.Dispatch<React.SetStateAction<CspBrush[]>>] {
  const [customBrushes, setCustomBrushes] = useState<CspBrush[]>(() => getCachedCustomBrushes());

  useEffect(() => {
    let active = true;
    loadCustomBrushes().then((brushes) => {
      if (!active) return;
      setCustomBrushes(brushes);
      for (const b of brushes) {
        if (b.tipDataUrl) preloadTipImage(b.tipDataUrl).catch(() => {});
        if (b.secondaryTipDataUrl) preloadTipImage(b.secondaryTipDataUrl).catch(() => {});
        if (b.subTips) {
          for (const st of b.subTips) {
            if (st.dataUrl) preloadTipImage(st.dataUrl).catch(() => {});
          }
        }
        if (b.paperTexture) preloadTipImage(b.paperTexture).catch(() => {});
      }
    });
    const handleChanged = () => setCustomBrushes([...getCachedCustomBrushes()]);
    window.addEventListener(CUSTOM_BRUSHES_CHANGED_EVENT, handleChanged);
    return () => {
      active = false;
      window.removeEventListener(CUSTOM_BRUSHES_CHANGED_EVENT, handleChanged);
    };
  }, []);

  return [customBrushes, setCustomBrushes];
}

/** Isolated BrushSizePalette wrapper so brush size changes never re-render dock chrome or layers */
const BrushSizeDockedContent: React.FC<{ themePreset: ThemePreset }> = React.memo(
  ({ themePreset }) => {
    const { t } = useI18n();
    const size = useToolStore((s) => s.brushSettings.size);
    const brushName = useToolStore((s) => s.brushSettings.brushName);
    const preset = useToolStore((s) => s.brushSettings.preset);
    const tool = useToolStore((s) => s.tool);

    const activePresetId =
      tool === 'eraser' ? ERASER_PRESET_ID : preset || DEFAULT_BRUSH_PRESET_ID;

    const handleSelectSize = useCallback((nextSize: number) => {
      toolStoreActions.updateBrushSettings({ size: nextSize });
    }, []);

    const handleResetSize = useCallback(() => {
      const defaults = getEffectiveBrushSettings(activePresetId);
      if (defaults.size !== undefined) {
        toolStoreActions.updateBrushSettings({ size: defaults.size });
      }
    }, [activePresetId]);

    const handleResetAll = useCallback(() => {
      const restored = resetBrushSettingsToDefault(activePresetId, getCachedCustomBrushes());
      toolStoreActions.updateBrushSettings(restored);
    }, [activePresetId]);

    return (
      <BrushSizePalette
        currentSize={size}
        onSelectSize={handleSelectSize}
        activeBrushName={brushName || (tool === 'eraser' ? t('Eraser') : String(preset || t('Brush')))}
        tool={tool}
        presetId={activePresetId}
        onResetSizeToDefault={handleResetSize}
        onResetAllSettings={handleResetAll}
        themePreset={themePreset}
      />
    );
  }
);
BrushSizeDockedContent.displayName = 'BrushSizeDockedContent';

/** Isolated standalone Color Sliders palette wrapper so brush/layer changes never re-render it */
const ColorSliderDockedContent: React.FC<{
  colorMode: CanvasColorMode;
  containerWidth: number;
  containerHeight?: number;
}> = React.memo(({ colorMode, containerWidth, containerHeight }) => {
  const primaryColor = useToolStore((s) => s.primaryColor);
  const secondaryColor = useToolStore((s) => s.secondaryColor);
  const tool = useToolStore((s) => s.tool);

  const handlePrimaryChange = useCallback(
    (color: string, commit?: boolean) => {
      toolStoreActions.setPrimaryColor(color, commit, colorMode);
    },
    [colorMode]
  );

  const handleSecondaryChange = useCallback(
    (color: string, commit?: boolean) => {
      toolStoreActions.setSecondaryColor(color, commit, colorMode);
    },
    [colorMode]
  );

  const handleSwapColors = useCallback(() => {
    toolStoreActions.swapColors(colorMode);
  }, [colorMode]);

  const handleSelectTool = useCallback((nextTool: Parameters<typeof toolStoreActions.selectTool>[0]) => {
    toolStoreActions.selectTool(nextTool);
  }, []);

  return (
    <div className="h-full w-full overflow-hidden bg-ui-panel">
      <ColorSlider
        primaryColor={primaryColor}
        secondaryColor={secondaryColor}
        onPrimaryColorChange={handlePrimaryChange}
        onSecondaryColorChange={handleSecondaryChange}
        onSwapColors={handleSwapColors}
        colorMode={colorMode}
        currentTool={tool}
        onSelectTool={handleSelectTool}
        recentColors={[]}
        containerWidth={containerWidth}
        containerHeight={containerHeight}
        hideHeader={true}
      />
    </div>
  );
});
ColorSliderDockedContent.displayName = 'ColorSliderDockedContent';

export interface DockWorkspaceProps {
  themePreset: ThemePreset;
  colorMode: CanvasColorMode;
  commandHandlers: WorkspaceCommandHandlers;
  // Tool / selection callbacks
  onDeselect?: () => void;
  onTransformSelection?: () => void;
  onClearSelection?: () => void;
  onDeleteOutsideSelection?: () => void;
  onCutSelection?: () => void;
  onCopySelection?: () => void;
  onPasteSelection?: () => void;
  onMoveSelectionToNewLayer?: () => void;
  onExpandSelection?: (pixels: number) => void;
  onContractSelection?: (pixels: number) => void;
  onFeatherSelection?: (radius: number) => void;
  onInvertSelection?: () => void;
  onToggleTransparentColor?: () => void;
  // Layer & history props forwarded cleanly to RightSidebar docked panels
  layerSidebarProps: Omit<RightSidebarProps, 'width' | 'onWidthChange' | 'hideColorPanel' | 'dockedMode'>;
  // Navigator palette props
  navigatorProps?: Omit<NavigatorPanelProps, 'themePreset'>;
  // Auto Actions palette props
  autoActionProps?: AutoActionPanelProps;
  // Optional StatusBar pinned strictly below the Bottom Dock Zone
  statusBar?: React.ReactNode;
  // Center canvas area (DocumentTabBar + CanvasArea)
  children: React.ReactNode;
}

interface DockCellPanelProps {
  side: DockSide;
  colId: string;
  rowId: string;
  cell: DockSplitCell;
  groupIndex: number;
  isSplitRow: boolean;
  isRowCollapsed: boolean;
  estimatedWidth: number;
  estimatedHeight?: number;
  isCompactToolOnly: boolean;
  adjacentRowForSideSplit?: { id: string; direction: 'above' | 'below' } | null;
  draggingPanelId: DockPanelId | null;
  onStartDragPanel: (panelId: DockPanelId) => void;
  onEndDragPanel: () => void;
  onStartPointerTabDrag?: (
    e: React.PointerEvent<HTMLButtonElement>,
    panelId: DockPanelId,
    colId: string,
    groupId: string,
    groupPanelCount: number,
    cellId?: string
  ) => void;
  onCollapseRowOrDock: () => void;
  renderPanelBody: (
    panelId: DockPanelId,
    containerWidth: number,
    containerHeight?: number
  ) => React.ReactNode;
}

const DockCellPanel: React.FC<DockCellPanelProps> = React.memo(({
  side,
  colId,
  rowId,
  cell,
  groupIndex,
  isSplitRow,
  isRowCollapsed,
  estimatedWidth,
  estimatedHeight,
  isCompactToolOnly,
  adjacentRowForSideSplit,
  draggingPanelId,
  onStartDragPanel,
  onEndDragPanel,
  onStartPointerTabDrag,
  onCollapseRowOrDock,
  renderPanelBody,
}) => {
  const { t, td } = useI18n();
  const lockMove = useWorkspaceStore((s) => s.workspaceLocks.lockMove);
  const [menuOpen, setMenuOpen] = useState(false);
  const [menuPos, setMenuPos] = useState<{ top: number; left: number } | null>(null);
  const [isDragOverTab, setIsDragOverTab] = useState(false);
  const menuRef = useRef<HTMLDivElement>(null);
  const triggerBtnRef = useRef<HTMLButtonElement>(null);
  const portalMenuRef = useRef<HTMLDivElement>(null);
  const cellRootRef = useRef<HTMLDivElement>(null);

  const clampMenuCoordinates = useCallback(
    (rawLeft: number, rawTop: number, anchorTop?: number) => {
      if (typeof window === 'undefined') return { top: rawTop, left: rawLeft };
      const menuWidth = 196;
      const estMenuHeight = 250;
      const pad = 8;

      let left = rawLeft;
      if (left + menuWidth > window.innerWidth - pad) {
        left = window.innerWidth - menuWidth - pad;
      }
      left = Math.max(pad, Math.min(window.innerWidth - menuWidth - pad, left));

      let top = rawTop;
      if (top + estMenuHeight > window.innerHeight - pad) {
        if (anchorTop !== undefined && anchorTop - estMenuHeight - 4 >= pad) {
          top = anchorTop - estMenuHeight - 4;
        } else {
          top = Math.max(pad, window.innerHeight - estMenuHeight - pad);
        }
      } else {
        top = Math.max(pad, top);
      }

      return { top, left };
    },
    []
  );

  const computeMenuPosition = useCallback(() => {
    const btn = triggerBtnRef.current;
    if (!btn || typeof window === 'undefined') return null;
    const rect = btn.getBoundingClientRect();
    const menuWidth = 196;
    const rawLeft = side === 'left' ? rect.left : rect.right - menuWidth;
    return clampMenuCoordinates(rawLeft, rect.bottom + 4, rect.top);
  }, [clampMenuCoordinates, side]);

  useEffect(() => {
    if (!menuOpen) return;
    const handleOutside = (e: MouseEvent) => {
      const target = e.target as Node;
      if (menuRef.current?.contains(target) || portalMenuRef.current?.contains(target)) {
        return;
      }
      setMenuOpen(false);
    };
    const handleKey = (e: KeyboardEvent) => {
      if (isImeComposing(e)) return;
      if (e.key === 'Escape') setMenuOpen(false);
    };
    const handleReposition = () => {
      const next = computeMenuPosition();
      if (next) setMenuPos(next);
      else setMenuOpen(false);
    };
    window.addEventListener('mousedown', handleOutside);
    window.addEventListener('keydown', handleKey);
    window.addEventListener('resize', handleReposition);
    window.addEventListener('scroll', handleReposition, true);
    return () => {
      window.removeEventListener('mousedown', handleOutside);
      window.removeEventListener('keydown', handleKey);
      window.removeEventListener('resize', handleReposition);
      window.removeEventListener('scroll', handleReposition, true);
    };
  }, [menuOpen, computeMenuPosition]);

  const safePanelIds = Array.isArray(cell?.panelIds)
    ? cell.panelIds.filter((pid) => Boolean(DOCK_PANEL_META[pid]))
    : [];
  const activePanelId = safePanelIds.includes(cell.activePanelId)
    ? cell.activePanelId
    : safePanelIds[0];

  const handleDetachActivePanel = useCallback(() => {
    if (lockMove || !activePanelId) return;
    const rect = cellRootRef.current?.getBoundingClientRect();
    const meta = DOCK_PANEL_META[activePanelId];
    if (!meta) return;
    if (rect && typeof window !== 'undefined') {
      const offsetX =
        side === 'left'
          ? rect.right + 16
          : side === 'right'
            ? rect.left - meta.defaultFloatWidth - 16
            : Math.max(16, rect.left + rect.width * 0.5 - meta.defaultFloatWidth * 0.5);
      const offsetY =
        side === 'bottom'
          ? Math.max(44, rect.top - meta.defaultFloatHeight - 16)
          : Math.max(44, rect.top);
      workspaceStoreActions.detachPanel(activePanelId, {
        x: offsetX,
        y: offsetY,
      });
    } else {
      workspaceStoreActions.detachPanel(activePanelId);
    }
  }, [activePanelId, lockMove, side]);

  const handleDropOnTabs = (e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
    setIsDragOverTab(false);
    if (lockMove) {
      onEndDragPanel();
      return;
    }
    const rawId =
      (e.dataTransfer.getData(DND_PANEL_MIME) as DockPanelId) ||
      (e.dataTransfer.getData('text/plain') as DockPanelId) ||
      draggingPanelId;
    if (rawId && DOCK_PANEL_META[rawId]) {
      workspaceStoreActions.movePanel(rawId, {
        side,
        targetColId: colId,
        targetGroupId: rowId,
        targetCellId: cell.id,
      });
    }
    onEndDragPanel();
  };

  if (!activePanelId || !DOCK_PANEL_META[activePanelId]) {
    return null;
  }

  const canSplitActiveTab = safePanelIds.length > 1;

  return (
    <div
      ref={cellRootRef}
      data-testid={isSplitRow || side === 'bottom' ? `dock-cell-${cell.id}` : undefined}
      data-drop-cell={`${side}|${colId}|${rowId}|${cell.id}|${groupIndex}`}
      data-drop-bottom-cell={side === 'bottom' ? cell.id : undefined}
      style={
        isSplitRow || side === 'bottom'
          ? { flexGrow: cell.widthRatio, flexBasis: 0 }
          : undefined
      }
      className={`flex flex-col min-w-0 overflow-hidden bg-ui-panel ${
        isSplitRow || side === 'bottom' ? 'h-full' : 'flex-1 min-h-0'
      }`}
    >
      {/* Palette Tab Header Bar (Draggable to dock, split side-by-side, or detach!) */}
      <div
        data-dock-group-header="true"
        data-drop-tab-bar={`${side}|${colId}|${rowId}|${cell.id}`}
        onDragOver={(e) => {
          if (lockMove) return;
          e.preventDefault();
          e.dataTransfer.dropEffect = 'move';
          setIsDragOverTab(true);
        }}
        onDragLeave={() => setIsDragOverTab(false)}
        onDrop={handleDropOnTabs}
        onContextMenu={(e) => {
          e.preventDefault();
          e.stopPropagation();
          setMenuPos(clampMenuCoordinates(e.clientX, e.clientY));
          setMenuOpen(true);
        }}
        onDoubleClick={(e) => {
          if ((e.target as HTMLElement)?.closest?.('button')) return;
          onCollapseRowOrDock();
        }}
        className={`h-6 flex items-center justify-between px-1 shrink-0 select-none relative transition-colors ${
          isDragOverTab
            ? 'bg-ui-accent-subtle ring-1 ring-inset ring-ui-accent'
            : 'bg-ui-header border-b border-ui-subtle'
        }`}
      >
        <div className="flex items-center gap-0.5 min-w-0 overflow-x-auto no-scrollbar h-full">
          {safePanelIds.map((pid) => {
            const meta = DOCK_PANEL_META[pid];
            if (!meta) return null;
            const isActive = pid === activePanelId;
            return (
              <button
                key={pid}
                type="button"
                draggable={!lockMove && !onStartPointerTabDrag}
                onPointerDown={(e) => {
                  if (e.button !== 0 || lockMove) return;
                  e.stopPropagation();
                  onStartPointerTabDrag?.(e, pid, colId, rowId, safePanelIds.length, cell.id);
                }}
                onDragStart={(e) => {
                  if (lockMove) {
                    e.preventDefault();
                    return;
                  }
                  e.stopPropagation();
                  e.dataTransfer.setData(DND_PANEL_MIME, pid);
                  e.dataTransfer.setData('text/plain', pid);
                  e.dataTransfer.effectAllowed = 'move';
                  onStartDragPanel(pid);
                }}
                onDragEnd={onEndDragPanel}
                onClick={() => workspaceStoreActions.setGroupActivePanel(colId, rowId, pid, cell.id)}
                data-testid={`dock-tab-${pid}`}
                title={
                  lockMove
                    ? t('{title} (Position locked)', { title: td(meta.title) })
                    : t('{title} — Drag tab to move, split side-by-side, or detach', {
                        title: td(meta.title),
                      })
                }
                className={`relative h-5 ${isCompactToolOnly ? 'px-1' : 'px-1.5'} rounded-ui-xs flex items-center gap-1 text-[10px] transition-colors shrink-0 ${
                  lockMove ? 'cursor-pointer' : 'cursor-grab active:cursor-grabbing'
                } ${
                  isActive
                    ? 'bg-ui-control text-ui-primary font-medium border border-ui-default'
                    : 'text-ui-muted hover:text-ui-primary hover:bg-ui-control-hover border border-transparent'
                }`}
              >
                {renderPanelIcon(pid, 'w-3 h-3 shrink-0')}
                {!isCompactToolOnly && (
                  <span className="truncate max-w-[84px]">
                    {safePanelIds.length > 1 || isSplitRow
                      ? td(meta.shortTitle, 'panelShort')
                      : td(meta.title)}
                  </span>
                )}
                {isActive && safePanelIds.length > 1 && (
                  <span className="absolute bottom-0 left-1 right-1 h-[2px] bg-ui-accent rounded-full" />
                )}
              </button>
            );
          })}
        </div>

        {/* Upper-right Palette Controls: Compact Tool Detach OR Detach + Minimize (-) + Options Menu */}
        {isCompactToolOnly ? (
          <button
            type="button"
            data-testid="dock-detach-btn-tools"
            disabled={lockMove}
            onClick={handleDetachActivePanel}
            title={lockMove ? t('Position locked') : t('Detach & Float Tool Panel')}
            aria-label={t('Detach Tool panel')}
            className="w-4 h-4 rounded-ui-xs flex items-center justify-center text-ui-muted hover:text-ui-primary hover:bg-ui-control-hover disabled:opacity-35 disabled:cursor-not-allowed cursor-pointer shrink-0"
          >
            <PinOff className="w-2.5 h-2.5" />
          </button>
        ) : (
          <div className="flex items-center gap-0.5 shrink-0" ref={menuRef}>
            <button
              type="button"
              data-testid={`dock-detach-btn-${activePanelId}`}
              disabled={lockMove}
              onClick={handleDetachActivePanel}
              title={lockMove ? t('Position locked') : t('Detach & Float Palette')}
              aria-label={t('Detach {title}', { title: td(DOCK_PANEL_META[activePanelId].title) })}
              className="w-4 h-5 rounded-ui-xs flex items-center justify-center text-ui-muted hover:text-ui-primary hover:bg-ui-control-hover disabled:opacity-35 disabled:cursor-not-allowed cursor-pointer"
            >
              <PinOff className="w-2.5 h-2.5" />
            </button>

            <button
              type="button"
              data-testid={`dock-collapse-group-btn-${activePanelId}`}
              onClick={onCollapseRowOrDock}
              title={isRowCollapsed ? t('Expand Panel') : t('Hide / Collapse Panel')}
              aria-label={
                isRowCollapsed
                  ? t('Expand {title}', { title: td(DOCK_PANEL_META[activePanelId].title) })
                  : t('Hide {title}', { title: td(DOCK_PANEL_META[activePanelId].title) })
              }
              aria-expanded={!isRowCollapsed}
              className={`w-4 h-5 rounded-ui-xs flex items-center justify-center cursor-pointer transition-colors ${
                isRowCollapsed
                  ? 'text-ui-accent bg-ui-control-active'
                  : 'text-ui-muted hover:text-ui-primary hover:bg-ui-control-hover'
              }`}
            >
              <Minus className="w-2.5 h-2.5" />
            </button>

            <button
              ref={triggerBtnRef}
              type="button"
              onClick={() => {
                setMenuOpen((prev) => {
                  if (!prev) {
                    setMenuPos(computeMenuPosition());
                    return true;
                  }
                  return false;
                });
              }}
              data-testid={`dock-menu-btn-${activePanelId}`}
              title={t('Palette Dock Options')}
              className="w-5 h-5 rounded-ui-xs flex items-center justify-center text-ui-muted hover:text-ui-primary hover:bg-ui-control-hover cursor-pointer"
            >
              <MoreHorizontal className="w-3 h-3" />
            </button>

            {menuOpen &&
              typeof document !== 'undefined' &&
              createPortal(
                <div
                  ref={portalMenuRef}
                  data-testid={`dock-menu-popover-${activePanelId}`}
                  style={{
                    position: 'fixed',
                    top: menuPos?.top ?? 0,
                    left: menuPos?.left ?? 0,
                  }}
                  className="w-52 rounded-ui-md shadow-ui-popover p-1 z-[1000] text-[11px] bg-ui-elevated border border-ui-default text-ui-primary"
                >
                  <div className="px-2 py-0.5 text-[10px] text-ui-muted truncate">
                    {td(DOCK_PANEL_META[activePanelId].title)}
                  </div>
                  <div className="my-0.5 border-t border-ui-subtle" />

                  <button
                    type="button"
                    data-testid={`detach-float-${activePanelId}`}
                    disabled={lockMove}
                    onClick={() => {
                      handleDetachActivePanel();
                      setMenuOpen(false);
                    }}
                    className="w-full flex items-center gap-1.5 px-2 py-1 rounded-ui-sm hover:bg-ui-control-hover disabled:opacity-40 disabled:cursor-not-allowed cursor-pointer text-left"
                  >
                    <PinOff className="w-3 h-3 text-ui-accent" />
                    <span>{t('Detach & Float Palette')}</span>
                  </button>

                  {canSplitActiveTab && (
                    <>
                      <button
                        type="button"
                        data-testid={`split-left-${activePanelId}`}
                        disabled={lockMove}
                        onClick={() => {
                          workspaceStoreActions.movePanel(activePanelId, {
                            side,
                            targetColId: colId,
                            targetGroupId: rowId,
                            targetCellId: cell.id,
                            splitHorizontal: 'left',
                          });
                          setMenuOpen(false);
                        }}
                        className="w-full flex items-center gap-1.5 px-2 py-1 rounded-ui-sm hover:bg-ui-control-hover disabled:opacity-40 disabled:cursor-not-allowed cursor-pointer text-left"
                      >
                        <Columns2 className="w-3 h-3 text-ui-accent" />
                        <span>{t('Split Side-by-Side Left')}</span>
                      </button>

                      <button
                        type="button"
                        data-testid={`split-right-${activePanelId}`}
                        disabled={lockMove}
                        onClick={() => {
                          workspaceStoreActions.movePanel(activePanelId, {
                            side,
                            targetColId: colId,
                            targetGroupId: rowId,
                            targetCellId: cell.id,
                            splitHorizontal: 'right',
                          });
                          setMenuOpen(false);
                        }}
                        className="w-full flex items-center gap-1.5 px-2 py-1 rounded-ui-sm hover:bg-ui-control-hover disabled:opacity-40 disabled:cursor-not-allowed cursor-pointer text-left"
                      >
                        <Columns2 className="w-3 h-3 text-ui-accent" />
                        <span>{t('Split Side-by-Side Right')}</span>
                      </button>
                    </>
                  )}

                  {!canSplitActiveTab && adjacentRowForSideSplit && side !== 'bottom' && (
                    <button
                      type="button"
                      data-testid={`split-right-${activePanelId}`}
                      disabled={lockMove}
                      onClick={() => {
                        workspaceStoreActions.movePanel(activePanelId, {
                          side,
                          targetColId: colId,
                          targetGroupId: adjacentRowForSideSplit.id,
                          splitHorizontal: 'right',
                        });
                        setMenuOpen(false);
                      }}
                      className="w-full flex items-center gap-1.5 px-2 py-1 rounded-ui-sm hover:bg-ui-control-hover disabled:opacity-40 disabled:cursor-not-allowed cursor-pointer text-left"
                    >
                      <Columns2 className="w-3 h-3 text-ui-accent" />
                      <span>
                        {adjacentRowForSideSplit.direction === 'above'
                          ? t('Side-by-Side with Above')
                          : t('Side-by-Side with Below')}
                      </span>
                    </button>
                  )}

                  {side !== 'left' && (
                    <button
                      type="button"
                      data-testid={`move-to-left-${activePanelId}`}
                      disabled={lockMove}
                      onClick={() => {
                        workspaceStoreActions.movePanel(activePanelId, { side: 'left' });
                        setMenuOpen(false);
                      }}
                      className="w-full flex items-center gap-1.5 px-2 py-1 rounded-ui-sm hover:bg-ui-control-hover disabled:opacity-40 disabled:cursor-not-allowed cursor-pointer text-left"
                    >
                      <ArrowLeftToLine className="w-3 h-3 text-ui-accent" />
                      <span>{t('Move to Left Dock')}</span>
                    </button>
                  )}

                  {side !== 'right' && (
                    <button
                      type="button"
                      data-testid={`move-to-right-${activePanelId}`}
                      disabled={lockMove}
                      onClick={() => {
                        workspaceStoreActions.movePanel(activePanelId, { side: 'right' });
                        setMenuOpen(false);
                      }}
                      className="w-full flex items-center gap-1.5 px-2 py-1 rounded-ui-sm hover:bg-ui-control-hover disabled:opacity-40 disabled:cursor-not-allowed cursor-pointer text-left"
                    >
                      <ArrowRightToLine className="w-3 h-3 text-ui-accent" />
                      <span>{t('Move to Right Dock')}</span>
                    </button>
                  )}

                  {side !== 'bottom' && (
                    <button
                      type="button"
                      data-testid={`move-to-bottom-${activePanelId}`}
                      disabled={lockMove}
                      onClick={() => {
                        workspaceStoreActions.movePanel(activePanelId, { side: 'bottom' });
                        setMenuOpen(false);
                      }}
                      className="w-full flex items-center gap-1.5 px-2 py-1 rounded-ui-sm hover:bg-ui-control-hover disabled:opacity-40 disabled:cursor-not-allowed cursor-pointer text-left"
                    >
                      <ArrowDownToLine className="w-3 h-3 text-ui-accent" />
                      <span>{t('Move to Bottom Dock')}</span>
                    </button>
                  )}

                  {side !== 'bottom' && (
                    <>
                      <button
                        type="button"
                        disabled={lockMove}
                        onClick={() => {
                          workspaceStoreActions.movePanel(activePanelId, { side });
                          setMenuOpen(false);
                        }}
                        className="w-full flex items-center gap-1.5 px-2 py-1 rounded-ui-sm hover:bg-ui-control-hover disabled:opacity-40 disabled:cursor-not-allowed cursor-pointer text-left"
                      >
                        {side === 'left' ? (
                          <PanelLeft className="w-3 h-3 text-ui-muted" />
                        ) : (
                          <PanelRight className="w-3 h-3 text-ui-muted" />
                        )}
                        <span>{t('Move to New Column')}</span>
                      </button>

                      <button
                        type="button"
                        onClick={() => {
                          workspaceStoreActions.toggleColumnCollapsed(colId, true);
                          setMenuOpen(false);
                        }}
                        className="w-full flex items-center gap-1.5 px-2 py-1 rounded-ui-sm hover:bg-ui-control-hover cursor-pointer text-left"
                      >
                        {side === 'left' ? (
                          <ChevronsLeft className="w-3 h-3 text-ui-muted" />
                        ) : (
                          <ChevronsRight className="w-3 h-3 text-ui-muted" />
                        )}
                        <span>{t('Collapse Dock Strip')}</span>
                      </button>
                    </>
                  )}

                  <div className="my-0.5 border-t border-ui-subtle" />

                  <button
                    type="button"
                    onClick={() => {
                      workspaceStoreActions.togglePanelVisibility(activePanelId);
                      setMenuOpen(false);
                    }}
                    className="w-full flex items-center gap-1.5 px-2 py-1 rounded-ui-sm hover:bg-ui-danger/15 text-ui-danger cursor-pointer text-left"
                  >
                    <X className="w-3 h-3" />
                    <span>{t('Close Palette')}</span>
                  </button>
                </div>,
                document.body
              )}
          </div>
        )}
      </div>

      {/* Active Panel Content (hidden when row is collapsed via "-") */}
      {!isRowCollapsed && (
        <div
          data-testid={`dock-group-body-${activePanelId}`}
          className="flex-1 min-h-0 overflow-hidden flex flex-col"
        >
          {renderPanelBody(activePanelId, estimatedWidth, estimatedHeight)}
        </div>
      )}
    </div>
  );
});
DockCellPanel.displayName = 'DockCellPanel';

interface DockGroupViewProps {
  side: DockSide;
  col: DockColumn;
  group: DockGroup;
  groupIndex?: number;
  themePreset: ThemePreset;
  draggingPanelId: DockPanelId | null;
  onStartDragPanel: (panelId: DockPanelId) => void;
  onEndDragPanel: () => void;
  onStartPointerTabDrag?: (
    e: React.PointerEvent<HTMLButtonElement>,
    panelId: DockPanelId,
    colId: string,
    groupId: string,
    groupPanelCount: number,
    cellId?: string
  ) => void;
  renderPanelBody: (
    panelId: DockPanelId,
    containerWidth: number,
    containerHeight?: number
  ) => React.ReactNode;
}

export const DockGroupView: React.FC<DockGroupViewProps> = React.memo(({
  side,
  col,
  group,
  groupIndex = 0,
  themePreset: _themePreset,
  draggingPanelId,
  onStartDragPanel,
  onEndDragPanel,
  onStartPointerTabDrag,
  renderPanelBody,
}) => {
  const { t } = useI18n();
  const lockWidth = useWorkspaceStore((s) => s.workspaceLocks.lockWidth);
  const rowRef = useRef<HTMLDivElement>(null);
  const [resizingCellSplitIdx, setResizingCellSplitIdx] = useState<number | null>(null);

  const cells = getGroupCells(group);
  const isSplitRow = cells.length > 1;
  const isCollapsed = Boolean(group.collapsed);
  const groupPanelIds = Array.isArray(group.panelIds) ? group.panelIds : [];
  const isCompactToolOnly =
    !isSplitRow &&
    col.width <= 64 &&
    groupPanelIds.length === 1 &&
    groupPanelIds[0] === 'tools';

  const adjacentRowForSideSplit = React.useMemo(() => {
    const groups = Array.isArray(col.groups) ? col.groups : [];
    if (groups.length <= 1) return null;
    if (groupIndex > 0 && groups[groupIndex - 1]) {
      return { id: groups[groupIndex - 1].id, direction: 'above' as const };
    }
    if (groupIndex + 1 < groups.length && groups[groupIndex + 1]) {
      return { id: groups[groupIndex + 1].id, direction: 'below' as const };
    }
    return null;
  }, [col.groups, groupIndex]);

  const handleToggleRowCollapsed = useCallback(() => {
    workspaceStoreActions.toggleGroupCollapsed(col.id, group.id);
  }, [col.id, group.id]);

  const handleStartCellSplitResize = useCallback(
    (
      e: React.PointerEvent<HTMLDivElement>,
      leftCell: DockSplitCell,
      rightCell: DockSplitCell,
      splitIdx: number
    ) => {
      if (e.button !== 0 || lockWidth) return;
      const rowEl = rowRef.current;
      if (!rowEl) return;
      e.preventDefault();
      e.stopPropagation();

      const releaseGuard = acquireWorkspaceInteractionLock('dock-cell-resize');
      const targetEl = e.currentTarget;
      const pointerId = e.pointerId;
      try {
        targetEl.setPointerCapture?.(pointerId);
      } catch {
        // Ignore synthetic pointer events
      }

      setResizingCellSplitIdx(splitIdx);
      const totalWidth = Math.max(120, rowEl.getBoundingClientRect().width);
      const totalRatioSum = cells.reduce((acc, c) => acc + c.widthRatio, 0) || 1;
      const pairSum = leftCell.widthRatio + rightCell.widthRatio;
      const startX = e.clientX;
      const startLeftRatio = leftCell.widthRatio;
      let latestLeft = startLeftRatio;
      let latestRight = rightCell.widthRatio;

      const computePair = (clientX: number) => {
        const deltaRatio = ((clientX - startX) / totalWidth) * totalRatioSum;
        const minRatio = Math.min(0.16 * totalRatioSum, pairSum * 0.25);
        const nextLeft = Math.max(minRatio, Math.min(pairSum - minRatio, startLeftRatio + deltaRatio));
        return { nextLeft, nextRight: pairSum - nextLeft };
      };

      const cleanup = () => {
        releaseGuard();
        setResizingCellSplitIdx(null);
        try {
          if (targetEl.hasPointerCapture?.(pointerId)) {
            targetEl.releasePointerCapture?.(pointerId);
          }
        } catch {
          // Ignore synthetic capture release errors
        }
        window.removeEventListener('pointermove', handleMove);
        window.removeEventListener('pointerup', handleUp);
        window.removeEventListener('pointercancel', handleCancel);
      };

      const handleMove = (ev: PointerEvent) => {
        const pair = computePair(ev.clientX);
        latestLeft = pair.nextLeft;
        latestRight = pair.nextRight;
        workspaceStoreActions.resizeCellSplit(
          col.id,
          group.id,
          leftCell.id,
          rightCell.id,
          latestLeft,
          latestRight,
          false
        );
      };

      const handleUp = (ev: PointerEvent) => {
        const pair = computePair(ev.clientX);
        cleanup();
        workspaceStoreActions.resizeCellSplit(
          col.id,
          group.id,
          leftCell.id,
          rightCell.id,
          pair.nextLeft,
          pair.nextRight,
          true
        );
      };

      const handleCancel = () => {
        cleanup();
      };

      window.addEventListener('pointermove', handleMove);
      window.addEventListener('pointerup', handleUp);
      window.addEventListener('pointercancel', handleCancel);
    },
    [cells, col.id, group.id, lockWidth]
  );

  const totalWidthRatio = cells.reduce((acc, c) => acc + c.widthRatio, 0) || 1;

  return (
    <div
      ref={rowRef}
      data-testid={`dock-group-${group.id}`}
      data-collapsed={String(isCollapsed)}
      data-split-row={isSplitRow ? 'true' : 'false'}
      data-drop-group={`${side}|${col.id}|${group.id}|${groupIndex}`}
      style={
        isCollapsed
          ? { flexGrow: 0, flexBasis: 'auto' }
          : { flexGrow: group.heightRatio, flexBasis: 0 }
      }
      className={`flex ${isSplitRow ? 'flex-row bg-ui-void' : 'flex-col bg-ui-panel'} overflow-hidden ${
        isCollapsed ? 'shrink-0' : 'min-h-[72px]'
      }`}
    >
      {cells.map((cell, cellIdx) => {
        const estWidth = Math.max(
          96,
          Math.round((col.width * cell.widthRatio) / totalWidthRatio)
        );
        return (
          <React.Fragment key={cell.id}>
            <DockCellPanel
              side={side}
              colId={col.id}
              rowId={group.id}
              cell={cell}
              groupIndex={groupIndex}
              isSplitRow={isSplitRow}
              isRowCollapsed={isCollapsed}
              estimatedWidth={estWidth}
              isCompactToolOnly={isCompactToolOnly}
              adjacentRowForSideSplit={adjacentRowForSideSplit}
              draggingPanelId={draggingPanelId}
              onStartDragPanel={onStartDragPanel}
              onEndDragPanel={onEndDragPanel}
              onStartPointerTabDrag={onStartPointerTabDrag}
              onCollapseRowOrDock={handleToggleRowCollapsed}
              renderPanelBody={renderPanelBody}
            />

            {isSplitRow && cellIdx < cells.length - 1 && (
              <div
                data-dock-cell-splitter="true"
                data-testid={`dock-cell-splitter-${group.id}-${cellIdx}`}
                data-active={resizingCellSplitIdx === cellIdx ? 'true' : 'false'}
                data-locked={lockWidth ? 'true' : 'false'}
                onPointerDown={(e) =>
                  handleStartCellSplitResize(e, cell, cells[cellIdx + 1], cellIdx)
                }
                title={lockWidth ? t('Width locked') : t('Drag to resize side-by-side palettes')}
                className={`group/csplit relative w-1 shrink-0 flex items-center justify-center transition-colors ${
                  lockWidth ? 'cursor-default' : 'cursor-col-resize'
                }`}
              >
                <span
                  aria-hidden="true"
                  className={`dock-vsplit-line h-full w-[2px] rounded-full transition-colors ${
                    resizingCellSplitIdx === cellIdx
                      ? 'bg-[var(--ui-accent-border)]'
                      : lockWidth
                        ? 'bg-[var(--ui-border-subtle)]'
                        : 'bg-[var(--ui-border-subtle)] group-hover/csplit:bg-[var(--ui-accent-border)]'
                  }`}
                />
              </div>
            )}
          </React.Fragment>
        );
      })}
    </div>
  );
});
DockGroupView.displayName = 'DockGroupView';

interface DockColumnViewProps {
  side: DockSide;
  col: DockColumn;
  colIndex: number;
  themePreset: ThemePreset;
  draggingPanelId: DockPanelId | null;
  onStartDragPanel: (panelId: DockPanelId) => void;
  onEndDragPanel: () => void;
  onStartPointerTabDrag: (
    e: React.PointerEvent<HTMLButtonElement>,
    panelId: DockPanelId,
    colId: string,
    groupId: string,
    groupPanelCount: number,
    cellId?: string
  ) => void;
  renderPanelBody: (
    panelId: DockPanelId,
    containerWidth: number,
    containerHeight?: number
  ) => React.ReactNode;
}

const DockColumnView: React.FC<DockColumnViewProps> = React.memo(({
  side,
  col,
  colIndex,
  themePreset,
  draggingPanelId,
  onStartDragPanel,
  onEndDragPanel,
  onStartPointerTabDrag,
  renderPanelBody,
}) => {
  const { t, td } = useI18n();
  const openPopover = useWorkspaceStore((s) => s.openPopover);
  const workspaceLocks = useWorkspaceStore((s) => s.workspaceLocks);
  const { lockWidth, lockHeight, lockMove } = workspaceLocks;
  const colRef = useRef<HTMLDivElement>(null);
  const [dragOverSplitIdx, setDragOverSplitIdx] = useState<number | null>(null);
  const [isResizingColumn, setIsResizingColumn] = useState(false);
  const [resizingSplitIdx, setResizingSplitIdx] = useState<number | null>(null);

  const activePopoverPanelId =
    col.collapsed && openPopover?.colId === col.id ? openPopover.panelId : null;

  const handleStartColumnResize = (e: React.PointerEvent<HTMLDivElement>) => {
    if (e.button !== 0 || lockWidth) return;
    e.preventDefault();
    e.stopPropagation();

    const releaseGuard = acquireWorkspaceInteractionLock('dock-col-resize');
    const targetEl = e.currentTarget;
    const pointerId = e.pointerId;
    try {
      targetEl.setPointerCapture?.(pointerId);
    } catch {
      // Ignore synthetic events without active pointer
    }

    setIsResizingColumn(true);
    const startX = e.clientX;
    const startWidth = col.width;

    const cleanup = () => {
      releaseGuard();
      setIsResizingColumn(false);
      try {
        if (targetEl.hasPointerCapture?.(pointerId)) {
          targetEl.releasePointerCapture?.(pointerId);
        }
      } catch {
        // Ignore synthetic capture errors
      }
      window.removeEventListener('pointermove', handleMove);
      window.removeEventListener('pointerup', handleUp);
      window.removeEventListener('pointercancel', handleCancel);
    };

    const handleMove = (ev: PointerEvent) => {
      const delta = side === 'left' ? ev.clientX - startX : startX - ev.clientX;
      workspaceStoreActions.resizeColumn(col.id, startWidth + delta);
    };
    const handleUp = () => {
      cleanup();
    };
    const handleCancel = () => {
      cleanup();
    };
    window.addEventListener('pointermove', handleMove);
    window.addEventListener('pointerup', handleUp);
    window.addEventListener('pointercancel', handleCancel);
  };

  const handleStartGroupSplitResize = (
    e: React.PointerEvent<HTMLDivElement>,
    topGroup: DockGroup,
    bottomGroup: DockGroup,
    splitIdx: number
  ) => {
    if (e.button !== 0 || lockHeight) return;
    const colEl = colRef.current;
    if (!colEl) return;
    e.preventDefault();
    e.stopPropagation();

    const releaseGuard = acquireWorkspaceInteractionLock('dock-row-resize');
    const targetEl = e.currentTarget;
    const pointerId = e.pointerId;
    try {
      targetEl.setPointerCapture?.(pointerId);
    } catch {
      // Ignore synthetic events without active pointer
    }

    setResizingSplitIdx(splitIdx);
    const totalHeight = Math.max(120, colEl.getBoundingClientRect().height);
    const totalRatioSum = col.groups.reduce((acc, g) => acc + g.heightRatio, 0) || 1;
    const pairSum = topGroup.heightRatio + bottomGroup.heightRatio;
    const startY = e.clientY;
    const startTopRatio = topGroup.heightRatio;

    const cleanup = () => {
      releaseGuard();
      setResizingSplitIdx(null);
      try {
        if (targetEl.hasPointerCapture?.(pointerId)) {
          targetEl.releasePointerCapture?.(pointerId);
        }
      } catch {
        // Ignore synthetic capture errors
      }
      window.removeEventListener('pointermove', handleMove);
      window.removeEventListener('pointerup', handleUp);
      window.removeEventListener('pointercancel', handleCancel);
    };

    const handleMove = (ev: PointerEvent) => {
      const deltaRatio = ((ev.clientY - startY) / totalHeight) * totalRatioSum;
      const minRatio = Math.min(0.15 * totalRatioSum, pairSum * 0.25);
      const nextTop = Math.max(minRatio, Math.min(pairSum - minRatio, startTopRatio + deltaRatio));
      const nextBottom = pairSum - nextTop;
      workspaceStoreActions.resizeGroupSplit(
        col.id,
        topGroup.id,
        bottomGroup.id,
        nextTop,
        nextBottom
      );
    };
    const handleUp = () => {
      cleanup();
    };
    const handleCancel = () => {
      cleanup();
    };
    window.addEventListener('pointermove', handleMove);
    window.addEventListener('pointerup', handleUp);
    window.addEventListener('pointercancel', handleCancel);
  };

  const handleDropNewGroup = (e: React.DragEvent, insertIndex: number) => {
    e.preventDefault();
    e.stopPropagation();
    setDragOverSplitIdx(null);
    if (lockMove) {
      onEndDragPanel();
      return;
    }
    const rawId =
      (e.dataTransfer.getData(DND_PANEL_MIME) as DockPanelId) ||
      (e.dataTransfer.getData('text/plain') as DockPanelId) ||
      draggingPanelId;
    if (rawId && DOCK_PANEL_META[rawId]) {
      workspaceStoreActions.movePanel(rawId, {
        side,
        targetColId: col.id,
        insertGroupIndex: insertIndex,
      });
    }
    onEndDragPanel();
  };

  // Collapsed CSP Tab Strip mode
  if (col.collapsed) {
    const panelOwners: Array<{
      panelId: DockPanelId;
      groupId: string;
      cellId: string;
      cellPanelCount: number;
    }> = [];
    for (const grp of Array.isArray(col.groups) ? col.groups : []) {
      for (const cell of getGroupCells(grp)) {
        const pids = Array.isArray(cell.panelIds) ? cell.panelIds : [];
        for (const pid of pids) {
          if (!DOCK_PANEL_META[pid]) continue;
          panelOwners.push({
            panelId: pid,
            groupId: grp.id,
            cellId: cell.id,
            cellPanelCount: pids.length,
          });
        }
      }
    }
    const popoverWidth = Math.max(204, col.width);
    const firstGroupId = col.groups?.[0]?.id ?? '';

    return (
      <div
        data-testid={`dock-column-${col.id}`}
        data-dock-side={side}
        data-collapsed="true"
        data-drop-collapsed-col={`${side}|${col.id}|${firstGroupId}`}
        className="relative w-[30px] h-full flex flex-col items-center py-1 gap-1 shrink-0 select-none z-20 bg-ui-header border-x border-ui-subtle"
      >
        {/* Expand Column Button */}
        <button
          type="button"
          onClick={() => workspaceStoreActions.toggleColumnCollapsed(col.id, false)}
          data-testid={`dock-expand-${col.id}`}
          title={t('Expand Dock Column')}
          className="w-6 h-5 rounded-ui-xs flex items-center justify-center text-ui-muted hover:text-ui-primary hover:bg-ui-control-hover cursor-pointer shrink-0"
        >
          {side === 'left' ? (
            <ChevronsRight className="w-3.5 h-3.5" />
          ) : (
            <ChevronsLeft className="w-3.5 h-3.5" />
          )}
        </button>

        <div className="w-4 border-t border-ui-subtle shrink-0" />

        {/* Vertical Icon Tab Strip */}
        <div className="flex flex-col items-center gap-1 flex-1 overflow-y-auto no-scrollbar w-full px-0.5">
          {panelOwners.map(({ panelId: pid, groupId, cellId, cellPanelCount }) => {
            const meta = DOCK_PANEL_META[pid];
            const isOpen = activePopoverPanelId === pid;
            return (
              <button
                key={pid}
                type="button"
                onPointerDown={(e) => {
                  if (e.button !== 0 || lockMove) return;
                  e.stopPropagation();
                  onStartPointerTabDrag(e, pid, col.id, groupId, cellPanelCount, cellId);
                }}
                onClick={() => workspaceStoreActions.togglePopover(col.id, pid)}
                data-testid={`collapsed-tab-${pid}`}
                title={
                  lockMove
                    ? t('{title} (Click to pop out — position locked)', { title: td(meta.title) })
                    : t('{title} (Click to pop out, drag to move or detach)', {
                        title: td(meta.title),
                      })
                }
                aria-pressed={isOpen}
                className={`relative w-6 h-7 rounded-ui-sm flex items-center justify-center transition-colors cursor-pointer shrink-0 ${
                  isOpen
                    ? 'bg-ui-control-active text-ui-accent'
                    : 'text-ui-muted hover:text-ui-primary hover:bg-ui-control-hover'
                }`}
              >
                {isOpen && (
                  <span
                    className={`absolute top-1 bottom-1 w-[2px] rounded-full bg-ui-accent ${
                      side === 'left' ? 'left-0' : 'right-0'
                    }`}
                  />
                )}
                {renderPanelIcon(pid, 'w-3.5 h-3.5')}
              </button>
            );
          })}
        </div>

        {/* CSP Pop-out Floating Palette Popover */}
        {activePopoverPanelId && DOCK_PANEL_META[activePopoverPanelId] && (
          <div
            data-testid={`dock-popover-${activePopoverPanelId}`}
            style={{ width: popoverWidth }}
            className={`absolute top-1 bottom-1 z-40 flex flex-col rounded-ui-md shadow-ui-popover overflow-hidden bg-ui-panel border border-ui-default ${
              side === 'left' ? 'left-[32px]' : 'right-[32px]'
            }`}
          >
            <div className="h-7 px-2 flex items-center justify-between shrink-0 bg-ui-header border-b border-ui-subtle">
              <div className="flex items-center gap-1.5 min-w-0">
                {renderPanelIcon(activePopoverPanelId, 'w-3.5 h-3.5 text-ui-accent')}
                <span className="text-[11px] font-medium text-ui-primary truncate">
                  {td(DOCK_PANEL_META[activePopoverPanelId].title)}
                </span>
              </div>
              <div className="flex items-center gap-0.5 shrink-0">
                <button
                  type="button"
                  disabled={lockMove}
                  onClick={() => workspaceStoreActions.detachPanel(activePopoverPanelId)}
                  title={lockMove ? t('Position locked') : t('Detach & Float Palette')}
                  className="w-5 h-5 rounded-ui-xs flex items-center justify-center text-ui-muted hover:text-ui-primary hover:bg-ui-control-hover disabled:opacity-35 disabled:cursor-not-allowed cursor-pointer"
                >
                  <PinOff className="w-3 h-3" />
                </button>
                <button
                  type="button"
                  onClick={() => workspaceStoreActions.toggleColumnCollapsed(col.id, false)}
                  title={t('Expand & Pin Column')}
                  className="w-5 h-5 rounded-ui-xs flex items-center justify-center text-ui-muted hover:text-ui-primary hover:bg-ui-control-hover cursor-pointer"
                >
                  {side === 'left' ? (
                    <ChevronsRight className="w-3 h-3" />
                  ) : (
                    <ChevronsLeft className="w-3 h-3" />
                  )}
                </button>
                <button
                  type="button"
                  onClick={() => workspaceStoreActions.closePopover()}
                  title={t('Dismiss Popover (Esc)')}
                  className="w-5 h-5 rounded-ui-xs flex items-center justify-center text-ui-muted hover:text-ui-primary hover:bg-ui-control-hover cursor-pointer"
                >
                  <X className="w-3 h-3" />
                </button>
              </div>
            </div>
            <div className="flex-1 min-h-0 overflow-hidden flex flex-col">
              {renderPanelBody(activePopoverPanelId, popoverWidth)}
            </div>
          </div>
        )}
      </div>
    );
  }

  // Expanded Dock Column mode
  return (
    <div
      ref={colRef}
      data-testid={`dock-column-${col.id}`}
      data-dock-side={side}
      data-collapsed="false"
      data-drop-col={`${side}|${col.id}|${colIndex}`}
      style={{ width: col.width }}
      className={`relative h-full flex flex-col shrink-0 overflow-visible z-10 bg-ui-void ${
        side === 'left' ? 'border-r border-ui-subtle' : 'border-l border-ui-subtle'
      }`}
    >
      {/* Slim CSP Column Collapse Bar */}
      <div
        data-dock-col-collapse-bar="true"
        className={`h-4 px-1 flex items-center shrink-0 bg-ui-header border-b border-ui-subtle ${
          side === 'left' ? 'justify-end' : 'justify-start'
        }`}
      >
        <button
          type="button"
          onClick={() => workspaceStoreActions.toggleColumnCollapsed(col.id, true)}
          data-testid={`dock-collapse-${col.id}`}
          title={t('Collapse Dock Column to Icon Strip')}
          className="h-3.5 px-1 rounded-ui-xs flex items-center justify-center text-ui-muted hover:text-ui-primary hover:bg-ui-control-hover cursor-pointer"
        >
          {side === 'left' ? (
            <ChevronsLeft className="w-3 h-3" />
          ) : (
            <ChevronsRight className="w-3 h-3" />
          )}
        </button>
      </div>

      {/* Stacked Palette Groups (each row can contain 1 or N side-by-side equal-height cells) */}
      <div
        data-dock-col-groups="true"
        className="flex-1 min-h-0 flex flex-col overflow-hidden"
      >
        {col.groups.map((grp, idx) => (
          <React.Fragment key={grp.id}>
            {draggingPanelId && !lockMove && (
              <div
                onDragOver={(e) => {
                  e.preventDefault();
                  setDragOverSplitIdx(idx);
                }}
                onDragLeave={() => setDragOverSplitIdx(null)}
                onDrop={(e) => handleDropNewGroup(e, idx)}
                className={`h-1.5 shrink-0 transition-all ${
                  dragOverSplitIdx === idx ? 'h-3 bg-ui-accent-subtle border-y border-ui-accent' : 'bg-transparent'
                }`}
              />
            )}

            <DockGroupView
              side={side}
              col={col}
              group={grp}
              groupIndex={idx}
              themePreset={themePreset}
              draggingPanelId={draggingPanelId}
              onStartDragPanel={onStartDragPanel}
              onEndDragPanel={onEndDragPanel}
              onStartPointerTabDrag={onStartPointerTabDrag}
              renderPanelBody={renderPanelBody}
            />

            {idx < col.groups.length - 1 && (
              <div
                data-dock-group-splitter="true"
                data-active={resizingSplitIdx === idx ? 'true' : 'false'}
                data-locked={lockHeight ? 'true' : 'false'}
                onPointerDown={(e) => handleStartGroupSplitResize(e, grp, col.groups[idx + 1], idx)}
                title={lockHeight ? t('Height locked') : t('Drag to resize stacked palettes')}
                className={`group/hsplit relative h-1 shrink-0 flex items-center justify-center transition-colors ${
                  lockHeight ? 'cursor-default' : 'cursor-row-resize'
                }`}
              >
                <span
                  aria-hidden="true"
                  className={`dock-hsplit-line w-full h-[2px] rounded-full transition-colors ${
                    resizingSplitIdx === idx
                      ? 'bg-[var(--ui-accent-border)]'
                      : lockHeight
                        ? 'bg-[var(--ui-border-subtle)]'
                        : 'bg-[var(--ui-border-subtle)] group-hover/hsplit:bg-[var(--ui-accent-border)]'
                  }`}
                />
              </div>
            )}
          </React.Fragment>
        ))}

        {/* Bottom drop zone for stacking a dragged palette at the bottom of this column */}
        {draggingPanelId && !lockMove && (
          <div
            onDragOver={(e) => {
              e.preventDefault();
              setDragOverSplitIdx(col.groups.length);
            }}
            onDragLeave={() => setDragOverSplitIdx(null)}
            onDrop={(e) => handleDropNewGroup(e, col.groups.length)}
            className={`h-2 shrink-0 transition-all ${
              dragOverSplitIdx === col.groups.length
                ? 'h-5 bg-ui-accent-subtle border-t border-ui-accent'
                : 'bg-transparent'
            }`}
          />
        )}
      </div>

      {/* Vertical Column Resize Splitter — positioned strictly on outer seam so it never overlaps panel scrollbars */}
      <div
        data-dock-col-splitter={side}
        data-active={isResizingColumn ? 'true' : 'false'}
        data-locked={lockWidth ? 'true' : 'false'}
        onPointerDown={handleStartColumnResize}
        title={lockWidth ? t('Width locked') : t('Drag to resize dock column')}
        className={`group/vsplit absolute top-0 bottom-0 w-[6px] flex items-center justify-center z-30 ${
          lockWidth ? 'cursor-default pointer-events-none' : 'cursor-col-resize'
        } ${side === 'left' ? '-right-[5px]' : '-left-[5px]'}`}
      >
        <span
          aria-hidden="true"
          className={`dock-vsplit-line h-full w-[2px] rounded-full transition-colors ${
            isResizingColumn
              ? 'bg-[var(--ui-accent-border)]'
              : lockWidth
                ? 'bg-transparent'
                : 'bg-transparent group-hover/vsplit:bg-[var(--ui-accent-border)]'
          }`}
        />
      </div>
    </div>
  );
});
DockColumnView.displayName = 'DockColumnView';

export interface BottomDockViewProps {
  bottomDock: DockBottomZone;
  draggingPanelId: DockPanelId | null;
  onStartDragPanel: (panelId: DockPanelId) => void;
  onEndDragPanel: () => void;
  onStartPointerTabDrag?: (
    e: React.PointerEvent<HTMLButtonElement>,
    panelId: DockPanelId,
    colId: string,
    groupId: string,
    groupPanelCount: number,
    cellId?: string
  ) => void;
  renderPanelBody: (
    panelId: DockPanelId,
    containerWidth: number,
    containerHeight?: number
  ) => React.ReactNode;
}

export const BottomDockView: React.FC<BottomDockViewProps> = React.memo(({
  bottomDock,
  draggingPanelId,
  onStartDragPanel,
  onEndDragPanel,
  onStartPointerTabDrag,
  renderPanelBody,
}) => {
  const { t, td } = useI18n();
  const workspaceLocks = useWorkspaceStore((s) => s.workspaceLocks);
  const { lockWidth, lockHeight, lockMove } = workspaceLocks;
  const rowRef = useRef<HTMLDivElement>(null);
  const [measuredWidth, setMeasuredWidth] = useState(720);
  const [isResizingHeight, setIsResizingHeight] = useState(false);
  const [resizingCellSplitIdx, setResizingCellSplitIdx] = useState<number | null>(null);
  const [isDragOverCollapsed, setIsDragOverCollapsed] = useState(false);

  useEffect(() => {
    const el = rowRef.current;
    if (!el || typeof ResizeObserver === 'undefined') return;
    const update = () => {
      const nextW = Math.round(el.getBoundingClientRect().width);
      if (nextW > 0) setMeasuredWidth(nextW);
    };
    update();
    const observer = new ResizeObserver(update);
    observer.observe(el);
    return () => observer.disconnect();
  }, [bottomDock.collapsed]);

  const handleCollapseBottom = useCallback(() => {
    workspaceStoreActions.toggleBottomDockCollapsed(true);
  }, []);

  const handleStartHeightResize = useCallback(
    (e: React.PointerEvent<HTMLDivElement>) => {
      if (e.button !== 0 || lockHeight) return;
      e.preventDefault();
      e.stopPropagation();

      const releaseGuard = acquireWorkspaceInteractionLock('bottom-dock-resize');
      const targetEl = e.currentTarget;
      const pointerId = e.pointerId;
      try {
        targetEl.setPointerCapture?.(pointerId);
      } catch {
        // Ignore synthetic events
      }

      setIsResizingHeight(true);
      const startY = e.clientY;
      const startHeight = bottomDock.height;

      const cleanup = () => {
        releaseGuard();
        setIsResizingHeight(false);
        try {
          if (targetEl.hasPointerCapture?.(pointerId)) {
            targetEl.releasePointerCapture?.(pointerId);
          }
        } catch {
          // Ignore synthetic capture release errors
        }
        window.removeEventListener('pointermove', handleMove);
        window.removeEventListener('pointerup', handleUp);
        window.removeEventListener('pointercancel', handleCancel);
      };

      const handleMove = (ev: PointerEvent) => {
        const nextHeight = startHeight + (startY - ev.clientY);
        workspaceStoreActions.resizeBottomDock(nextHeight, false);
      };

      const handleUp = (ev: PointerEvent) => {
        const nextHeight = startHeight + (startY - ev.clientY);
        cleanup();
        workspaceStoreActions.resizeBottomDock(nextHeight, true);
      };

      const handleCancel = () => {
        cleanup();
      };

      window.addEventListener('pointermove', handleMove);
      window.addEventListener('pointerup', handleUp);
      window.addEventListener('pointercancel', handleCancel);
    },
    [bottomDock.height, lockHeight]
  );

  const handleStartCellSplitResize = useCallback(
    (
      e: React.PointerEvent<HTMLDivElement>,
      leftCell: DockSplitCell,
      rightCell: DockSplitCell,
      splitIdx: number
    ) => {
      if (e.button !== 0 || lockWidth) return;
      const rowEl = rowRef.current;
      if (!rowEl) return;
      e.preventDefault();
      e.stopPropagation();

      const releaseGuard = acquireWorkspaceInteractionLock('bottom-cell-resize');
      const targetEl = e.currentTarget;
      const pointerId = e.pointerId;
      try {
        targetEl.setPointerCapture?.(pointerId);
      } catch {
        // Ignore synthetic events
      }

      setResizingCellSplitIdx(splitIdx);
      const totalWidth = Math.max(160, rowEl.getBoundingClientRect().width);
      const totalRatioSum = bottomDock.cells.reduce((acc, c) => acc + c.widthRatio, 0) || 1;
      const pairSum = leftCell.widthRatio + rightCell.widthRatio;
      const startX = e.clientX;
      const startLeftRatio = leftCell.widthRatio;

      const computePair = (clientX: number) => {
        const deltaRatio = ((clientX - startX) / totalWidth) * totalRatioSum;
        const minRatio = Math.min(0.14 * totalRatioSum, pairSum * 0.22);
        const nextLeft = Math.max(minRatio, Math.min(pairSum - minRatio, startLeftRatio + deltaRatio));
        return { nextLeft, nextRight: pairSum - nextLeft };
      };

      const cleanup = () => {
        releaseGuard();
        setResizingCellSplitIdx(null);
        try {
          if (targetEl.hasPointerCapture?.(pointerId)) {
            targetEl.releasePointerCapture?.(pointerId);
          }
        } catch {
          // Ignore synthetic capture release errors
        }
        window.removeEventListener('pointermove', handleMove);
        window.removeEventListener('pointerup', handleUp);
        window.removeEventListener('pointercancel', handleCancel);
      };

      const handleMove = (ev: PointerEvent) => {
        const pair = computePair(ev.clientX);
        workspaceStoreActions.resizeCellSplit(
          BOTTOM_DOCK_COL_ID,
          BOTTOM_DOCK_COL_ID,
          leftCell.id,
          rightCell.id,
          pair.nextLeft,
          pair.nextRight,
          false
        );
      };

      const handleUp = (ev: PointerEvent) => {
        const pair = computePair(ev.clientX);
        cleanup();
        workspaceStoreActions.resizeCellSplit(
          BOTTOM_DOCK_COL_ID,
          BOTTOM_DOCK_COL_ID,
          leftCell.id,
          rightCell.id,
          pair.nextLeft,
          pair.nextRight,
          true
        );
      };

      const handleCancel = () => {
        cleanup();
      };

      window.addEventListener('pointermove', handleMove);
      window.addEventListener('pointerup', handleUp);
      window.addEventListener('pointercancel', handleCancel);
    },
    [bottomDock.cells, lockWidth]
  );

  // Collapsed compact bottom dock strip
  if (bottomDock.collapsed) {
    return (
      <div
        data-testid="bottom-dock-zone"
        data-dock-side="bottom"
        data-collapsed="true"
        data-drop-bottom-collapsed="true"
        onDragOver={(e) => {
          if (lockMove) return;
          e.preventDefault();
          setIsDragOverCollapsed(true);
        }}
        onDragLeave={() => setIsDragOverCollapsed(false)}
        onDrop={(e) => {
          e.preventDefault();
          e.stopPropagation();
          setIsDragOverCollapsed(false);
          if (lockMove) {
            onEndDragPanel();
            return;
          }
          const rawId =
            (e.dataTransfer.getData(DND_PANEL_MIME) as DockPanelId) ||
            (e.dataTransfer.getData('text/plain') as DockPanelId) ||
            draggingPanelId;
          if (rawId && DOCK_PANEL_META[rawId]) {
            workspaceStoreActions.movePanel(rawId, { side: 'bottom' });
          }
          onEndDragPanel();
        }}
        className={`h-[26px] px-1.5 flex items-center justify-between gap-1.5 shrink-0 select-none z-20 border-t border-ui-subtle transition-colors ${
          isDragOverCollapsed ? 'bg-ui-accent-subtle border-ui-accent' : 'bg-ui-header'
        }`}
      >
        <div className="flex items-center gap-1 min-w-0 overflow-x-auto no-scrollbar">
          {bottomDock.cells.flatMap((cell) =>
            cell.panelIds.map((pid) => {
              const meta = DOCK_PANEL_META[pid];
              return (
                <button
                  key={`${cell.id}-${pid}`}
                  type="button"
                  data-testid={`bottom-collapsed-tab-${pid}`}
                  onPointerDown={(e) => {
                    if (e.button !== 0 || lockMove) return;
                    e.stopPropagation();
                    onStartPointerTabDrag?.(
                      e,
                      pid,
                      BOTTOM_DOCK_COL_ID,
                      BOTTOM_DOCK_COL_ID,
                      cell.panelIds.length,
                      cell.id
                    );
                  }}
                  onClick={() => {
                    workspaceStoreActions.setGroupActivePanel(
                      BOTTOM_DOCK_COL_ID,
                      BOTTOM_DOCK_COL_ID,
                      pid,
                      cell.id
                    );
                    workspaceStoreActions.toggleBottomDockCollapsed(false);
                  }}
                  title={t('Expand {title}', { title: td(meta.title) })}
                  className="h-5 px-1.5 rounded-ui-xs flex items-center gap-1 text-[10px] text-ui-muted hover:text-ui-primary hover:bg-ui-control-hover cursor-pointer shrink-0"
                >
                  {renderPanelIcon(pid, 'w-3 h-3 shrink-0')}
                  <span className="truncate max-w-[92px]">{td(meta.shortTitle, 'panelShort')}</span>
                </button>
              );
            })
          )}
        </div>

        <button
          type="button"
          data-testid="bottom-dock-collapse-btn"
          onClick={() => workspaceStoreActions.toggleBottomDockCollapsed(false)}
          title={t('Expand Bottom Dock')}
          aria-expanded="false"
          className="h-5 px-1.5 rounded-ui-xs flex items-center gap-1 text-[10px] text-ui-muted hover:text-ui-primary hover:bg-ui-control-hover cursor-pointer shrink-0"
        >
          <ChevronUp className="w-3.5 h-3.5" />
        </button>
      </div>
    );
  }

  const totalWidthRatio = bottomDock.cells.reduce((acc, c) => acc + c.widthRatio, 0) || 1;
  const estCellHeight = Math.max(64, bottomDock.height - 24);

  return (
    <div
      data-testid="bottom-dock-zone"
      data-dock-side="bottom"
      data-collapsed="false"
      className="relative flex flex-col shrink-0 z-20 bg-ui-void border-t border-ui-subtle"
    >
      {/* Top Height Resize Splitter + Slim Collapse Toggle Bar */}
      <div
        data-bottom-dock-splitter="true"
        data-testid="bottom-dock-resizer"
        data-active={isResizingHeight ? 'true' : 'false'}
        data-locked={lockHeight ? 'true' : 'false'}
        onPointerDown={handleStartHeightResize}
        title={lockHeight ? t('Height locked') : t('Drag to resize Bottom Dock height')}
        className={`group/bsplit relative h-[5px] shrink-0 flex items-center justify-center transition-colors ${
          lockHeight ? 'cursor-default' : 'cursor-row-resize'
        }`}
      >
        <span
          aria-hidden="true"
          className={`dock-hsplit-line w-full h-[2px] rounded-full transition-colors ${
            isResizingHeight
              ? 'bg-[var(--ui-accent-border)]'
              : lockHeight
                ? 'bg-[var(--ui-border-subtle)]'
                : 'bg-[var(--ui-border-subtle)] group-hover/bsplit:bg-[var(--ui-accent-border)]'
          }`}
        />
        <button
          type="button"
          data-testid="bottom-dock-collapse-btn"
          onPointerDown={(e) => e.stopPropagation()}
          onClick={handleCollapseBottom}
          title={t('Collapse Bottom Dock')}
          aria-expanded="true"
          className="absolute right-1.5 -top-[5px] h-[14px] px-1.5 rounded-ui-xs bg-ui-header border border-ui-subtle text-ui-muted hover:text-ui-primary hover:border-ui-default flex items-center justify-center cursor-pointer z-30"
        >
          <ChevronDown className="w-3 h-3" />
        </button>
      </div>

      {/* Horizontal Side-by-Side Bottom Dock Cells */}
      <div
        ref={rowRef}
        data-testid="bottom-dock-cells"
        style={{ height: bottomDock.height }}
        className="flex flex-row min-w-0 overflow-hidden"
      >
        {bottomDock.cells.map((cell, cellIdx) => {
          const estWidth = Math.max(
            120,
            Math.round((measuredWidth * cell.widthRatio) / totalWidthRatio)
          );
          return (
            <React.Fragment key={cell.id}>
              <DockCellPanel
                side="bottom"
                colId={BOTTOM_DOCK_COL_ID}
                rowId={BOTTOM_DOCK_COL_ID}
                cell={cell}
                groupIndex={cellIdx}
                isSplitRow={bottomDock.cells.length > 1}
                isRowCollapsed={false}
                estimatedWidth={estWidth}
                estimatedHeight={estCellHeight}
                isCompactToolOnly={false}
                adjacentRowForSideSplit={null}
                draggingPanelId={draggingPanelId}
                onStartDragPanel={onStartDragPanel}
                onEndDragPanel={onEndDragPanel}
                onStartPointerTabDrag={onStartPointerTabDrag}
                onCollapseRowOrDock={handleCollapseBottom}
                renderPanelBody={renderPanelBody}
              />

              {cellIdx < bottomDock.cells.length - 1 && (
                <div
                  data-dock-cell-splitter="true"
                  data-testid={`bottom-cell-splitter-${cellIdx}`}
                  data-active={resizingCellSplitIdx === cellIdx ? 'true' : 'false'}
                  data-locked={lockWidth ? 'true' : 'false'}
                  onPointerDown={(e) =>
                    handleStartCellSplitResize(e, cell, bottomDock.cells[cellIdx + 1], cellIdx)
                  }
                  title={lockWidth ? t('Width locked') : t('Drag to resize side-by-side palettes')}
                  className={`group/csplit relative w-1 shrink-0 flex items-center justify-center transition-colors ${
                    lockWidth ? 'cursor-default' : 'cursor-col-resize'
                  }`}
                >
                  <span
                    aria-hidden="true"
                    className={`dock-vsplit-line h-full w-[2px] rounded-full transition-colors ${
                      resizingCellSplitIdx === cellIdx
                        ? 'bg-[var(--ui-accent-border)]'
                        : lockWidth
                          ? 'bg-[var(--ui-border-subtle)]'
                          : 'bg-[var(--ui-border-subtle)] group-hover/csplit:bg-[var(--ui-accent-border)]'
                    }`}
                  />
                </div>
              )}
            </React.Fragment>
          );
        })}
      </div>
    </div>
  );
});
BottomDockView.displayName = 'BottomDockView';

interface PreviewRect {
  left: number;
  top: number;
  width: number;
  height: number;
}

export type DockDropTarget =
  | {
      kind: 'dock-tab';
      side: DockSide;
      targetColId: string;
      targetGroupId: string;
      targetCellId?: string;
      previewRect: PreviewRect;
      label: string;
    }
  | {
      kind: 'dock-split';
      side: DockSide;
      targetColId: string;
      insertGroupIndex: number;
      previewRect: PreviewRect;
      label: string;
    }
  | {
      kind: 'dock-cell-split';
      side: DockSide;
      targetColId: string;
      targetGroupId: string;
      targetCellId: string;
      splitHorizontal: 'left' | 'right';
      previewRect: PreviewRect;
      label: string;
    }
  | {
      kind: 'dock-column';
      side: DockSide;
      insertColumnIndex: number;
      previewRect: PreviewRect;
      label: string;
    }
  | {
      kind: 'dock-bottom';
      previewRect: PreviewRect;
      label: string;
    }
  | {
      kind: 'floating-tab';
      targetFloatingId: string;
      previewRect: PreviewRect;
      label: string;
    }
  | {
      kind: 'self-noop';
    };

export interface PointerDragSource {
  kind: 'docked-tab' | 'floating-window' | 'floating-tab';
  panelId: DockPanelId;
  sourceFloatingId?: string;
  sourceColId?: string;
  sourceGroupId?: string;
  sourceCellId?: string;
  sourceGroupPanelCount?: number;
}

interface ActivePointerDragUi {
  source: PointerDragSource;
  pointerX: number;
  pointerY: number;
  dropTarget: DockDropTarget | null;
}

export function detectDockDropTarget(
  clientX: number,
  clientY: number,
  workspaceEl: HTMLDivElement | null,
  leftDockEl: HTMLDivElement | null,
  rightDockEl: HTMLDivElement | null,
  layout: WorkspaceLayout,
  source: PointerDragSource,
  canvasStageEl: HTMLDivElement | null = null,
  lockMove = false
): DockDropTarget | null {
  if (typeof document === 'undefined' || lockMove) return null;

  // 1. Check other floating panel headers (merge as tab into another floating panel)
  const floatingHeaders = Array.from(
    document.querySelectorAll<HTMLElement>('[data-drop-floating-header]')
  );
  let bestFloatingMatch: { id: string; z: number; rect: DOMRect } | null = null;
  for (const el of floatingHeaders) {
    const fId = el.getAttribute('data-drop-floating-header');
    if (!fId || fId === source.sourceFloatingId) continue;
    const rect = el.getBoundingClientRect();
    if (
      clientX >= rect.left &&
      clientX <= rect.right &&
      clientY >= rect.top - 4 &&
      clientY <= rect.bottom + 6
    ) {
      const fp = (layout.floatingPanels ?? []).find((p) => p.id === fId);
      const z = fp?.zIndex ?? 0;
      if (!bestFloatingMatch || z >= bestFloatingMatch.z) {
        bestFloatingMatch = { id: fId, z, rect };
      }
    }
  }
  if (bestFloatingMatch) {
    const targetFp = (layout.floatingPanels ?? []).find((p) => p.id === bestFloatingMatch!.id);
    const targetMeta = targetFp ? DOCK_PANEL_META[targetFp.activePanelId] : undefined;
    const title = targetMeta ? translateData(targetMeta.title) : translate('Panel');
    return {
      kind: 'floating-tab',
      targetFloatingId: bestFloatingMatch.id,
      previewRect: {
        left: bestFloatingMatch.rect.left,
        top: bestFloatingMatch.rect.top,
        width: bestFloatingMatch.rect.width,
        height: bestFloatingMatch.rect.height,
      },
      label: translate('Group with {title}', { title }),
    };
  }

  if (!workspaceEl) return null;
  const wsRect = workspaceEl.getBoundingClientRect();
  if (clientY < wsRect.top - 12 || clientY > wsRect.bottom + 12) return null;

  // 2. Extreme outer workspace left / right edges -> create outermost dock column
  const outerEdgeWidth = 22;
  if (clientX >= wsRect.left - 8 && clientX <= wsRect.left + outerEdgeWidth) {
    return {
      kind: 'dock-column',
      side: 'left',
      insertColumnIndex: 0,
      previewRect: {
        left: wsRect.left + 2,
        top: wsRect.top + 4,
        width: 28,
        height: Math.max(40, wsRect.height - 8),
      },
      label: translate('Dock Left Edge'),
    };
  }
  if (clientX <= wsRect.right + 8 && clientX >= wsRect.right - outerEdgeWidth) {
    return {
      kind: 'dock-column',
      side: 'right',
      insertColumnIndex: layout.rightDocks.length,
      previewRect: {
        left: wsRect.right - 30,
        top: wsRect.top + 4,
        width: 28,
        height: Math.max(40, wsRect.height - 8),
      },
      label: translate('Dock Right Edge'),
    };
  }

  // 3. Collapsed dock column strips & collapsed bottom dock strip
  const collapsedCols = Array.from(
    workspaceEl.querySelectorAll<HTMLElement>('[data-drop-collapsed-col]')
  );
  for (const el of collapsedCols) {
    const rect = el.getBoundingClientRect();
    if (
      clientX >= rect.left - 6 &&
      clientX <= rect.right + 6 &&
      clientY >= rect.top &&
      clientY <= rect.bottom
    ) {
      const raw = el.getAttribute('data-drop-collapsed-col') || '';
      const [sideStr, colId, firstGroupId] = raw.split('|');
      if ((sideStr === 'left' || sideStr === 'right') && colId && firstGroupId) {
        return {
          kind: 'dock-tab',
          side: sideStr,
          targetColId: colId,
          targetGroupId: firstGroupId,
          previewRect: {
            left: rect.left,
            top: rect.top + 2,
            width: rect.width,
            height: Math.max(40, rect.height - 4),
          },
          label: translate('Dock to Strip'),
        };
      }
    }
  }

  const collapsedBottom = workspaceEl.querySelector<HTMLElement>('[data-drop-bottom-collapsed]');
  if (collapsedBottom) {
    const rect = collapsedBottom.getBoundingClientRect();
    if (
      clientX >= rect.left &&
      clientX <= rect.right &&
      clientY >= rect.top - 6 &&
      clientY <= rect.bottom + 6
    ) {
      return {
        kind: 'dock-bottom',
        previewRect: {
          left: rect.left + 2,
          top: rect.top,
          width: Math.max(60, rect.width - 4),
          height: Math.max(24, rect.height),
        },
        label: translate('Dock to Bottom'),
      };
    }
  }

  // 4. Column seams for inserting a new column between existing left/right columns
  const expandedCols = Array.from(workspaceEl.querySelectorAll<HTMLElement>('[data-drop-col]'));
  for (const el of expandedCols) {
    const rect = el.getBoundingClientRect();
    if (clientY < rect.top || clientY > rect.bottom) continue;
    const raw = el.getAttribute('data-drop-col') || '';
    const [sideStr, , idxStr] = raw.split('|');
    const colIdx = parseInt(idxStr, 10);
    if ((sideStr !== 'left' && sideStr !== 'right') || isNaN(colIdx)) continue;

    if (sideStr === 'left' && Math.abs(clientX - rect.right) <= 8) {
      return {
        kind: 'dock-column',
        side: 'left',
        insertColumnIndex: colIdx + 1,
        previewRect: {
          left: rect.right - 5,
          top: rect.top + 4,
          width: 10,
          height: Math.max(40, rect.height - 8),
        },
        label: translate('New Left Column'),
      };
    }
    if (sideStr === 'right' && Math.abs(clientX - rect.left) <= 8) {
      return {
        kind: 'dock-column',
        side: 'right',
        insertColumnIndex: colIdx,
        previewRect: {
          left: rect.left - 5,
          top: rect.top + 4,
          width: 10,
          height: Math.max(40, rect.height - 8),
        },
        label: translate('New Right Column'),
      };
    }
  }

  // 4b. Expanded bottom dock cells (header/center = tab merge, left/right 26% = horizontal split)
  const bottomCells = Array.from(
    workspaceEl.querySelectorAll<HTMLElement>('[data-drop-bottom-cell]')
  );
  for (const el of bottomCells) {
    const rect = el.getBoundingClientRect();
    if (
      clientX >= rect.left &&
      clientX <= rect.right &&
      clientY >= rect.top &&
      clientY <= rect.bottom
    ) {
      const cellId = el.getAttribute('data-drop-bottom-cell') || '';
      if (!cellId) continue;

      if (
        source.kind === 'docked-tab' &&
        source.sourceColId === BOTTOM_DOCK_COL_ID &&
        source.sourceCellId === cellId &&
        source.sourceGroupPanelCount === 1
      ) {
        return { kind: 'self-noop' };
      }

      const isOverHeader = clientY <= rect.top + 26;
      const relX = (clientX - rect.left) / Math.max(1, rect.width);

      if (isOverHeader) {
        return {
          kind: 'dock-tab',
          side: 'bottom',
          targetColId: BOTTOM_DOCK_COL_ID,
          targetGroupId: BOTTOM_DOCK_COL_ID,
          targetCellId: cellId,
          previewRect: {
            left: rect.left + 1,
            top: rect.top + 1,
            width: Math.max(24, rect.width - 2),
            height: 24,
          },
          label: translate('Add as Tab'),
        };
      }

      if (relX < 0.26) {
        const splitW = Math.max(28, Math.min(rect.width * 0.45, rect.width - 12));
        return {
          kind: 'dock-cell-split',
          side: 'bottom',
          targetColId: BOTTOM_DOCK_COL_ID,
          targetGroupId: BOTTOM_DOCK_COL_ID,
          targetCellId: cellId,
          splitHorizontal: 'left',
          previewRect: {
            left: rect.left + 2,
            top: rect.top + 2,
            width: splitW,
            height: Math.max(24, rect.height - 4),
          },
          label: translate('Split Left'),
        };
      }

      if (relX > 0.74) {
        const splitW = Math.max(28, Math.min(rect.width * 0.45, rect.width - 12));
        return {
          kind: 'dock-cell-split',
          side: 'bottom',
          targetColId: BOTTOM_DOCK_COL_ID,
          targetGroupId: BOTTOM_DOCK_COL_ID,
          targetCellId: cellId,
          splitHorizontal: 'right',
          previewRect: {
            left: rect.right - splitW - 2,
            top: rect.top + 2,
            width: splitW,
            height: Math.max(24, rect.height - 4),
          },
          label: translate('Split Right'),
        };
      }

      return {
        kind: 'dock-tab',
        side: 'bottom',
        targetColId: BOTTOM_DOCK_COL_ID,
        targetGroupId: BOTTOM_DOCK_COL_ID,
        targetCellId: cellId,
        previewRect: {
          left: rect.left + 2,
          top: rect.top + 2,
          width: Math.max(24, rect.width - 4),
          height: Math.max(24, rect.height - 4),
        },
        label: translate('Add as Tab'),
      };
    }
  }

  // 5. Expanded dock cells in left/right columns — 5 clean geometric drop zones:
  //    Header/Center = Merge Tab, Top = Stack Above, Bottom = Stack Below,
  //    Left = Split Side-by-Side Left (equal height), Right = Split Side-by-Side Right (equal height)
  const dockCells = Array.from(workspaceEl.querySelectorAll<HTMLElement>('[data-drop-cell]'));
  for (const el of dockCells) {
    const raw = el.getAttribute('data-drop-cell') || '';
    const [sideStr, colId, groupId, cellId, idxStr] = raw.split('|');
    if (sideStr !== 'left' && sideStr !== 'right') continue;
    const groupIdx = parseInt(idxStr, 10);
    if (!colId || !groupId || !cellId || isNaN(groupIdx)) continue;

    const rect = el.getBoundingClientRect();
    if (
      clientX >= rect.left &&
      clientX <= rect.right &&
      clientY >= rect.top &&
      clientY <= rect.bottom
    ) {
      // If dragging the sole panel of this exact cell over itself, keep docked (avoid accidental detach)
      if (
        source.kind === 'docked-tab' &&
        source.sourceGroupId === groupId &&
        (!source.sourceCellId || source.sourceCellId === cellId) &&
        source.sourceGroupPanelCount === 1
      ) {
        return { kind: 'self-noop' };
      }

      const isOverHeader = clientY <= rect.top + 26;
      if (isOverHeader) {
        return {
          kind: 'dock-tab',
          side: sideStr,
          targetColId: colId,
          targetGroupId: groupId,
          targetCellId: cellId,
          previewRect: {
            left: rect.left + 1,
            top: rect.top + 1,
            width: Math.max(24, rect.width - 2),
            height: 24,
          },
          label: translate('Add as Tab'),
        };
      }

      const relX = (clientX - rect.left) / Math.max(1, rect.width);
      const relY = (clientY - rect.top) / Math.max(1, rect.height);
      const inTop = relY < 0.24;
      const inBottom = relY > 0.76;
      const inLeft = relX < 0.26;
      const inRight = relX > 0.74;

      const distTop = relY;
      const distBottom = 1 - relY;
      const distLeft = relX;
      const distRight = 1 - relX;

      if (inLeft && distLeft <= distTop && distLeft <= distBottom) {
        const splitW = Math.max(24, Math.min(rect.width * 0.44, rect.width - 10));
        return {
          kind: 'dock-cell-split',
          side: sideStr,
          targetColId: colId,
          targetGroupId: groupId,
          targetCellId: cellId,
          splitHorizontal: 'left',
          previewRect: {
            left: rect.left + 2,
            top: rect.top + 2,
            width: splitW,
            height: Math.max(24, rect.height - 4),
          },
          label: translate('Split Side-by-Side Left'),
        };
      }

      if (inRight && distRight <= distTop && distRight <= distBottom) {
        const splitW = Math.max(24, Math.min(rect.width * 0.44, rect.width - 10));
        return {
          kind: 'dock-cell-split',
          side: sideStr,
          targetColId: colId,
          targetGroupId: groupId,
          targetCellId: cellId,
          splitHorizontal: 'right',
          previewRect: {
            left: rect.right - splitW - 2,
            top: rect.top + 2,
            width: splitW,
            height: Math.max(24, rect.height - 4),
          },
          label: translate('Split Side-by-Side Right'),
        };
      }

      if (inTop) {
        const splitH = Math.max(18, Math.min(44, rect.height * 0.26));
        return {
          kind: 'dock-split',
          side: sideStr,
          targetColId: colId,
          insertGroupIndex: groupIdx,
          previewRect: {
            left: rect.left + 2,
            top: rect.top + 2,
            width: Math.max(24, rect.width - 4),
            height: splitH,
          },
          label: translate('Stack Above'),
        };
      }

      if (inBottom) {
        const splitH = Math.max(18, Math.min(44, rect.height * 0.26));
        return {
          kind: 'dock-split',
          side: sideStr,
          targetColId: colId,
          insertGroupIndex: groupIdx + 1,
          previewRect: {
            left: rect.left + 2,
            top: rect.bottom - splitH - 2,
            width: Math.max(24, rect.width - 4),
            height: splitH,
          },
          label: translate('Stack Below'),
        };
      }

      return {
        kind: 'dock-tab',
        side: sideStr,
        targetColId: colId,
        targetGroupId: groupId,
        targetCellId: cellId,
        previewRect: {
          left: rect.left + 2,
          top: rect.top + 2,
          width: Math.max(24, rect.width - 4),
          height: Math.max(24, rect.height - 4),
        },
        label: translate('Add as Tab'),
      };
    }
  }

  // 6. Inner dock zone edges (beside left/right dock into canvas -> new column)
  //    AND Bottom edge of the canvas viewport -> Dock to Bottom beneath canvas
  if (canvasStageEl) {
    const stageRect = canvasStageEl.getBoundingClientRect();
    if (
      clientX >= stageRect.left + 12 &&
      clientX <= stageRect.right - 12 &&
      clientY >= stageRect.bottom - 38 &&
      clientY <= stageRect.bottom + 12
    ) {
      return {
        kind: 'dock-bottom',
        previewRect: {
          left: stageRect.left + 6,
          top: stageRect.bottom - 36,
          width: Math.max(80, stageRect.width - 12),
          height: 32,
        },
        label: translate('Dock to Bottom'),
      };
    }
  }

  if (leftDockEl && layout.leftDocks.length > 0) {
    const ldRect = leftDockEl.getBoundingClientRect();
    if (clientX > ldRect.right && clientX <= ldRect.right + 26) {
      return {
        kind: 'dock-column',
        side: 'left',
        insertColumnIndex: layout.leftDocks.length,
        previewRect: {
          left: ldRect.right + 2,
          top: wsRect.top + 4,
          width: 24,
          height: Math.max(40, wsRect.height - 8),
        },
        label: translate('New Left Column'),
      };
    }
  }
  if (rightDockEl && layout.rightDocks.length > 0) {
    const rdRect = rightDockEl.getBoundingClientRect();
    if (clientX < rdRect.left && clientX >= rdRect.left - 26) {
      return {
        kind: 'dock-column',
        side: 'right',
        insertColumnIndex: 0,
        previewRect: {
          left: rdRect.left - 26,
          top: wsRect.top + 4,
          width: 24,
          height: Math.max(40, wsRect.height - 8),
        },
        label: translate('New Right Column'),
      };
    }
  }

  return null;
}

export const DockWorkspace: React.FC<DockWorkspaceProps> = React.memo(({
  themePreset,
  colorMode,
  commandHandlers,
  onDeselect,
  onTransformSelection,
  onClearSelection,
  onDeleteOutsideSelection,
  onCutSelection,
  onCopySelection,
  onPasteSelection,
  onMoveSelectionToNewLayer,
  onExpandSelection,
  onContractSelection,
  onFeatherSelection,
  onInvertSelection,
  onToggleTransparentColor,
  layerSidebarProps,
  navigatorProps,
  autoActionProps,
  statusBar,
  children,
}) => {
  const { t, td } = useI18n();
  const layout = useWorkspaceStore((s) => s.layout);
  const palettesHidden = useWorkspaceStore((s) => s.palettesHidden);
  const openPopover = useWorkspaceStore((s) => s.openPopover);
  const workspaceLocks = useWorkspaceStore((s) => s.workspaceLocks);

  const [customBrushes, setCustomBrushes] = useSharedCustomBrushes();
  const [draggingPanelId, setDraggingPanelId] = useState<DockPanelId | null>(null);
  const [edgeDropSide, setEdgeDropSide] = useState<DockSide | null>(null);
  const [pointerDragUi, setPointerDragUi] = useState<ActivePointerDragUi | null>(null);
  const workspaceRef = useRef<HTMLDivElement>(null);
  const leftDockRef = useRef<HTMLDivElement>(null);
  const rightDockRef = useRef<HTMLDivElement>(null);
  const canvasStageRef = useRef<HTMLDivElement>(null);
  const html5DragReleaseRef = useRef<(() => void) | null>(null);

  const floatingPanels = layout.floatingPanels ?? [];

  // Install global non-rerendering scrollbar/chrome pointer guard for pen displays
  useEffect(() => {
    ensureGlobalChromeScrollbarGuard();
    return () => {
      html5DragReleaseRef.current?.();
      html5DragReleaseRef.current = null;
    };
  }, []);

  // Safety cleanup for HTML5 drag guard if dragend finishes outside a tracked node
  useEffect(() => {
    if (!draggingPanelId) return;
    const handleGlobalDragEnd = () => {
      html5DragReleaseRef.current?.();
      html5DragReleaseRef.current = null;
      setDraggingPanelId(null);
      setEdgeDropSide(null);
    };
    window.addEventListener('dragend', handleGlobalDragEnd);
    window.addEventListener('blur', handleGlobalDragEnd);
    return () => {
      window.removeEventListener('dragend', handleGlobalDragEnd);
      window.removeEventListener('blur', handleGlobalDragEnd);
    };
  }, [draggingPanelId]);

  // Close collapsed-strip popover on Escape
  useEffect(() => {
    if (!openPopover) return;
    const handleKey = (e: KeyboardEvent) => {
      if (isImeComposing(e)) return;
      if (e.key === 'Escape') workspaceStoreActions.closePopover();
    };
    window.addEventListener('keydown', handleKey);
    return () => window.removeEventListener('keydown', handleKey);
  }, [openPopover]);

  // Keep all floating panels safely inside the viewport when the window resizes
  useEffect(() => {
    if (floatingPanels.length === 0) return;
    const handleResize = () => {
      const fps = useWorkspaceStore.getState().layout.floatingPanels ?? [];
      for (const fp of fps) {
        workspaceStoreActions.moveFloatingPanel(fp.id, fp.x, fp.y, false);
      }
    };
    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, [floatingPanels.length]);

  const handleStartDragPanel = useCallback((panelId: DockPanelId) => {
    if (useWorkspaceStore.getState().workspaceLocks.lockMove) return;
    html5DragReleaseRef.current?.();
    html5DragReleaseRef.current = acquireWorkspaceInteractionLock('html5-tab-drag');
    setDraggingPanelId(panelId);
  }, []);

  const handleEndDragPanel = useCallback(() => {
    html5DragReleaseRef.current?.();
    html5DragReleaseRef.current = null;
    setDraggingPanelId(null);
    setEdgeDropSide(null);
  }, []);

  // Unified pointer drag: drag any docked tab (or tab from a multi-tab floating panel)
  // to another dock location, side-by-side split, bottom dock, floating panel, or detach!
  const startTabPointerDrag = useCallback(
    (
      e: React.PointerEvent<HTMLButtonElement>,
      panelId: DockPanelId,
      source: PointerDragSource
    ) => {
      if (e.button !== 0 || useWorkspaceStore.getState().workspaceLocks.lockMove) return;
      e.stopPropagation();

      const releaseGuard = acquireWorkspaceInteractionLock('pointer-tab-drag');
      const startX = e.clientX;
      const startY = e.clientY;
      let active = false;
      let latestTarget: DockDropTarget | null = null;

      const cleanup = () => {
        releaseGuard();
        window.removeEventListener('pointermove', onMove);
        window.removeEventListener('pointerup', onUp);
        window.removeEventListener('pointercancel', onCancel);
        window.removeEventListener('keydown', onKeyDown);
        setPointerDragUi(null);
      };

      const onKeyDown = (ev: KeyboardEvent) => {
        if (isImeComposing(ev)) return;
        if (ev.key === 'Escape' && active) {
          ev.preventDefault();
          cleanup();
        }
      };

      const onMove = (ev: PointerEvent) => {
        const dist = Math.hypot(ev.clientX - startX, ev.clientY - startY);
        if (!active) {
          if (dist < 6) return;
          active = true;
        }
        const state = useWorkspaceStore.getState();
        latestTarget = detectDockDropTarget(
          ev.clientX,
          ev.clientY,
          workspaceRef.current,
          leftDockRef.current,
          rightDockRef.current,
          state.layout,
          source,
          canvasStageRef.current,
          state.workspaceLocks.lockMove
        );
        setPointerDragUi({
          source,
          pointerX: ev.clientX,
          pointerY: ev.clientY,
          dropTarget: latestTarget,
        });
      };

      const onCancel = () => {
        cleanup();
      };

      const onUp = (ev: PointerEvent) => {
        const wasActive = active;
        const finalTarget = latestTarget;
        cleanup();
        if (!wasActive || useWorkspaceStore.getState().workspaceLocks.lockMove) return;

        if (!finalTarget) {
          const meta = DOCK_PANEL_META[panelId];
          workspaceStoreActions.detachPanel(panelId, {
            x: ev.clientX - Math.round(meta.defaultFloatWidth / 2),
            y: ev.clientY - Math.round(FLOATING_HEADER_HEIGHT / 2),
          });
          return;
        }

        if (finalTarget.kind === 'self-noop') return;

        if (finalTarget.kind === 'dock-tab') {
          workspaceStoreActions.movePanel(panelId, {
            side: finalTarget.side,
            targetColId: finalTarget.targetColId,
            targetGroupId: finalTarget.targetGroupId,
            targetCellId: finalTarget.targetCellId,
          });
        } else if (finalTarget.kind === 'dock-cell-split') {
          workspaceStoreActions.movePanel(panelId, {
            side: finalTarget.side,
            targetColId: finalTarget.targetColId,
            targetGroupId: finalTarget.targetGroupId,
            targetCellId: finalTarget.targetCellId,
            splitHorizontal: finalTarget.splitHorizontal,
          });
        } else if (finalTarget.kind === 'dock-split') {
          workspaceStoreActions.movePanel(panelId, {
            side: finalTarget.side,
            targetColId: finalTarget.targetColId,
            insertGroupIndex: finalTarget.insertGroupIndex,
          });
        } else if (finalTarget.kind === 'dock-column') {
          workspaceStoreActions.movePanel(panelId, {
            side: finalTarget.side,
            insertColumnIndex: finalTarget.insertColumnIndex,
          });
        } else if (finalTarget.kind === 'dock-bottom') {
          workspaceStoreActions.movePanel(panelId, {
            side: 'bottom',
          });
        } else if (finalTarget.kind === 'floating-tab') {
          workspaceStoreActions.mergePanelIntoFloating(panelId, finalTarget.targetFloatingId);
        }
      };

      window.addEventListener('pointermove', onMove);
      window.addEventListener('pointerup', onUp);
      window.addEventListener('pointercancel', onCancel);
      window.addEventListener('keydown', onKeyDown);
    },
    []
  );

  const handleStartDockedTabDrag = useCallback(
    (
      e: React.PointerEvent<HTMLButtonElement>,
      panelId: DockPanelId,
      colId: string,
      groupId: string,
      groupPanelCount: number,
      cellId?: string
    ) => {
      startTabPointerDrag(e, panelId, {
        kind: 'docked-tab',
        panelId,
        sourceColId: colId,
        sourceGroupId: groupId,
        sourceCellId: cellId,
        sourceGroupPanelCount: groupPanelCount,
      });
    },
    [startTabPointerDrag]
  );

  const handleStartFloatingTabDrag = useCallback(
    (
      e: React.PointerEvent<HTMLButtonElement>,
      panelId: DockPanelId,
      floatingId: string
    ) => {
      startTabPointerDrag(e, panelId, {
        kind: 'floating-tab',
        panelId,
        sourceFloatingId: floatingId,
      });
    },
    [startTabPointerDrag]
  );

  // Dragging a floating panel by its title bar: moves freely at 60fps AND snaps/reattaches
  // when dropped onto any dock zone (left, right, split cell, bottom) or another floating panel!
  const handleStartFloatingHeaderDrag = useCallback(
    (e: React.PointerEvent<HTMLDivElement>, floatingId: string) => {
      if (e.button !== 0 || useWorkspaceStore.getState().workspaceLocks.lockMove) return;
      const fp = (useWorkspaceStore.getState().layout.floatingPanels ?? []).find(
        (f) => f.id === floatingId
      );
      if (!fp) return;

      e.preventDefault();
      e.stopPropagation();

      const releaseGuard = acquireWorkspaceInteractionLock('floating-panel-drag');
      const targetEl = e.currentTarget;
      const pointerId = e.pointerId;
      try {
        targetEl.setPointerCapture?.(pointerId);
      } catch {
        // Ignore synthetic pointer events
      }

      const startX = e.clientX;
      const startY = e.clientY;
      const origX = fp.x;
      const origY = fp.y;
      const source: PointerDragSource = {
        kind: 'floating-window',
        panelId: fp.activePanelId,
        sourceFloatingId: floatingId,
      };
      let active = false;
      let latestTarget: DockDropTarget | null = null;

      const cleanup = () => {
        releaseGuard();
        try {
          if (targetEl.hasPointerCapture?.(pointerId)) {
            targetEl.releasePointerCapture?.(pointerId);
          }
        } catch {
          // Ignore synthetic capture release errors
        }
        window.removeEventListener('pointermove', onMove);
        window.removeEventListener('pointerup', onUp);
        window.removeEventListener('pointercancel', onCancel);
        window.removeEventListener('keydown', onKeyDown);
        setPointerDragUi(null);
      };

      const onKeyDown = (ev: KeyboardEvent) => {
        if (isImeComposing(ev)) return;
        if (ev.key === 'Escape' && active) {
          ev.preventDefault();
          workspaceStoreActions.moveFloatingPanel(floatingId, origX, origY, false);
          cleanup();
        }
      };

      const onMove = (ev: PointerEvent) => {
        const dx = ev.clientX - startX;
        const dy = ev.clientY - startY;
        if (!active) {
          if (Math.hypot(dx, dy) < 4) return;
          active = true;
        }
        workspaceStoreActions.moveFloatingPanel(floatingId, origX + dx, origY + dy, false);
        const state = useWorkspaceStore.getState();
        latestTarget = detectDockDropTarget(
          ev.clientX,
          ev.clientY,
          workspaceRef.current,
          leftDockRef.current,
          rightDockRef.current,
          state.layout,
          source,
          canvasStageRef.current,
          state.workspaceLocks.lockMove
        );
        setPointerDragUi({
          source,
          pointerX: ev.clientX,
          pointerY: ev.clientY,
          dropTarget: latestTarget,
        });
      };

      const onCancel = () => {
        if (active) {
          workspaceStoreActions.moveFloatingPanel(floatingId, origX, origY, false);
        }
        cleanup();
      };

      const onUp = (ev: PointerEvent) => {
        const wasActive = active;
        const finalTarget = latestTarget;
        cleanup();
        if (!wasActive) return;

        if (!finalTarget || finalTarget.kind === 'self-noop') {
          workspaceStoreActions.moveFloatingPanel(
            floatingId,
            origX + (ev.clientX - startX),
            origY + (ev.clientY - startY),
            true
          );
          return;
        }

        if (finalTarget.kind === 'dock-tab') {
          workspaceStoreActions.dockFloatingPanel(floatingId, {
            side: finalTarget.side,
            targetColId: finalTarget.targetColId,
            targetGroupId: finalTarget.targetGroupId,
            targetCellId: finalTarget.targetCellId,
          });
        } else if (finalTarget.kind === 'dock-cell-split') {
          workspaceStoreActions.dockFloatingPanel(floatingId, {
            side: finalTarget.side,
            targetColId: finalTarget.targetColId,
            targetGroupId: finalTarget.targetGroupId,
            targetCellId: finalTarget.targetCellId,
            splitHorizontal: finalTarget.splitHorizontal,
          });
        } else if (finalTarget.kind === 'dock-split') {
          workspaceStoreActions.dockFloatingPanel(floatingId, {
            side: finalTarget.side,
            targetColId: finalTarget.targetColId,
            insertGroupIndex: finalTarget.insertGroupIndex,
          });
        } else if (finalTarget.kind === 'dock-column') {
          workspaceStoreActions.dockFloatingPanel(floatingId, {
            side: finalTarget.side,
            insertColumnIndex: finalTarget.insertColumnIndex,
          });
        } else if (finalTarget.kind === 'dock-bottom') {
          workspaceStoreActions.dockFloatingPanel(floatingId, {
            side: 'bottom',
          });
        } else if (finalTarget.kind === 'floating-tab') {
          const latestFp = (useWorkspaceStore.getState().layout.floatingPanels ?? []).find(
            (f) => f.id === floatingId
          );
          if (latestFp) {
            for (const pid of [...latestFp.panelIds]) {
              workspaceStoreActions.mergePanelIntoFloating(pid, finalTarget.targetFloatingId);
            }
          }
        }
      };

      window.addEventListener('pointermove', onMove);
      window.addEventListener('pointerup', onUp);
      window.addEventListener('pointercancel', onCancel);
      window.addEventListener('keydown', onKeyDown);
    },
    []
  );

  const handleDropEdge = (e: React.DragEvent, side: DockSide) => {
    e.preventDefault();
    if (useWorkspaceStore.getState().workspaceLocks.lockMove) {
      handleEndDragPanel();
      return;
    }
    const rawId =
      (e.dataTransfer.getData(DND_PANEL_MIME) as DockPanelId) ||
      (e.dataTransfer.getData('text/plain') as DockPanelId) ||
      draggingPanelId;
    if (rawId && DOCK_PANEL_META[rawId]) {
      if (side === 'bottom') {
        workspaceStoreActions.movePanel(rawId, { side: 'bottom' });
      } else {
        workspaceStoreActions.movePanel(rawId, {
          side,
          insertColumnIndex: side === 'left' ? layout.leftDocks.length : 0,
        });
      }
    }
    handleEndDragPanel();
  };

  const renderPanelBody = useCallback(
    (panelId: DockPanelId, containerWidth: number, containerHeight?: number): React.ReactNode => {
      switch (panelId) {
        case 'tools':
          return (
            <ToolStrip
              fluid
              onTransformSelection={onTransformSelection}
              onToggleTransparentColor={onToggleTransparentColor}
            />
          );
        case 'subtool':
          return (
            <div className="flex flex-col h-full min-h-0 overflow-hidden bg-ui-panel">
              <SubToolList
                customBrushes={customBrushes}
                setCustomBrushes={setCustomBrushes}
              />
            </div>
          );
        case 'tool-property':
          return (
            <div className="flex flex-col h-full min-h-0 overflow-hidden bg-ui-panel">
              <ToolPropertyInspector
                width={containerWidth}
                customBrushes={customBrushes}
                setCustomBrushes={setCustomBrushes}
                onDeselect={onDeselect}
                onTransformSelection={onTransformSelection}
                onClearSelection={onClearSelection}
                onDeleteOutsideSelection={onDeleteOutsideSelection}
                onCutSelection={onCutSelection}
                onCopySelection={onCopySelection}
                onPasteSelection={onPasteSelection}
                onMoveSelectionToNewLayer={onMoveSelectionToNewLayer}
                onExpandSelection={onExpandSelection}
                onContractSelection={onContractSelection}
                onFeatherSelection={onFeatherSelection}
                onInvertSelection={onInvertSelection}
              />
            </div>
          );
        case 'brush-size':
          return <BrushSizeDockedContent themePreset={themePreset} />;
        case 'navigator':
          return navigatorProps ? (
            <NavigatorPanel {...navigatorProps} themePreset={themePreset} />
          ) : null;
        case 'sub-view':
          return <SubViewPanel colorMode={colorMode} themePreset={themePreset} />;
        case 'info':
          return (
            <InfoPanel
              layers={layerSidebarProps.layers}
              colorMode={colorMode}
              themePreset={themePreset}
            />
          );
        case 'color':
          return (
            <RightSidebarColorSection
              colorMode={colorMode}
              containerWidth={containerWidth}
              containerHeight={containerHeight}
              fullHeight
            />
          );
        case 'color-sliders':
          return (
            <ColorSliderDockedContent
              colorMode={colorMode}
              containerWidth={containerWidth}
              containerHeight={containerHeight}
            />
          );
        case 'color-sets':
          return (
            <ColorSetsPanel
              colorMode={colorMode}
              containerWidth={containerWidth}
            />
          );
        case 'color-history':
          return (
            <ColorHistoryPanel
              colorMode={colorMode}
              containerWidth={containerWidth}
            />
          );
        case 'layers':
          return (
            <RightSidebar
              {...layerSidebarProps}
              hideColorPanel
              dockedMode="layers"
            />
          );
        case 'history':
          return (
            <RightSidebar
              {...layerSidebarProps}
              hideColorPanel
              dockedMode="history"
            />
          );
        case 'quick-access':
          return (
            <QuickAccessPanel
              handlers={commandHandlers}
              themePreset={themePreset}
            />
          );
        case 'auto-actions':
          return autoActionProps ? (
            <AutoActionPanel {...autoActionProps} />
          ) : null;
      }
    },
    [
      autoActionProps,
      colorMode,
      commandHandlers,
      customBrushes,
      layerSidebarProps,
      navigatorProps,
      onClearSelection,
      onContractSelection,
      onCopySelection,
      onCutSelection,
      onDeleteOutsideSelection,
      onDeselect,
      onExpandSelection,
      onFeatherSelection,
      onInvertSelection,
      onMoveSelectionToNewLayer,
      onPasteSelection,
      onToggleTransparentColor,
      onTransformSelection,
      setCustomBrushes,
      themePreset,
    ]
  );

  const visibleDropTarget =
    pointerDragUi?.dropTarget && pointerDragUi.dropTarget.kind !== 'self-noop'
      ? pointerDragUi.dropTarget
      : null;

  return (
    <div
      ref={workspaceRef}
      data-testid="dock-workspace"
      data-palettes-hidden={String(palettesHidden)}
      className="flex flex-1 min-h-0 overflow-hidden relative gap-px bg-ui-void"
    >
      {/* Left Dock Zone */}
      {!palettesHidden && (
        <div
          ref={leftDockRef}
          data-testid="left-dock-zone"
          className="flex h-full shrink-0 gap-px relative z-20"
        >
          {(layout?.leftDocks ?? []).map((col, colIdx) => (
            <DockColumnView
              key={col.id}
              side="left"
              col={col}
              colIndex={colIdx}
              themePreset={themePreset}
              draggingPanelId={draggingPanelId}
              onStartDragPanel={handleStartDragPanel}
              onEndDragPanel={handleEndDragPanel}
              onStartPointerTabDrag={handleStartDockedTabDrag}
              renderPanelBody={renderPanelBody}
            />
          ))}

          {/* Left-side New Column Drop Zone while HTML5-dragging */}
          {draggingPanelId && !workspaceLocks.lockMove && (
            <div
              onDragOver={(e) => {
                e.preventDefault();
                setEdgeDropSide('left');
              }}
              onDragLeave={() => setEdgeDropSide(null)}
              onDrop={(e) => handleDropEdge(e, 'left')}
              className={`w-4 h-full transition-all flex items-center justify-center ${
                edgeDropSide === 'left'
                  ? 'w-8 bg-ui-accent-subtle border-2 border-dashed border-ui-accent'
                  : 'bg-ui-accent-subtle/40'
              }`}
              title={t('Drop to create new Left Dock column')}
            />
          )}
        </div>
      )}

      {/* Center Canvas Column (Canvas Stage + Bottom Dock Zone + StatusBar) */}
      <div
        data-testid="canvas-center-column"
        className="flex flex-col flex-1 min-w-0 min-h-0 overflow-hidden relative bg-ui-canvas-matte"
        onMouseDown={() => {
          if (openPopover) workspaceStoreActions.closePopover();
        }}
      >
        {/* Canvas Stage Region (DocumentTabBar + CanvasArea + FocusMode / QuickBrush) */}
        <div
          ref={canvasStageRef}
          data-testid="canvas-stage-region"
          className="flex flex-col flex-1 min-w-0 min-h-0 overflow-hidden relative"
        >
          {children}

          {/* HTML5 Bottom Dock Drop Zone while dragging a palette tab */}
          {!palettesHidden && draggingPanelId && !workspaceLocks.lockMove && (
            <div
              data-testid="bottom-dock-drop-zone"
              onDragOver={(e) => {
                e.preventDefault();
                setEdgeDropSide('bottom');
              }}
              onDragLeave={() => setEdgeDropSide(null)}
              onDrop={(e) => handleDropEdge(e, 'bottom')}
              className={`absolute left-2 right-2 bottom-1 z-30 rounded-ui-xs transition-all flex items-center justify-center ${
                edgeDropSide === 'bottom'
                  ? 'h-8 bg-ui-accent-subtle border-2 border-dashed border-ui-accent'
                  : 'h-4 bg-ui-accent-subtle/40 border border-dashed border-ui-accent-border/60'
              }`}
              title={t('Drop to dock beneath the canvas')}
            >
              {edgeDropSide === 'bottom' && (
                <span className="text-[10px] font-medium text-ui-primary">{t('Dock to Bottom')}</span>
              )}
            </div>
          )}

          {/* Floating Quick-Access Brush Panel (stays accessible in Focus Mode when keepQuickBrushPanel is on) */}
          <QuickBrushPanel customBrushes={customBrushes} />

          {/* Artist-First Focus Mode Floating Micro-HUD Overlay (zero overhead in normal mode) */}
          <FocusModeOverlay
            colorMode={colorMode}
            commandHandlers={commandHandlers}
            onTransformSelection={onTransformSelection}
            onToggleTransparentColor={onToggleTransparentColor}
          />
        </div>

        {/* Bottom Dock Zone (directly beneath canvas viewport, above StatusBar, hidden in Focus Mode) */}
        {!palettesHidden && layout.bottomDock && layout.bottomDock.cells.length > 0 && (
          <BottomDockView
            bottomDock={layout.bottomDock}
            draggingPanelId={draggingPanelId}
            onStartDragPanel={handleStartDragPanel}
            onEndDragPanel={handleEndDragPanel}
            onStartPointerTabDrag={handleStartDockedTabDrag}
            renderPanelBody={renderPanelBody}
          />
        )}

        {/* Status Bar sits cleanly beneath Bottom Dock */}
        {statusBar}
      </div>

      {/* Right Dock Zone */}
      {!palettesHidden && (
        <div
          ref={rightDockRef}
          data-testid="right-dock-zone"
          className="flex h-full shrink-0 gap-px relative z-20"
        >
          {/* Right-side New Column Drop Zone while HTML5-dragging */}
          {draggingPanelId && !workspaceLocks.lockMove && (
            <div
              onDragOver={(e) => {
                e.preventDefault();
                setEdgeDropSide('right');
              }}
              onDragLeave={() => setEdgeDropSide(null)}
              onDrop={(e) => handleDropEdge(e, 'right')}
              className={`w-4 h-full transition-all flex items-center justify-center ${
                edgeDropSide === 'right'
                  ? 'w-8 bg-ui-accent-subtle border-2 border-dashed border-ui-accent'
                  : 'bg-ui-accent-subtle/40'
              }`}
              title={t('Drop to create new Right Dock column')}
            />
          )}

          {(layout?.rightDocks ?? []).map((col, colIdx) => (
            <DockColumnView
              key={col.id}
              side="right"
              col={col}
              colIndex={colIdx}
              themePreset={themePreset}
              draggingPanelId={draggingPanelId}
              onStartDragPanel={handleStartDragPanel}
              onEndDragPanel={handleEndDragPanel}
              onStartPointerTabDrag={handleStartDockedTabDrag}
              renderPanelBody={renderPanelBody}
            />
          ))}
        </div>
      )}

      {/* Freely Floating Detached Panels (Portaled to document.body, non-blocking) */}
      {!palettesHidden &&
        floatingPanels.map((fp) => (
          <FloatingPanelWindow
            key={fp.id}
            panel={fp}
            isDragging={
              pointerDragUi?.source.kind === 'floating-window' &&
              pointerDragUi.source.sourceFloatingId === fp.id
            }
            isDockTargetActive={
              pointerDragUi?.source.kind === 'floating-window' &&
              pointerDragUi.source.sourceFloatingId === fp.id &&
              Boolean(visibleDropTarget)
            }
            isMergeTabTarget={
              visibleDropTarget?.kind === 'floating-tab' &&
              visibleDropTarget.targetFloatingId === fp.id
            }
            renderPanelIcon={renderPanelIcon}
            renderPanelBody={renderPanelBody}
            onStartHeaderDrag={handleStartFloatingHeaderDrag}
            onStartTabDrag={handleStartFloatingTabDrag}
          />
        ))}

      {/* Live Dock Drop Preview Overlay while dragging a panel */}
      {visibleDropTarget &&
        typeof document !== 'undefined' &&
        createPortal(
          <div
            data-testid="dock-drop-preview"
            style={{
              position: 'fixed',
              left: visibleDropTarget.previewRect.left,
              top: visibleDropTarget.previewRect.top,
              width: visibleDropTarget.previewRect.width,
              height: visibleDropTarget.previewRect.height,
              zIndex: 49,
            }}
            className="pointer-events-none rounded-ui-xs border-2 border-ui-accent bg-ui-accent-subtle flex items-center justify-center transition-all duration-75"
          >
            <span className="px-2 py-0.5 rounded-ui-xs bg-ui-elevated border border-ui-accent-border text-[10px] font-medium text-ui-primary whitespace-nowrap shadow-ui-floating">
              {visibleDropTarget.label}
            </span>
          </div>,
          document.body
        )}

      {/* Floating Drag Ghost Pill when dragging a docked tab or splitting a floating tab */}
      {pointerDragUi &&
        pointerDragUi.source.kind !== 'floating-window' &&
        typeof document !== 'undefined' &&
        createPortal(
          <div
            data-testid="panel-drag-ghost"
            style={{
              position: 'fixed',
              left: pointerDragUi.pointerX + 12,
              top: pointerDragUi.pointerY + 12,
              zIndex: 49,
            }}
            className="pointer-events-none flex items-center gap-1.5 px-2.5 py-1.5 rounded-ui-md bg-ui-floating border border-ui-strong shadow-ui-floating text-[11px] text-ui-primary select-none"
          >
            {renderPanelIcon(pointerDragUi.source.panelId, 'w-3.5 h-3.5 text-ui-accent')}
            <span className="font-medium">
              {td(DOCK_PANEL_META[pointerDragUi.source.panelId].title)}
            </span>
            <span className="text-[10px] text-ui-muted border-l border-ui-subtle pl-1.5">
              {visibleDropTarget
                ? visibleDropTarget.label
                : pointerDragUi.dropTarget?.kind === 'self-noop'
                  ? t('Drag outside to float')
                  : t('Release to float')}
            </span>
          </div>,
          document.body
        )}
    </div>
  );
});

DockWorkspace.displayName = 'DockWorkspace';