Skip to content

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

88.1 KB
Raw Blame
import { safeLocalStorageSetItem } from './safeStorage';
import { t } from '../i18n';
import { migrateLegacyPresetId } from './brushPresetManager';
import { clampNavigatorSplitRatio, DEFAULT_NAVIGATOR_SPLIT_RATIO } from './valueCheck';
import { BrushPresetId } from '../types/editor';
import {
  AppearanceConfig,
  INK_THEME_FORMAT_ID,
  INK_THEME_SCHEMA_VERSION,
  sanitizeAppearanceConfig,
} from '../types/appearance';
import { parseThemePreset } from './themeEngine';
import {
  ALL_DOCK_PANEL_IDS,
  BOTTOM_DOCK_COL_ID,
  BOTTOM_DOCK_DEFAULT_HEIGHT,
  BOTTOM_DOCK_MAX_HEIGHT,
  BOTTOM_DOCK_MIN_HEIGHT,
  BUILT_IN_WORKSPACE_PRESET_IDS,
  BuiltInWorkspacePresetId,
  COMMAND_CATALOG,
  CommandActionId,
  DEFAULT_STATUS_BAR_MODULES,
  DEFAULT_WORKSPACE_LOCKS,
  DOCK_PANEL_META,
  DockBottomZone,
  DockColumn,
  DockGroup,
  DockPanelId,
  DockSide,
  DockSplitCell,
  FloatingPanelLastDock,
  FloatingPanelState,
  FocusHudConfig,
  FocusHudPositions,
  FocusHudPresetId,
  FocusHudWidgetId,
  INK_WORKSPACE_FORMAT_ID,
  INK_WORKSPACE_SCHEMA_VERSION,
  InkWorkspaceBundleFile,
  NavigatorPreviewMode,
  ParseWorkspaceBundleResult,
  PersistedWorkspaceState,
  QuickAccessItem,
  QuickAccessViewMode,
  QuickBrushPanelOrientation,
  QuickBrushPanelState,
  QuickBrushPreviewStyle,
  QuickBrushTileSize,
  SavedWorkspaceProfile,
  StatusBarModulesConfig,
  WorkspaceLayout,
  WorkspaceLocks,
  WorkspacePresetId,
} from '../types/workspace';

export const WORKSPACE_STORAGE_KEY = 'ink_studio_workspace_v1';

const VALID_PANEL_SET = new Set<string>(ALL_DOCK_PANEL_IDS);
const VALID_COMMAND_SET = new Set<string>(COMMAND_CATALOG.map((c) => c.id));

export const DEFAULT_ILLUSTRATION_LAYOUT: WorkspaceLayout = {
  leftDocks: [
    {
      id: 'col-left-tools',
      width: 46,
      collapsed: false,
      groups: [
        {
          id: 'grp-tools',
          panelIds: ['tools'],
          activePanelId: 'tools',
          heightRatio: 1,
        },
      ],
    },
    {
      id: 'col-left-brushes',
      width: 204,
      collapsed: false,
      groups: [
        {
          id: 'grp-subtool',
          panelIds: ['subtool'],
          activePanelId: 'subtool',
          heightRatio: 0.34,
        },
        {
          id: 'grp-tool-prop',
          panelIds: ['tool-property'],
          activePanelId: 'tool-property',
          heightRatio: 0.38,
        },
        {
          id: 'grp-brush-size',
          panelIds: ['brush-size'],
          activePanelId: 'brush-size',
          heightRatio: 0.28,
        },
      ],
    },
  ],
  rightDocks: [
    {
      id: 'col-right-quick',
      width: 180,
      collapsed: true,
      groups: [
        {
          id: 'grp-quick-access',
          panelIds: ['quick-access'],
          activePanelId: 'quick-access',
          heightRatio: 1,
        },
      ],
    },
    {
      id: 'col-right-main',
      width: 224,
      collapsed: false,
      groups: [
        {
          id: 'grp-navigator-subview',
          panelIds: ['navigator', 'sub-view', 'info'],
          activePanelId: 'navigator',
          heightRatio: 0.26,
        },
        {
          id: 'grp-color',
          panelIds: ['color', 'color-sliders', 'color-sets', 'color-history'],
          activePanelId: 'color',
          heightRatio: 0.26,
        },
        {
          id: 'grp-layers-history',
          panelIds: ['layers', 'history', 'auto-actions'],
          activePanelId: 'layers',
          heightRatio: 0.48,
        },
      ],
    },
  ],
};

export const MANGA_STUDIO_LAYOUT: WorkspaceLayout = {
  leftDocks: [
    {
      id: 'col-manga-tools',
      width: 46,
      collapsed: false,
      groups: [
        {
          id: 'grp-manga-tools',
          panelIds: ['tools'],
          activePanelId: 'tools',
          heightRatio: 1,
        },
      ],
    },
    {
      id: 'col-manga-ink',
      width: 196,
      collapsed: false,
      groups: [
        {
          id: 'grp-manga-subtool',
          panelIds: ['subtool'],
          activePanelId: 'subtool',
          heightRatio: 0.45,
        },
        {
          id: 'grp-manga-size',
          panelIds: ['brush-size'],
          activePanelId: 'brush-size',
          heightRatio: 0.55,
        },
      ],
    },
    {
      id: 'col-manga-prop',
      width: 184,
      collapsed: true,
      groups: [
        {
          id: 'grp-manga-prop',
          panelIds: ['tool-property'],
          activePanelId: 'tool-property',
          heightRatio: 1,
        },
      ],
    },
  ],
  rightDocks: [
    {
      id: 'col-manga-quick',
      width: 168,
      collapsed: false,
      groups: [
        {
          id: 'grp-manga-quick',
          panelIds: ['quick-access'],
          activePanelId: 'quick-access',
          heightRatio: 0.65,
        },
        {
          id: 'grp-manga-color',
          panelIds: ['color', 'color-sliders', 'color-sets', 'color-history'],
          activePanelId: 'color',
          heightRatio: 0.35,
        },
      ],
    },
    {
      id: 'col-manga-layers',
      width: 232,
      collapsed: false,
      groups: [
        {
          id: 'grp-manga-nav-subview',
          panelIds: ['navigator', 'sub-view', 'info'],
          activePanelId: 'navigator',
          heightRatio: 0.26,
        },
        {
          id: 'grp-manga-layers',
          panelIds: ['layers'],
          activePanelId: 'layers',
          heightRatio: 0.5,
        },
        {
          id: 'grp-manga-history',
          panelIds: ['history'],
          activePanelId: 'history',
          heightRatio: 0.24,
        },
      ],
    },
  ],
};

export const MINIMALIST_TABLET_LAYOUT: WorkspaceLayout = {
  leftDocks: [
    {
      id: 'col-tablet-tools',
      width: 46,
      collapsed: false,
      groups: [
        {
          id: 'grp-tablet-tools',
          panelIds: ['tools'],
          activePanelId: 'tools',
          heightRatio: 1,
        },
      ],
    },
    {
      id: 'col-tablet-left-strip',
      width: 210,
      collapsed: true,
      groups: [
        {
          id: 'grp-tablet-brush',
          panelIds: ['subtool', 'tool-property', 'brush-size', 'color', 'color-sliders', 'color-sets', 'color-history'],
          activePanelId: 'subtool',
          heightRatio: 1,
        },
      ],
    },
  ],
  rightDocks: [
    {
      id: 'col-tablet-right-strip',
      width: 224,
      collapsed: true,
      groups: [
        {
          id: 'grp-tablet-layers',
          panelIds: ['navigator', 'sub-view', 'info', 'layers', 'history', 'auto-actions', 'quick-access'],
          activePanelId: 'layers',
          heightRatio: 1,
        },
      ],
    },
  ],
};

/**
 * Photoshop Studio archetype:
 * Slim left tool rail + collapsed secondary utility strip + right Color / Brushes / Layers stack.
 * Pairs with the top Contextual Tool Options Bar enabled by default.
 */
export const PHOTOSHOP_STUDIO_LAYOUT: WorkspaceLayout = {
  leftDocks: [
    {
      id: 'col-ps-tools',
      width: 46,
      collapsed: false,
      groups: [
        {
          id: 'grp-ps-tools',
          panelIds: ['tools'],
          activePanelId: 'tools',
          heightRatio: 1,
        },
      ],
    },
  ],
  rightDocks: [
    {
      id: 'col-ps-util-strip',
      width: 204,
      collapsed: true,
      groups: [
        {
          id: 'grp-ps-util',
          panelIds: ['navigator', 'sub-view', 'info', 'history', 'quick-access', 'auto-actions'],
          activePanelId: 'navigator',
          heightRatio: 1,
        },
      ],
    },
    {
      id: 'col-ps-main',
      width: 244,
      collapsed: false,
      groups: [
        {
          id: 'grp-ps-color',
          panelIds: ['color', 'color-sets', 'color-sliders', 'color-history'],
          activePanelId: 'color',
          heightRatio: 0.3,
        },
        {
          id: 'grp-ps-brushes',
          panelIds: ['subtool', 'tool-property', 'brush-size'],
          activePanelId: 'subtool',
          heightRatio: 0.28,
        },
        {
          id: 'grp-ps-layers',
          panelIds: ['layers'],
          activePanelId: 'layers',
          heightRatio: 0.42,
        },
      ],
    },
  ],
};

/**
 * Classic Clip Studio Paint archetype:
 * Left Tool rail + stacked Sub Tool / Tool Property / Brush Size,
 * Right collapsed History/Quick/Actions rail + Navigator / Color / dedicated Layers stack.
 */
export const CLIP_STUDIO_LAYOUT: WorkspaceLayout = {
  leftDocks: [
    {
      id: 'col-csp-tools',
      width: 46,
      collapsed: false,
      groups: [
        {
          id: 'grp-csp-tools',
          panelIds: ['tools'],
          activePanelId: 'tools',
          heightRatio: 1,
        },
      ],
    },
    {
      id: 'col-csp-brushes',
      width: 204,
      collapsed: false,
      groups: [
        {
          id: 'grp-csp-subtool',
          panelIds: ['subtool'],
          activePanelId: 'subtool',
          heightRatio: 0.35,
        },
        {
          id: 'grp-csp-prop',
          panelIds: ['tool-property'],
          activePanelId: 'tool-property',
          heightRatio: 0.4,
        },
        {
          id: 'grp-csp-size',
          panelIds: ['brush-size'],
          activePanelId: 'brush-size',
          heightRatio: 0.25,
        },
      ],
    },
  ],
  rightDocks: [
    {
      id: 'col-csp-util',
      width: 196,
      collapsed: true,
      groups: [
        {
          id: 'grp-csp-util',
          panelIds: ['history', 'quick-access', 'auto-actions'],
          activePanelId: 'history',
          heightRatio: 1,
        },
      ],
    },
    {
      id: 'col-csp-main',
      width: 232,
      collapsed: false,
      groups: [
        {
          id: 'grp-csp-navigator',
          panelIds: ['navigator', 'sub-view', 'info'],
          activePanelId: 'navigator',
          heightRatio: 0.26,
        },
        {
          id: 'grp-csp-color',
          panelIds: ['color', 'color-sliders', 'color-sets', 'color-history'],
          activePanelId: 'color',
          heightRatio: 0.28,
        },
        {
          id: 'grp-csp-layers',
          panelIds: ['layers'],
          activePanelId: 'layers',
          heightRatio: 0.46,
        },
      ],
    },
  ],
};

export const DEFAULT_QUICK_ACCESS_ITEMS: QuickAccessItem[] = [
  { id: 'qa-flip-h', kind: 'command', label: 'Flip Horizontal', commandId: 'flip-h' },
  { id: 'qa-clear-layer', kind: 'command', label: 'Clear Layer', commandId: 'clear-layer' },
  { id: 'qa-merge-down', kind: 'command', label: 'Merge Down', commandId: 'merge-down' },
  { id: 'qa-save', kind: 'command', label: 'Save', commandId: 'save' },
  { id: 'qa-undo', kind: 'command', label: 'Undo', commandId: 'undo' },
  { id: 'qa-redo', kind: 'command', label: 'Redo', commandId: 'redo' },
  { id: 'qa-new-layer', kind: 'command', label: 'New Layer', commandId: 'new-layer' },
  { id: 'qa-reset-zoom', kind: 'command', label: 'Reset Zoom', commandId: 'reset-zoom' },
  { id: 'qa-tool-brush', kind: 'tool', label: 'Brush', toolId: 'brush' },
  { id: 'qa-tool-eraser', kind: 'tool', label: 'Eraser', toolId: 'eraser' },
  { id: 'qa-color-black', kind: 'color', label: 'Ink Black', color: '#000000' },
  { id: 'qa-color-white', kind: 'color', label: 'Paper White', color: '#ffffff' },
];

export const DEFAULT_COMMAND_BAR_IDS: CommandActionId[] = [
  'save',
  'undo',
  'redo',
  'flip-h',
  'flip-v',
  'clear-layer',
  'merge-down',
  'toggle-palettes',
  'toggle-quick-brushes',
];

export const DEFAULT_FOCUS_QUICK_ACTION_IDS: CommandActionId[] = [
  'eyedropper',
  'selection',
  'flip-h',
  'value-check',
  'new-layer',
  'reset-zoom',
  'fullscreen',
];

export const FOCUS_HUD_WIDGET_IDS: readonly FocusHudWidgetId[] = [
  'brushSliders',
  'quickActionDock',
  'colorWheel',
  'toolRail',
] as const;

export function createFocusHudPresetPatch(
  preset: 'atelier-hud' | 'pure-canvas'
): Pick<
  FocusHudConfig,
  | 'preset'
  | 'showToolRail'
  | 'showBrushSlidersHud'
  | 'showQuickActionDock'
  | 'showFloatingColorWheel'
  | 'keepQuickBrushPanel'
  | 'hideHeaderInFocus'
> {
  if (preset === 'pure-canvas') {
    return {
      preset: 'pure-canvas',
      showToolRail: false,
      showBrushSlidersHud: false,
      showQuickActionDock: false,
      showFloatingColorWheel: false,
      keepQuickBrushPanel: false,
      hideHeaderInFocus: true,
    };
  }
  return {
    preset: 'atelier-hud',
    showToolRail: false,
    showBrushSlidersHud: true,
    showQuickActionDock: true,
    showFloatingColorWheel: true,
    keepQuickBrushPanel: true,
    hideHeaderInFocus: true,
  };
}

export function createDefaultFocusHudConfig(): FocusHudConfig {
  return {
    ...createFocusHudPresetPatch('atelier-hud'),
    autoFadeWhileDrawing: true,
    quickActionIds: [...DEFAULT_FOCUS_QUICK_ACTION_IDS],
    hudPositions: {},
  };
}

export const DEFAULT_QUICK_BRUSH_IDS: BrushPresetId[] = [];

/** Pre-added brushes that shipped before Quick Brush Panel defaulted to empty */
export const LEGACY_DEFAULT_QUICK_BRUSH_IDS: BrushPresetId[] = [
  'g-pen',
  'real-g-pen',
  'pencil-hb-2b',
  'soft-glaze-airbrush',
  'oil-flat-alla-prima',
  'blend-oil-bristle',
  'blend-velvet-soft',
  'impasto-bristle-oil',
  'dry-bristle-rake',
];

function isLegacyDefaultQuickBrushIds(brushIds: BrushPresetId[]): boolean {
  return (
    brushIds.length === LEGACY_DEFAULT_QUICK_BRUSH_IDS.length &&
    brushIds.every((id, idx) => id === LEGACY_DEFAULT_QUICK_BRUSH_IDS[idx])
  );
}

export function createDefaultQuickBrushPanelState(): QuickBrushPanelState {
  return {
    visible: true,
    orientation: 'vertical',
    position: null,
    locked: false,
    keepVisibleWhenPalettesHidden: true,
    tileSize: 'medium',
    columns: 1,
    previewStyle: 'tip',
    showNames: true,
    showTitle: true,
    title: 'Favorites',
    showCategoryColors: true,
    opacity: 0.95,
    showHideUiButton: false,
    brushIds: [...DEFAULT_QUICK_BRUSH_IDS],
  };
}

export const FLOATING_MIN_X = 8;
export const FLOATING_MIN_Y = 38;
export const FLOATING_MAX_WIDTH = 720;
export const FLOATING_MAX_HEIGHT = 860;

export function getFloatingSizeBounds(panelIds: DockPanelId[]): {
  minWidth: number;
  maxWidth: number;
  minHeight: number;
  maxHeight: number;
} {
  if (panelIds.length === 1 && panelIds[0] === 'tools') {
    return {
      minWidth: 56,
      maxWidth: 220,
      minHeight: DOCK_PANEL_META.tools.minFloatHeight,
      maxHeight: FLOATING_MAX_HEIGHT,
    };
  }
  const isSlimSwatchOnly =
    panelIds.length > 0 && panelIds.every((pid) => pid === 'color-history' || pid === 'color-sets');
  let minWidth = isSlimSwatchOnly ? 72 : 176;
  let minHeight = isSlimSwatchOnly ? 130 : 140;
  for (const pid of panelIds) {
    const meta = DOCK_PANEL_META[pid];
    if (!meta) continue;
    if (pid !== 'tools' && meta.minWidth > minWidth) minWidth = meta.minWidth;
    if (meta.minFloatHeight > minHeight) minHeight = meta.minFloatHeight;
  }
  return {
    minWidth,
    maxWidth: FLOATING_MAX_WIDTH,
    minHeight,
    maxHeight: FLOATING_MAX_HEIGHT,
  };
}

export function clampFloatingRect(
  x: number,
  y: number,
  width: number,
  height: number,
  panelIds: DockPanelId[],
  viewport?: { width: number; height: number }
): { x: number; y: number; width: number; height: number } {
  const bounds = getFloatingSizeBounds(panelIds);
  const vw = viewport?.width ?? (typeof window !== 'undefined' ? window.innerWidth : 1280);
  const vh = viewport?.height ?? (typeof window !== 'undefined' ? window.innerHeight : 800);

  const clampedW = Math.max(
    bounds.minWidth,
    Math.min(bounds.maxWidth, Math.min(Math.max(bounds.minWidth, vw - 16), Math.round(width)))
  );
  const clampedH = Math.max(
    bounds.minHeight,
    Math.min(
      bounds.maxHeight,
      Math.min(Math.max(bounds.minHeight, vh - FLOATING_MIN_Y - 12), Math.round(height))
    )
  );
  const maxX = Math.max(FLOATING_MIN_X, vw - Math.min(clampedW, 120));
  const maxY = Math.max(FLOATING_MIN_Y, vh - 36);
  const clampedX = Math.max(FLOATING_MIN_X, Math.min(maxX, Math.round(x)));
  const clampedY = Math.max(FLOATING_MIN_Y, Math.min(maxY, Math.round(y)));

  return { x: clampedX, y: clampedY, width: clampedW, height: clampedH };
}

function normalizeFloatingZIndices(panels: FloatingPanelState[]): FloatingPanelState[] {
  if (panels.length === 0) return [];
  const order = panels
    .map((p, idx) => ({ id: p.id, z: p.zIndex, idx }))
    .sort((a, b) => (a.z !== b.z ? a.z - b.z : a.idx - b.idx));
  const zMap = new Map<string, number>();
  order.forEach((item, rank) => {
    zMap.set(item.id, rank + 1);
  });
  return panels.map((p) => ({
    ...p,
    zIndex: zMap.get(p.id) ?? 1,
  }));
}

export function getGroupCells(group: DockGroup): DockSplitCell[] {
  if (Array.isArray(group?.splitCells) && group.splitCells.length > 1) {
    return group.splitCells;
  }
  return [
    {
      id: group?.id ?? 'group',
      panelIds: Array.isArray(group?.panelIds) ? group.panelIds : [],
      activePanelId: group?.activePanelId,
      widthRatio: 1,
      collapsed: group?.collapsed,
    },
  ];
}

export function isGroupSplit(group: DockGroup): boolean {
  return Boolean(Array.isArray(group?.splitCells) && group.splitCells.length > 1);
}

function normalizeSplitCells(cells: DockSplitCell[]): DockSplitCell[] {
  if (!Array.isArray(cells)) return [];
  const nonEmpty = cells
    .filter((c) => c && Array.isArray(c.panelIds) && c.panelIds.length > 0)
    .map((c) => ({
      ...c,
      panelIds: [...c.panelIds],
      activePanelId: c.panelIds.includes(c.activePanelId) ? c.activePanelId : c.panelIds[0],
      widthRatio:
        typeof c.widthRatio === 'number' && Number.isFinite(c.widthRatio) && c.widthRatio > 0
          ? c.widthRatio
          : 1,
    }));
  if (nonEmpty.length === 0) return [];
  const total = nonEmpty.reduce((acc, c) => acc + c.widthRatio, 0) || 1;
  return nonEmpty.map((c) => ({
    ...c,
    widthRatio: Math.max(0.08, c.widthRatio / total),
  }));
}

function syncGroupFromSplitCells(group: DockGroup, rawCells: DockSplitCell[]): DockGroup | null {
  const cells = normalizeSplitCells(rawCells);
  if (cells.length === 0) return null;
  if (cells.length === 1) {
    const only = cells[0];
    const nextGroup: DockGroup = {
      id: only.id || group.id,
      panelIds: [...only.panelIds],
      activePanelId: only.activePanelId,
      heightRatio: group.heightRatio,
    };
    if (group.collapsed || only.collapsed) {
      nextGroup.collapsed = Boolean(group.collapsed ?? only.collapsed);
    }
    return nextGroup;
  }
  const allPids = cells.flatMap((c) => c.panelIds);
  const nextGroup: DockGroup = {
    id: group.id,
    panelIds: allPids,
    activePanelId: cells[0].activePanelId,
    heightRatio: group.heightRatio,
    splitCells: cells,
  };
  if (group.collapsed !== undefined) {
    nextGroup.collapsed = group.collapsed;
  }
  return nextGroup;
}

function cloneGroup(g: DockGroup): DockGroup {
  const copy: DockGroup = {
    ...g,
    panelIds: [...g.panelIds],
  };
  if (g.splitCells && g.splitCells.length > 1) {
    copy.splitCells = g.splitCells.map((c) => ({
      ...c,
      panelIds: [...c.panelIds],
    }));
  } else {
    delete copy.splitCells;
  }
  return copy;
}

function cloneBottomDock(bottomDock?: DockBottomZone): DockBottomZone | undefined {
  if (!bottomDock || bottomDock.cells.length === 0) return undefined;
  return {
    height: Math.max(
      BOTTOM_DOCK_MIN_HEIGHT,
      Math.min(BOTTOM_DOCK_MAX_HEIGHT, Math.round(bottomDock.height))
    ),
    collapsed: Boolean(bottomDock.collapsed),
    cells: bottomDock.cells.map((c) => ({
      ...c,
      panelIds: [...c.panelIds],
    })),
  };
}

function withOptionalBottomDock(
  base: {
    leftDocks: DockColumn[];
    rightDocks: DockColumn[];
    floatingPanels?: FloatingPanelState[];
  },
  bottomDock?: DockBottomZone
): WorkspaceLayout {
  if (bottomDock && bottomDock.cells.length > 0) {
    return { ...base, bottomDock };
  }
  return base;
}

export function cloneLayout(layout: WorkspaceLayout): WorkspaceLayout {
  return withOptionalBottomDock(
    {
      leftDocks: layout.leftDocks.map((col) => ({
        ...col,
        groups: col.groups.map(cloneGroup),
      })),
      rightDocks: layout.rightDocks.map((col) => ({
        ...col,
        groups: col.groups.map(cloneGroup),
      })),
      floatingPanels: (layout.floatingPanels ?? []).map((fp) => ({
        ...fp,
        panelIds: [...fp.panelIds],
        lastDock: fp.lastDock ? { ...fp.lastDock } : undefined,
      })),
    },
    cloneBottomDock(layout.bottomDock)
  );
}

export function getPresetLayout(preset: BuiltInWorkspacePresetId): WorkspaceLayout {
  switch (preset) {
    case 'photoshop-studio':
      return cloneLayout(PHOTOSHOP_STUDIO_LAYOUT);
    case 'clip-studio':
      return cloneLayout(CLIP_STUDIO_LAYOUT);
    case 'manga-studio':
      return cloneLayout(MANGA_STUDIO_LAYOUT);
    case 'minimalist-tablet':
      return cloneLayout(MINIMALIST_TABLET_LAYOUT);
    case 'default-illustration':
    default:
      return cloneLayout(DEFAULT_ILLUSTRATION_LAYOUT);
  }
}

export function getPresetDefaultToolOptionsBar(preset: BuiltInWorkspacePresetId): boolean {
  return preset === 'photoshop-studio';
}

function mirrorColumnSplitRows(col: DockColumn): DockColumn {
  return {
    ...col,
    groups: col.groups.map((g) => {
      if (!g.splitCells || g.splitCells.length <= 1) return g;
      const reversed = [...g.splitCells].reverse();
      return {
        ...g,
        panelIds: reversed.flatMap((c) => c.panelIds),
        activePanelId: reversed[0].activePanelId,
        splitCells: reversed,
      };
    }),
  };
}

/**
 * Pure, strictly reversible horizontal mirror of a WorkspaceLayout for left-handed pen-display ergonomics.
 * Swaps `leftDocks` <-> `rightDocks` while reversing column order AND side-by-side split cell order so the
 * outermost narrow `tools` rail cleanly moves to the far right outer edge, while stacked/split palettes dock
 * mirrored on the opposite side. Preserves `bottomDock` and flips `floatingPanels[].lastDock.side` (`left` <-> `right`).
 */
export function mirrorWorkspaceLayout(layout: WorkspaceLayout): WorkspaceLayout {
  const cloned = cloneLayout(layout);
  return withOptionalBottomDock(
    {
      leftDocks: cloned.rightDocks.reverse().map(mirrorColumnSplitRows),
      rightDocks: cloned.leftDocks.reverse().map(mirrorColumnSplitRows),
      floatingPanels: (cloned.floatingPanels ?? []).map((fp) => ({
        ...fp,
        lastDock: fp.lastDock
          ? {
              ...fp.lastDock,
              side:
                fp.lastDock.side === 'left'
                  ? 'right'
                  : fp.lastDock.side === 'right'
                    ? 'left'
                    : 'bottom',
            }
          : undefined,
      })),
    },
    cloned.bottomDock
  );
}

export function listVisiblePanelIds(layout: WorkspaceLayout): Set<DockPanelId> {
  const out = new Set<DockPanelId>();
  for (const col of [...layout.leftDocks, ...layout.rightDocks]) {
    for (const grp of col.groups) {
      for (const cell of getGroupCells(grp)) {
        for (const pid of cell.panelIds) {
          out.add(pid);
        }
      }
    }
  }
  for (const cell of layout.bottomDock?.cells ?? []) {
    for (const pid of cell.panelIds) {
      out.add(pid);
    }
  }
  for (const fp of layout.floatingPanels ?? []) {
    for (const pid of fp.panelIds) {
      out.add(pid);
    }
  }
  return out;
}

export interface PanelLocation {
  side: DockSide;
  colId: string;
  groupId: string;
  cellId?: string;
}

export function findPanelLocation(
  layout: WorkspaceLayout,
  panelId: DockPanelId
): PanelLocation | null {
  for (const side of ['left', 'right'] as const) {
    const cols = side === 'left' ? layout.leftDocks : layout.rightDocks;
    for (const col of cols) {
      for (const grp of col.groups) {
        if (grp.splitCells && grp.splitCells.length > 1) {
          for (const cell of grp.splitCells) {
            if (cell.panelIds.includes(panelId)) {
              return { side, colId: col.id, groupId: grp.id, cellId: cell.id };
            }
          }
        } else if (grp.panelIds.includes(panelId)) {
          return { side, colId: col.id, groupId: grp.id };
        }
      }
    }
  }
  if (layout.bottomDock) {
    for (const cell of layout.bottomDock.cells) {
      if (cell.panelIds.includes(panelId)) {
        return {
          side: 'bottom',
          colId: BOTTOM_DOCK_COL_ID,
          groupId: cell.id,
          cellId: cell.id,
        };
      }
    }
  }
  return null;
}

export function findFloatingPanelLocation(
  layout: WorkspaceLayout,
  panelId: DockPanelId
): { floatingId: string } | null {
  for (const fp of layout.floatingPanels ?? []) {
    if (fp.panelIds.includes(panelId)) {
      return { floatingId: fp.id };
    }
  }
  return null;
}

function pruneEmptyContainers(columns: DockColumn[]): DockColumn[] {
  return columns
    .map((col) => {
      const nonEmptyGroups: DockGroup[] = [];
      for (const g of col.groups) {
        if (g.splitCells && g.splitCells.length > 0) {
          const synced = syncGroupFromSplitCells(g, g.splitCells);
          if (synced) nonEmptyGroups.push(synced);
        } else if (g.panelIds.length > 0) {
          const nextGrp: DockGroup = {
            ...g,
            activePanelId: g.panelIds.includes(g.activePanelId) ? g.activePanelId : g.panelIds[0],
          };
          delete nextGrp.splitCells;
          nonEmptyGroups.push(nextGrp);
        }
      }
      if (nonEmptyGroups.length === 0) return null;
      const totalRatio = nonEmptyGroups.reduce((acc, g) => acc + (g.heightRatio || 1), 0) || 1;
      return {
        ...col,
        groups: nonEmptyGroups.map((g) => ({
          ...g,
          heightRatio: Math.max(0.1, (g.heightRatio || 1) / totalRatio),
        })),
      };
    })
    .filter((c): c is DockColumn => c !== null);
}

function pruneBottomDock(bottomDock?: DockBottomZone): DockBottomZone | undefined {
  if (!bottomDock) return undefined;
  const cells = normalizeSplitCells(bottomDock.cells);
  if (cells.length === 0) return undefined;
  return {
    height: Math.max(
      BOTTOM_DOCK_MIN_HEIGHT,
      Math.min(BOTTOM_DOCK_MAX_HEIGHT, Math.round(bottomDock.height || BOTTOM_DOCK_DEFAULT_HEIGHT))
    ),
    collapsed: Boolean(bottomDock.collapsed),
    cells,
  };
}

function pruneEmptyFloatingPanels(panels: FloatingPanelState[]): FloatingPanelState[] {
  const nonEmpty = panels
    .map((fp) => {
      if (fp.panelIds.length === 0) return null;
      return {
        ...fp,
        activePanelId: fp.panelIds.includes(fp.activePanelId) ? fp.activePanelId : fp.panelIds[0],
      };
    })
    .filter((fp): fp is FloatingPanelState => fp !== null);
  return normalizeFloatingZIndices(nonEmpty);
}

export function removePanelFromLayout(
  layout: WorkspaceLayout,
  panelId: DockPanelId
): WorkspaceLayout {
  const stripCols = (cols: DockColumn[]) =>
    pruneEmptyContainers(
      cols.map((col) => ({
        ...col,
        groups: col.groups.map((g) => {
          if (g.splitCells && g.splitCells.length > 1) {
            return {
              ...g,
              panelIds: g.panelIds.filter((id) => id !== panelId),
              splitCells: g.splitCells.map((c) => ({
                ...c,
                panelIds: c.panelIds.filter((id) => id !== panelId),
              })),
            };
          }
          return {
            ...g,
            panelIds: g.panelIds.filter((id) => id !== panelId),
          };
        }),
      }))
    );

  const nextBottom = layout.bottomDock
    ? pruneBottomDock({
        ...layout.bottomDock,
        cells: layout.bottomDock.cells.map((c) => ({
          ...c,
          panelIds: c.panelIds.filter((id) => id !== panelId),
        })),
      })
    : undefined;

  const nextFloating = pruneEmptyFloatingPanels(
    (layout.floatingPanels ?? []).map((fp) => ({
      ...fp,
      panelIds: fp.panelIds.filter((id) => id !== panelId),
    }))
  );

  return withOptionalBottomDock(
    {
      leftDocks: stripCols(layout.leftDocks),
      rightDocks: stripCols(layout.rightDocks),
      floatingPanels: nextFloating,
    },
    nextBottom
  );
}

let uidSeq = 1;
function makeUid(prefix: string): string {
  uidSeq += 1;
  return `${prefix}-${Date.now().toString(36)}-${uidSeq}`;
}

export interface MovePanelTarget {
  side: DockSide;
  /** Target existing column id, or omit to create a new column on `side` (or dock into bottom dock) */
  targetColId?: string;
  /** Target existing group/row id to merge as a tab (or split horizontally within) */
  targetGroupId?: string;
  /** Target specific cell id inside a side-by-side split row or bottom dock */
  targetCellId?: string;
  /** Insert as a new vertical group at index inside `targetColId` */
  insertGroupIndex?: number;
  /** Insert as a brand new dock column at index on `side` */
  insertColumnIndex?: number;
  /**
   * Split horizontally side-by-side relative to `targetGroupId` / `targetCellId` at equal height!
   * Works inside left/right dock columns (2, 3, or more cells per row) and inside `bottomDock`.
   */
  splitHorizontal?: 'left' | 'right';
}

function getSourceCellPanelCount(layout: WorkspaceLayout, loc: PanelLocation): number {
  if (loc.side === 'bottom') {
    const cell = layout.bottomDock?.cells.find((c) => c.id === (loc.cellId ?? loc.groupId));
    return cell?.panelIds.length ?? 0;
  }
  const cols = loc.side === 'left' ? layout.leftDocks : layout.rightDocks;
  const col = cols.find((c) => c.id === loc.colId);
  const grp = col?.groups.find((g) => g.id === loc.groupId);
  if (!grp) return 0;
  if (grp.splitCells && grp.splitCells.length > 1) {
    const cell = grp.splitCells.find((c) => c.id === loc.cellId);
    return cell?.panelIds.length ?? 0;
  }
  return grp.panelIds.length;
}

export function movePanelInLayout(
  layout: WorkspaceLayout,
  panelId: DockPanelId,
  target: MovePanelTarget
): WorkspaceLayout {
  const current = findPanelLocation(layout, panelId);

  // No-op if dropping onto the exact same cell as a tab
  if (
    current &&
    !target.splitHorizontal &&
    current.side === target.side &&
    current.colId === target.targetColId &&
    current.groupId === target.targetGroupId &&
    (!target.targetCellId || (current.cellId ?? current.groupId) === target.targetCellId)
  ) {
    return setGroupActivePanelInLayout(
      layout,
      current.colId,
      current.groupId,
      panelId,
      current.cellId
    );
  }

  // No-op if trying to split a sole single-tab cell against itself
  if (
    current &&
    target.splitHorizontal &&
    current.side === target.side &&
    current.colId === target.targetColId &&
    current.groupId === target.targetGroupId &&
    (!target.targetCellId || (current.cellId ?? current.groupId) === target.targetCellId) &&
    getSourceCellPanelCount(layout, current) <= 1
  ) {
    return layout;
  }

  const cleaned = removePanelFromLayout(layout, panelId);
  const next = cloneLayout(cleaned);
  const meta = DOCK_PANEL_META[panelId];

  // 0. Bottom Dock target (`side === 'bottom'`)
  if (target.side === 'bottom') {
    const existingBottom = next.bottomDock ?? {
      height: BOTTOM_DOCK_DEFAULT_HEIGHT,
      collapsed: false,
      cells: [],
    };
    const cells = existingBottom.cells.map((c) => ({ ...c, panelIds: [...c.panelIds] }));
    const anchorCellId = target.targetCellId ?? target.targetGroupId;

    if (anchorCellId && !target.splitHorizontal) {
      const targetCell = cells.find((c) => c.id === anchorCellId);
      if (targetCell) {
        if (!targetCell.panelIds.includes(panelId)) {
          targetCell.panelIds.push(panelId);
        }
        targetCell.activePanelId = panelId;
        targetCell.collapsed = false;
        next.bottomDock = pruneBottomDock({
          ...existingBottom,
          collapsed: false,
          cells,
        });
        return next;
      }
    }

    const newCell: DockSplitCell = {
      id: makeUid('bcell'),
      panelIds: [panelId],
      activePanelId: panelId,
      widthRatio: 1 / (cells.length + 1),
    };

    const existingCount = cells.length;
    const scale = existingCount > 0 ? existingCount / (existingCount + 1) : 1;
    const scaled = cells.map((c) => ({ ...c, widthRatio: c.widthRatio * scale }));

    if (anchorCellId && target.splitHorizontal) {
      const idx = scaled.findIndex((c) => c.id === anchorCellId);
      if (idx >= 0) {
        const insertAt = target.splitHorizontal === 'left' ? idx : idx + 1;
        scaled.splice(insertAt, 0, newCell);
      } else {
        scaled.push(newCell);
      }
    } else {
      scaled.push(newCell);
    }

    next.bottomDock = pruneBottomDock({
      ...existingBottom,
      collapsed: false,
      cells: scaled,
    });
    return next;
  }

  const targetCols = target.side === 'left' ? next.leftDocks : next.rightDocks;

  // 1a. Split horizontally side-by-side inside an existing dock group/row (2, 3, or more equal-height cells!)
  if (target.targetColId && target.targetGroupId && target.splitHorizontal) {
    const col = targetCols.find((c) => c.id === target.targetColId);
    const grpIdx = col ? col.groups.findIndex((g) => g.id === target.targetGroupId) : -1;
    if (col && grpIdx >= 0) {
      const grp = col.groups[grpIdx];
      const existingCells = getGroupCells(grp).map((c) => ({
        ...c,
        panelIds: [...c.panelIds],
      }));
      const existingCount = existingCells.length;
      const scale = existingCount / (existingCount + 1);
      const scaledCells = existingCells.map((c) => ({
        ...c,
        widthRatio: c.widthRatio * scale,
      }));
      const newCell: DockSplitCell = {
        id: makeUid('cell'),
        panelIds: [panelId],
        activePanelId: panelId,
        widthRatio: 1 / (existingCount + 1),
      };

      const anchorId = target.targetCellId ?? grp.id;
      const anchorIdx = scaledCells.findIndex((c) => c.id === anchorId);
      const insertAt =
        anchorIdx >= 0
          ? target.splitHorizontal === 'left'
            ? anchorIdx
            : anchorIdx + 1
          : target.splitHorizontal === 'left'
            ? 0
            : scaledCells.length;
      scaledCells.splice(insertAt, 0, newCell);

      const synced = syncGroupFromSplitCells({ ...grp, collapsed: false }, scaledCells);
      if (synced) {
        col.groups[grpIdx] = synced;
        const { min, max } = getColumnWidthBounds(col);
        const comfortableWidth = Math.min(max, Math.max(min, scaledCells.length * 184));
        if (col.width < comfortableWidth) {
          col.width = Math.round(comfortableWidth);
        }
        return next;
      }
    }
  }

  // 1b. Merge into an existing group or split cell as a tab
  if (target.targetColId && target.targetGroupId) {
    const col = targetCols.find((c) => c.id === target.targetColId);
    const grpIdx = col ? col.groups.findIndex((g) => g.id === target.targetGroupId) : -1;
    if (col && grpIdx >= 0) {
      const grp = col.groups[grpIdx];
      if (Array.isArray(grp.splitCells) && grp.splitCells.length > 1) {
        const targetCell =
          (target.targetCellId
            ? grp.splitCells.find((c) => c.id === target.targetCellId)
            : undefined) ?? grp.splitCells[0];
        if (targetCell) {
          if (!Array.isArray(targetCell.panelIds)) targetCell.panelIds = [];
          if (!targetCell.panelIds.includes(panelId)) {
            targetCell.panelIds.push(panelId);
          }
          targetCell.activePanelId = panelId;
          targetCell.collapsed = false;
        }
        grp.collapsed = false;
        grp.panelIds = grp.splitCells.flatMap((c) => (Array.isArray(c.panelIds) ? c.panelIds : []));
      } else {
        if (!grp.panelIds.includes(panelId)) {
          grp.panelIds.push(panelId);
        }
        grp.activePanelId = panelId;
        grp.collapsed = false;
      }
      // If column was super narrow (e.g. tools 46px) and a regular palette joined it, expand width cleanly
      const { min } = getColumnWidthBounds(col);
      if (col.width < Math.max(meta.minWidth, min)) {
        col.width = Math.max(meta.defaultWidth, min);
      }
      return next;
    }
  }

  // 2. Insert as a new stacked group inside an existing column
  if (target.targetColId) {
    const col = targetCols.find((c) => c.id === target.targetColId);
    if (col) {
      const idx =
        target.insertGroupIndex !== undefined
          ? Math.max(0, Math.min(col.groups.length, target.insertGroupIndex))
          : col.groups.length;
      const newRatio = 1 / (col.groups.length + 1);
      const scale = 1 - newRatio;
      col.groups = col.groups.map((g) => ({ ...g, heightRatio: g.heightRatio * scale }));
      col.groups.splice(idx, 0, {
        id: makeUid('grp'),
        panelIds: [panelId],
        activePanelId: panelId,
        heightRatio: newRatio,
      });
      if (col.width < meta.minWidth) {
        col.width = meta.defaultWidth;
      }
      return next;
    }
  }

  // 3. Create a new dock column on `target.side`
  const newCol: DockColumn = {
    id: makeUid(`col-${target.side}`),
    width: meta.defaultWidth,
    collapsed: false,
    groups: [
      {
        id: makeUid('grp'),
        panelIds: [panelId],
        activePanelId: panelId,
        heightRatio: 1,
      },
    ],
  };

  if (target.insertColumnIndex !== undefined) {
    const idx = Math.max(0, Math.min(targetCols.length, target.insertColumnIndex));
    targetCols.splice(idx, 0, newCol);
  } else if (target.side === 'left') {
    targetCols.push(newCol);
  } else {
    targetCols.unshift(newCol);
  }

  return next;
}

export function setGroupActivePanelInLayout(
  layout: WorkspaceLayout,
  colId: string,
  groupId: string,
  panelId: DockPanelId,
  cellId?: string
): WorkspaceLayout {
  if (colId === BOTTOM_DOCK_COL_ID && layout.bottomDock) {
    const targetId = cellId ?? groupId;
    const nextBottom: DockBottomZone = {
      ...layout.bottomDock,
      collapsed: false,
      cells: layout.bottomDock.cells.map((c) =>
        c.id !== targetId || !c.panelIds.includes(panelId)
          ? c
          : { ...c, activePanelId: panelId, collapsed: false }
      ),
    };
    return withOptionalBottomDock(
      {
        leftDocks: layout.leftDocks,
        rightDocks: layout.rightDocks,
        floatingPanels: layout.floatingPanels ?? [],
      },
      nextBottom
    );
  }

  const mapCols = (cols: DockColumn[]) =>
    cols.map((col) =>
      col.id !== colId
        ? col
        : {
            ...col,
            groups: col.groups.map((g) => {
              if (g.id !== groupId) return g;
              if (g.splitCells && g.splitCells.length > 1) {
                const nextCells = g.splitCells.map((c) =>
                  (cellId ? c.id === cellId : c.panelIds.includes(panelId)) &&
                  c.panelIds.includes(panelId)
                    ? { ...c, activePanelId: panelId, collapsed: false }
                    : c
                );
                return {
                  ...g,
                  collapsed: false,
                  activePanelId: nextCells[0]?.activePanelId ?? g.activePanelId,
                  splitCells: nextCells,
                };
              }
              if (!g.panelIds.includes(panelId)) return g;
              return { ...g, activePanelId: panelId, collapsed: false };
            }),
          }
    );

  return withOptionalBottomDock(
    {
      leftDocks: mapCols(layout.leftDocks),
      rightDocks: mapCols(layout.rightDocks),
      floatingPanels: layout.floatingPanels ?? [],
    },
    layout.bottomDock
  );
}

export function toggleGroupCollapsedInLayout(
  layout: WorkspaceLayout,
  colId: string,
  groupId: string,
  forceValue?: boolean
): WorkspaceLayout {
  if (colId === BOTTOM_DOCK_COL_ID && layout.bottomDock) {
    return toggleBottomDockCollapsedInLayout(layout, forceValue);
  }

  const mapCols = (cols: DockColumn[]) =>
    cols.map((col) =>
      col.id !== colId
        ? col
        : {
            ...col,
            groups: col.groups.map((g) =>
              g.id !== groupId
                ? g
                : { ...g, collapsed: forceValue !== undefined ? forceValue : !g.collapsed }
            ),
          }
    );

  return withOptionalBottomDock(
    {
      leftDocks: mapCols(layout.leftDocks),
      rightDocks: mapCols(layout.rightDocks),
      floatingPanels: layout.floatingPanels ?? [],
    },
    layout.bottomDock
  );
}

export function toggleColumnCollapsedInLayout(
  layout: WorkspaceLayout,
  colId: string,
  forceValue?: boolean
): WorkspaceLayout {
  const mapCols = (cols: DockColumn[]) =>
    cols.map((col) =>
      col.id !== colId
        ? col
        : { ...col, collapsed: forceValue !== undefined ? forceValue : !col.collapsed }
    );

  return withOptionalBottomDock(
    {
      leftDocks: mapCols(layout.leftDocks),
      rightDocks: mapCols(layout.rightDocks),
      floatingPanels: layout.floatingPanels ?? [],
    },
    layout.bottomDock
  );
}

export function getColumnWidthBounds(col: DockColumn): { min: number; max: number } {
  const panels = col.groups.flatMap((g) => getGroupCells(g).flatMap((c) => c.panelIds));
  const maxCellsInRow = Math.max(1, ...col.groups.map((g) => getGroupCells(g).length));

  if (maxCellsInRow <= 1 && panels.length === 1 && panels[0] === 'tools') {
    return { min: 44, max: 92 };
  }
  const isSlimSwatchOnly =
    maxCellsInRow <= 1 &&
    panels.length > 0 &&
    panels.every((pid) => pid === 'color-history' || pid === 'color-sets');
  let min = isSlimSwatchOnly ? 72 : 136;
  let max = 380;
  for (const pid of panels) {
    const meta = DOCK_PANEL_META[pid];
    if (meta) {
      if (meta.minWidth > min && pid !== 'tools') min = meta.minWidth;
      if (meta.maxWidth > max) max = meta.maxWidth;
    }
  }
  if (maxCellsInRow > 1) {
    const splitMin = Math.min(540, maxCellsInRow * 124);
    const splitMax = Math.min(1040, Math.max(max, maxCellsInRow * 340));
    return { min: Math.max(min, splitMin), max: splitMax };
  }
  return { min, max };
}

export function resizeColumnInLayout(
  layout: WorkspaceLayout,
  colId: string,
  requestedWidth: number
): WorkspaceLayout {
  let changed = false;
  const mapCols = (cols: DockColumn[]) =>
    cols.map((col) => {
      if (col.id !== colId) return col;
      const { min, max } = getColumnWidthBounds(col);
      const clamped = Math.max(min, Math.min(max, Math.round(requestedWidth)));
      if (clamped === col.width) return col;
      changed = true;
      return { ...col, width: clamped };
    });

  const leftDocks = mapCols(layout.leftDocks);
  const rightDocks = mapCols(layout.rightDocks);
  if (!changed) return layout;

  return withOptionalBottomDock(
    {
      leftDocks,
      rightDocks,
      floatingPanels: layout.floatingPanels ?? [],
    },
    layout.bottomDock
  );
}

export function resizeGroupSplitInLayout(
  layout: WorkspaceLayout,
  colId: string,
  topGroupId: string,
  bottomGroupId: string,
  nextTopRatio: number,
  nextBottomRatio: number
): WorkspaceLayout {
  const mapCols = (cols: DockColumn[]) =>
    cols.map((col) => {
      if (col.id !== colId) return col;
      return {
        ...col,
        groups: col.groups.map((g) => {
          if (g.id === topGroupId) return { ...g, heightRatio: Math.max(0.1, nextTopRatio) };
          if (g.id === bottomGroupId) return { ...g, heightRatio: Math.max(0.1, nextBottomRatio) };
          return g;
        }),
      };
    });

  return withOptionalBottomDock(
    {
      leftDocks: mapCols(layout.leftDocks),
      rightDocks: mapCols(layout.rightDocks),
      floatingPanels: layout.floatingPanels ?? [],
    },
    layout.bottomDock
  );
}

/**
 * Resizes the horizontal width ratio between two adjacent side-by-side cells inside a split row
 * (either in a left/right dock column OR inside the bottom dock).
 */
export function resizeCellSplitInLayout(
  layout: WorkspaceLayout,
  colId: string,
  rowId: string,
  leftCellId: string,
  rightCellId: string,
  nextLeftRatio: number,
  nextRightRatio: number
): WorkspaceLayout {
  const safeLeft = Math.max(0.1, nextLeftRatio);
  const safeRight = Math.max(0.1, nextRightRatio);

  if (colId === BOTTOM_DOCK_COL_ID && layout.bottomDock) {
    const nextCells = layout.bottomDock.cells.map((c) => {
      if (c.id === leftCellId) return { ...c, widthRatio: safeLeft };
      if (c.id === rightCellId) return { ...c, widthRatio: safeRight };
      return c;
    });
    return withOptionalBottomDock(
      {
        leftDocks: layout.leftDocks,
        rightDocks: layout.rightDocks,
        floatingPanels: layout.floatingPanels ?? [],
      },
      { ...layout.bottomDock, cells: nextCells }
    );
  }

  const mapCols = (cols: DockColumn[]) =>
    cols.map((col) => {
      if (col.id !== colId) return col;
      return {
        ...col,
        groups: col.groups.map((g) => {
          if (g.id !== rowId || !g.splitCells || g.splitCells.length <= 1) return g;
          return {
            ...g,
            splitCells: g.splitCells.map((c) => {
              if (c.id === leftCellId) return { ...c, widthRatio: safeLeft };
              if (c.id === rightCellId) return { ...c, widthRatio: safeRight };
              return c;
            }),
          };
        }),
      };
    });

  return withOptionalBottomDock(
    {
      leftDocks: mapCols(layout.leftDocks),
      rightDocks: mapCols(layout.rightDocks),
      floatingPanels: layout.floatingPanels ?? [],
    },
    layout.bottomDock
  );
}

export function resizeBottomDockInLayout(
  layout: WorkspaceLayout,
  requestedHeight: number
): WorkspaceLayout {
  if (!layout.bottomDock || layout.bottomDock.cells.length === 0) return layout;
  const clamped = Math.max(
    BOTTOM_DOCK_MIN_HEIGHT,
    Math.min(BOTTOM_DOCK_MAX_HEIGHT, Math.round(requestedHeight))
  );
  if (clamped === layout.bottomDock.height) return layout;
  return withOptionalBottomDock(
    {
      leftDocks: layout.leftDocks,
      rightDocks: layout.rightDocks,
      floatingPanels: layout.floatingPanels ?? [],
    },
    { ...layout.bottomDock, height: clamped }
  );
}

export function toggleBottomDockCollapsedInLayout(
  layout: WorkspaceLayout,
  forceValue?: boolean
): WorkspaceLayout {
  if (!layout.bottomDock || layout.bottomDock.cells.length === 0) return layout;
  const nextCollapsed = forceValue !== undefined ? forceValue : !layout.bottomDock.collapsed;
  if (nextCollapsed === layout.bottomDock.collapsed) return layout;
  return withOptionalBottomDock(
    {
      leftDocks: layout.leftDocks,
      rightDocks: layout.rightDocks,
      floatingPanels: layout.floatingPanels ?? [],
    },
    { ...layout.bottomDock, collapsed: nextCollapsed }
  );
}

export interface DetachPanelOptions {
  x?: number;
  y?: number;
  width?: number;
  height?: number;
  viewport?: { width: number; height: number };
}

export function detachPanelToFloatingInLayout(
  layout: WorkspaceLayout,
  panelId: DockPanelId,
  options?: DetachPanelOptions
): WorkspaceLayout {
  const dockedLoc = findPanelLocation(layout, panelId);
  const existingFloatingLoc = findFloatingPanelLocation(layout, panelId);
  const existingFloating = existingFloatingLoc
    ? (layout.floatingPanels ?? []).find((f) => f.id === existingFloatingLoc.floatingId)
    : undefined;

  const lastDock: FloatingPanelLastDock | undefined = dockedLoc
    ? {
        side: dockedLoc.side,
        colId: dockedLoc.colId,
        groupId: dockedLoc.groupId,
        ...(dockedLoc.cellId ? { cellId: dockedLoc.cellId } : {}),
      }
    : existingFloating?.lastDock
      ? { ...existingFloating.lastDock }
      : { side: DOCK_PANEL_META[panelId].defaultSide };

  const cleaned = removePanelFromLayout(layout, panelId);
  const next = cloneLayout(cleaned);
  const floatingPanels = next.floatingPanels ?? [];
  const meta = DOCK_PANEL_META[panelId];

  const vw = options?.viewport?.width ?? (typeof window !== 'undefined' ? window.innerWidth : 1280);
  const vh = options?.viewport?.height ?? (typeof window !== 'undefined' ? window.innerHeight : 800);

  const cascade = (floatingPanels.length % 6) * 26;
  const reqW = options?.width ?? meta.defaultFloatWidth;
  const reqH = options?.height ?? meta.defaultFloatHeight;
  const defaultX =
    meta.defaultSide === 'left'
      ? Math.round(vw * 0.24) + cascade
      : Math.round(vw * 0.68 - reqW * 0.5) - cascade;
  const defaultY = Math.round(vh * 0.16) + cascade;

  const rect = clampFloatingRect(
    options?.x ?? defaultX,
    options?.y ?? defaultY,
    reqW,
    reqH,
    [panelId],
    options?.viewport
  );

  const maxZ = floatingPanels.reduce((acc, p) => Math.max(acc, p.zIndex), 0);
  const newFloating: FloatingPanelState = {
    id: makeUid('float'),
    panelIds: [panelId],
    activePanelId: panelId,
    x: rect.x,
    y: rect.y,
    width: rect.width,
    height: rect.height,
    collapsed: false,
    zIndex: maxZ + 1,
    lastDock,
  };

  next.floatingPanels = normalizeFloatingZIndices([...floatingPanels, newFloating]);
  return next;
}

export function mergePanelIntoFloatingInLayout(
  layout: WorkspaceLayout,
  panelId: DockPanelId,
  targetFloatingId: string
): WorkspaceLayout {
  const targetExists = (layout.floatingPanels ?? []).some((fp) => fp.id === targetFloatingId);
  if (!targetExists) return layout;

  const existingLoc = findFloatingPanelLocation(layout, panelId);
  if (existingLoc && existingLoc.floatingId === targetFloatingId) {
    return setFloatingActivePanelInLayout(layout, targetFloatingId, panelId);
  }

  const cleaned = removePanelFromLayout(layout, panelId);
  const next = cloneLayout(cleaned);
  const floatingPanels = next.floatingPanels ?? [];
  const target = floatingPanels.find((fp) => fp.id === targetFloatingId);
  if (!target) return layout;

  if (!target.panelIds.includes(panelId)) {
    target.panelIds.push(panelId);
  }
  target.activePanelId = panelId;
  target.collapsed = false;
  const bounds = getFloatingSizeBounds(target.panelIds);
  if (target.width < bounds.minWidth) {
    target.width = Math.max(bounds.minWidth, DOCK_PANEL_META[panelId].defaultFloatWidth);
  }
  if (target.height < bounds.minHeight) {
    target.height = Math.max(bounds.minHeight, DOCK_PANEL_META[panelId].defaultFloatHeight);
  }

  const maxZ = floatingPanels.reduce((acc, p) => Math.max(acc, p.zIndex), 0);
  target.zIndex = maxZ + 1;
  next.floatingPanels = normalizeFloatingZIndices(floatingPanels);
  return next;
}

export function dockFloatingPanelInLayout(
  layout: WorkspaceLayout,
  floatingId: string,
  target?: MovePanelTarget
): WorkspaceLayout {
  const fp = (layout.floatingPanels ?? []).find((f) => f.id === floatingId);
  if (!fp || fp.panelIds.length === 0) return layout;

  const panelsToDock = [...fp.panelIds];
  const preferredActive = fp.panelIds.includes(fp.activePanelId) ? fp.activePanelId : fp.panelIds[0];

  // Resolve target when 1-click reattaching without explicit drop target
  let resolvedTarget: MovePanelTarget;
  if (target) {
    resolvedTarget = target;
  } else {
    const last = fp.lastDock;
    const fallbackSide = last?.side ?? DOCK_PANEL_META[preferredActive].defaultSide;
    if (fallbackSide === 'bottom') {
      const matchedBottomCell = last?.cellId
        ? layout.bottomDock?.cells.find((c) => c.id === last.cellId)
        : undefined;
      resolvedTarget = matchedBottomCell
        ? { side: 'bottom', targetColId: BOTTOM_DOCK_COL_ID, targetCellId: matchedBottomCell.id }
        : { side: 'bottom' };
    } else {
      const sideCols = fallbackSide === 'left' ? layout.leftDocks : layout.rightDocks;
      const matchedCol = last?.colId ? sideCols.find((c) => c.id === last.colId) : undefined;
      const matchedGrp =
        matchedCol && last?.groupId
          ? matchedCol.groups.find((g) => g.id === last.groupId)
          : undefined;

      if (matchedCol && matchedGrp) {
        resolvedTarget = {
          side: fallbackSide,
          targetColId: matchedCol.id,
          targetGroupId: matchedGrp.id,
          ...(last?.cellId ? { targetCellId: last.cellId } : {}),
        };
      } else if (matchedCol) {
        resolvedTarget = {
          side: fallbackSide,
          targetColId: matchedCol.id,
          insertGroupIndex: matchedCol.groups.length,
        };
      } else {
        const preferredCol = sideCols.find(
          (c) =>
            !(
              Array.isArray(c.groups) &&
              c.groups.length === 1 &&
              Array.isArray(c.groups[0]?.panelIds) &&
              c.groups[0].panelIds.length === 1 &&
              c.groups[0].panelIds[0] === 'tools'
            )
        );
        if (preferredCol && preferredActive !== 'tools') {
          resolvedTarget = {
            side: fallbackSide,
            targetColId: preferredCol.id,
            insertGroupIndex: preferredCol.groups.length,
          };
        } else {
          resolvedTarget = {
            side: fallbackSide,
            insertColumnIndex: fallbackSide === 'left' ? 0 : sideCols.length,
          };
        }
      }
    }
  }

  let current = movePanelInLayout(layout, panelsToDock[0], resolvedTarget);
  const anchored = findPanelLocation(current, panelsToDock[0]);

  if (anchored && panelsToDock.length > 1) {
    for (let i = 1; i < panelsToDock.length; i++) {
      current = movePanelInLayout(current, panelsToDock[i], {
        side: anchored.side,
        targetColId: anchored.colId,
        targetGroupId: anchored.groupId,
        ...(anchored.cellId ? { targetCellId: anchored.cellId } : {}),
      });
    }
    current = setGroupActivePanelInLayout(
      current,
      anchored.colId,
      anchored.groupId,
      preferredActive,
      anchored.cellId
    );
  }

  return current;
}

export function moveFloatingPanelInLayout(
  layout: WorkspaceLayout,
  floatingId: string,
  x: number,
  y: number,
  viewport?: { width: number; height: number }
): WorkspaceLayout {
  const existing = layout.floatingPanels ?? [];
  const idx = existing.findIndex((f) => f.id === floatingId);
  if (idx < 0) return layout;

  const fp = existing[idx];
  const clamped = clampFloatingRect(x, y, fp.width, fp.height, fp.panelIds, viewport);
  if (clamped.x === fp.x && clamped.y === fp.y) return layout;

  const nextFloating = existing.map((f) =>
    f.id === floatingId ? { ...f, x: clamped.x, y: clamped.y } : f
  );
  return withOptionalBottomDock(
    {
      leftDocks: layout.leftDocks,
      rightDocks: layout.rightDocks,
      floatingPanels: nextFloating,
    },
    layout.bottomDock
  );
}

export function resizeFloatingPanelInLayout(
  layout: WorkspaceLayout,
  floatingId: string,
  rect: { x?: number; y?: number; width: number; height: number },
  viewport?: { width: number; height: number }
): WorkspaceLayout {
  const existing = layout.floatingPanels ?? [];
  const fp = existing.find((f) => f.id === floatingId);
  if (!fp) return layout;

  const clamped = clampFloatingRect(
    rect.x ?? fp.x,
    rect.y ?? fp.y,
    rect.width,
    rect.height,
    fp.panelIds,
    viewport
  );
  if (
    clamped.x === fp.x &&
    clamped.y === fp.y &&
    clamped.width === fp.width &&
    clamped.height === fp.height
  ) {
    return layout;
  }

  return withOptionalBottomDock(
    {
      leftDocks: layout.leftDocks,
      rightDocks: layout.rightDocks,
      floatingPanels: existing.map((f) => (f.id === floatingId ? { ...f, ...clamped } : f)),
    },
    layout.bottomDock
  );
}

export function toggleFloatingCollapsedInLayout(
  layout: WorkspaceLayout,
  floatingId: string,
  forceValue?: boolean
): WorkspaceLayout {
  const existing = layout.floatingPanels ?? [];
  if (!existing.some((f) => f.id === floatingId)) return layout;
  return withOptionalBottomDock(
    {
      leftDocks: layout.leftDocks,
      rightDocks: layout.rightDocks,
      floatingPanels: existing.map((f) =>
        f.id === floatingId
          ? { ...f, collapsed: forceValue !== undefined ? forceValue : !f.collapsed }
          : f
      ),
    },
    layout.bottomDock
  );
}

export function setFloatingActivePanelInLayout(
  layout: WorkspaceLayout,
  floatingId: string,
  panelId: DockPanelId
): WorkspaceLayout {
  const existing = layout.floatingPanels ?? [];
  const target = existing.find((f) => f.id === floatingId);
  if (!target || !target.panelIds.includes(panelId)) return layout;
  const maxZ = existing.reduce((acc, p) => Math.max(acc, p.zIndex), 0);
  const nextFloating = normalizeFloatingZIndices(
    existing.map((f) =>
      f.id === floatingId
        ? { ...f, activePanelId: panelId, collapsed: false, zIndex: maxZ + 1 }
        : f
    )
  );
  return withOptionalBottomDock(
    {
      leftDocks: layout.leftDocks,
      rightDocks: layout.rightDocks,
      floatingPanels: nextFloating,
    },
    layout.bottomDock
  );
}

export function bringFloatingPanelToFrontInLayout(
  layout: WorkspaceLayout,
  floatingId: string
): WorkspaceLayout {
  const existing = layout.floatingPanels ?? [];
  const target = existing.find((f) => f.id === floatingId);
  if (!target) return layout;
  const maxZ = existing.reduce((acc, p) => Math.max(acc, p.zIndex), 0);
  if (target.zIndex === maxZ && existing.filter((p) => p.zIndex === maxZ).length === 1) {
    return layout;
  }
  return withOptionalBottomDock(
    {
      leftDocks: layout.leftDocks,
      rightDocks: layout.rightDocks,
      floatingPanels: normalizeFloatingZIndices(
        existing.map((f) => (f.id === floatingId ? { ...f, zIndex: maxZ + 1 } : f))
      ),
    },
    layout.bottomDock
  );
}

export function closeFloatingPanelInLayout(
  layout: WorkspaceLayout,
  floatingId: string
): WorkspaceLayout {
  const existing = layout.floatingPanels ?? [];
  if (!existing.some((f) => f.id === floatingId)) return layout;
  return withOptionalBottomDock(
    {
      leftDocks: layout.leftDocks,
      rightDocks: layout.rightDocks,
      floatingPanels: normalizeFloatingZIndices(existing.filter((f) => f.id !== floatingId)),
    },
    layout.bottomDock
  );
}

export function togglePanelInLayout(
  layout: WorkspaceLayout,
  panelId: DockPanelId,
  leftHandedMode = false
): WorkspaceLayout {
  const existingDocked = findPanelLocation(layout, panelId);
  const existingFloating = findFloatingPanelLocation(layout, panelId);
  if (existingDocked || existingFloating) {
    return removePanelFromLayout(layout, panelId);
  }
  const meta = DOCK_PANEL_META[panelId];
  const targetSide: DockSide =
    meta.defaultSide === 'bottom'
      ? 'bottom'
      : leftHandedMode
        ? meta.defaultSide === 'left'
          ? 'right'
          : 'left'
        : meta.defaultSide;
  if (targetSide === 'bottom') {
    return movePanelInLayout(layout, panelId, { side: 'bottom' });
  }
  const targetCols = targetSide === 'left' ? layout.leftDocks : layout.rightDocks;
  const preferredCol = targetCols.find(
    (c) =>
      !(
        Array.isArray(c.groups) &&
        c.groups.length === 1 &&
        Array.isArray(c.groups[0]?.panelIds) &&
        c.groups[0].panelIds.length === 1 &&
        c.groups[0].panelIds[0] === 'tools'
      )
  );
  if (preferredCol && panelId !== 'tools') {
    return movePanelInLayout(layout, panelId, {
      side: targetSide,
      targetColId: preferredCol.id,
      insertGroupIndex: preferredCol.groups.length,
    });
  }
  return movePanelInLayout(layout, panelId, {
    side: targetSide,
    insertColumnIndex: targetSide === 'left' ? 0 : targetCols.length,
  });
}

function sanitizeSplitCellsList(
  rawCells: unknown,
  seenPanels: Set<DockPanelId>,
  idPrefix: string
): DockSplitCell[] {
  if (!Array.isArray(rawCells)) return [];
  const cells: DockSplitCell[] = [];
  for (const cItem of rawCells) {
    if (!cItem || typeof cItem !== 'object') continue;
    const cRec = cItem as Record<string, unknown>;
    const rawPids = Array.isArray(cRec.panelIds) ? cRec.panelIds : [];
    const panelIds: DockPanelId[] = [];
    for (const pid of rawPids) {
      if (typeof pid === 'string' && VALID_PANEL_SET.has(pid)) {
        const typedPid = pid as DockPanelId;
        if (!seenPanels.has(typedPid)) {
          seenPanels.add(typedPid);
          panelIds.push(typedPid);
        }
      }
    }
    if (panelIds.length === 0) continue;
    const activePanelId =
      typeof cRec.activePanelId === 'string' && panelIds.includes(cRec.activePanelId as DockPanelId)
        ? (cRec.activePanelId as DockPanelId)
        : panelIds[0];
    const widthRatio =
      typeof cRec.widthRatio === 'number' && Number.isFinite(cRec.widthRatio) && cRec.widthRatio > 0
        ? cRec.widthRatio
        : 1;
    const cell: DockSplitCell = {
      id: typeof cRec.id === 'string' && cRec.id.trim() ? cRec.id : makeUid(idPrefix),
      panelIds,
      activePanelId,
      widthRatio,
    };
    if (cRec.collapsed) cell.collapsed = true;
    cells.push(cell);
  }
  return normalizeSplitCells(cells);
}

function sanitizeColumns(raw: unknown, seenPanels: Set<DockPanelId>): DockColumn[] {
  if (!Array.isArray(raw)) return [];
  const result: DockColumn[] = [];
  for (const item of raw) {
    if (!item || typeof item !== 'object') continue;
    const rec = item as Record<string, unknown>;
    const colId = typeof rec.id === 'string' && rec.id.trim() ? rec.id : makeUid('col');
    const collapsed = Boolean(rec.collapsed);
    // Support both canonical `groups` (legacy + splitCells) and optional `rows` schema cleanly
    const rawGroups = Array.isArray(rec.groups)
      ? rec.groups
      : Array.isArray(rec.rows)
        ? rec.rows
        : [];
    const groups: DockGroup[] = [];
    for (const gItem of rawGroups) {
      if (!gItem || typeof gItem !== 'object') continue;
      const gRec = gItem as Record<string, unknown>;
      const heightRatio =
        typeof gRec.heightRatio === 'number' && Number.isFinite(gRec.heightRatio) && gRec.heightRatio > 0
          ? gRec.heightRatio
          : 1;
      const grpId = typeof gRec.id === 'string' && gRec.id.trim() ? gRec.id : makeUid('grp');
      const rawCells = Array.isArray(gRec.splitCells)
        ? gRec.splitCells
        : Array.isArray(gRec.cells)
          ? gRec.cells
          : null;

      if (rawCells && rawCells.length > 0) {
        const sanitizedCells = sanitizeSplitCellsList(rawCells, seenPanels, 'cell');
        const synced = syncGroupFromSplitCells(
          {
            id: grpId,
            panelIds: [],
            activePanelId: 'tools',
            heightRatio,
            collapsed: Boolean(gRec.collapsed),
          },
          sanitizedCells
        );
        if (synced) groups.push(synced);
        continue;
      }

      const rawPids = Array.isArray(gRec.panelIds) ? gRec.panelIds : [];
      const panelIds: DockPanelId[] = [];
      for (const pid of rawPids) {
        if (typeof pid === 'string' && VALID_PANEL_SET.has(pid)) {
          const typedPid = pid as DockPanelId;
          if (!seenPanels.has(typedPid)) {
            seenPanels.add(typedPid);
            panelIds.push(typedPid);
          }
        }
      }
      if (panelIds.length === 0) continue;
      const activePanelId =
        typeof gRec.activePanelId === 'string' && panelIds.includes(gRec.activePanelId as DockPanelId)
          ? (gRec.activePanelId as DockPanelId)
          : panelIds[0];
      groups.push({
        id: grpId,
        panelIds,
        activePanelId,
        heightRatio,
        collapsed: Boolean(gRec.collapsed),
      });
    }
    if (groups.length === 0) continue;
    const tentativeCol: DockColumn = { id: colId, width: 200, collapsed, groups };
    const { min, max } = getColumnWidthBounds(tentativeCol);
    const width =
      typeof rec.width === 'number' && Number.isFinite(rec.width)
        ? Math.max(min, Math.min(max, Math.round(rec.width)))
        : Math.max(min, Math.min(max, 200));
    result.push({ ...tentativeCol, width });
  }
  return pruneEmptyContainers(result);
}

function sanitizeBottomDock(
  raw: unknown,
  seenPanels: Set<DockPanelId>
): DockBottomZone | undefined {
  if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return undefined;
  const rec = raw as Record<string, unknown>;
  const rawCells = Array.isArray(rec.cells)
    ? rec.cells
    : Array.isArray(rec.groups)
      ? rec.groups
      : [];
  const cells = sanitizeSplitCellsList(rawCells, seenPanels, 'bcell');
  if (cells.length === 0) return undefined;
  const height =
    typeof rec.height === 'number' && Number.isFinite(rec.height)
      ? Math.max(BOTTOM_DOCK_MIN_HEIGHT, Math.min(BOTTOM_DOCK_MAX_HEIGHT, Math.round(rec.height)))
      : BOTTOM_DOCK_DEFAULT_HEIGHT;
  return {
    height,
    collapsed: Boolean(rec.collapsed),
    cells,
  };
}

function sanitizeFloatingPanels(raw: unknown, seenPanels: Set<DockPanelId>): FloatingPanelState[] {
  if (!Array.isArray(raw)) return [];
  const result: FloatingPanelState[] = [];
  for (const item of raw) {
    if (!item || typeof item !== 'object') continue;
    const rec = item as Record<string, unknown>;
    const rawPids = Array.isArray(rec.panelIds) ? rec.panelIds : [];
    const panelIds: DockPanelId[] = [];
    for (const pid of rawPids) {
      if (typeof pid === 'string' && VALID_PANEL_SET.has(pid)) {
        const typedPid = pid as DockPanelId;
        if (!seenPanels.has(typedPid)) {
          seenPanels.add(typedPid);
          panelIds.push(typedPid);
        }
      }
    }
    if (panelIds.length === 0) continue;
    const activePanelId =
      typeof rec.activePanelId === 'string' && panelIds.includes(rec.activePanelId as DockPanelId)
        ? (rec.activePanelId as DockPanelId)
        : panelIds[0];
    const meta = DOCK_PANEL_META[activePanelId];
    const rawX = typeof rec.x === 'number' && Number.isFinite(rec.x) ? rec.x : 180;
    const rawY = typeof rec.y === 'number' && Number.isFinite(rec.y) ? rec.y : 120;
    const rawW =
      typeof rec.width === 'number' && Number.isFinite(rec.width)
        ? rec.width
        : meta.defaultFloatWidth;
    const rawH =
      typeof rec.height === 'number' && Number.isFinite(rec.height)
        ? rec.height
        : meta.defaultFloatHeight;
    const rect = clampFloatingRect(rawX, rawY, rawW, rawH, panelIds);
    const zIndex =
      typeof rec.zIndex === 'number' && Number.isFinite(rec.zIndex) && rec.zIndex > 0
        ? Math.round(rec.zIndex)
        : result.length + 1;
    let lastDock: FloatingPanelLastDock | undefined;
    if (rec.lastDock && typeof rec.lastDock === 'object') {
      const ld = rec.lastDock as Record<string, unknown>;
      if (ld.side === 'left' || ld.side === 'right' || ld.side === 'bottom') {
        lastDock = {
          side: ld.side,
          colId: typeof ld.colId === 'string' ? ld.colId : undefined,
          groupId: typeof ld.groupId === 'string' ? ld.groupId : undefined,
          ...(typeof ld.cellId === 'string' ? { cellId: ld.cellId } : {}),
        };
      }
    }
    result.push({
      id: typeof rec.id === 'string' && rec.id.trim() ? rec.id : makeUid('float'),
      panelIds,
      activePanelId,
      x: rect.x,
      y: rect.y,
      width: rect.width,
      height: rect.height,
      collapsed: Boolean(rec.collapsed),
      zIndex,
      lastDock,
    });
  }
  return normalizeFloatingZIndices(result);
}

export function sanitizeLayout(raw: unknown): WorkspaceLayout | null {
  if (!raw || typeof raw !== 'object') return null;
  const rec = raw as Record<string, unknown>;
  const seen = new Set<DockPanelId>();
  const leftDocks = sanitizeColumns(rec.leftDocks, seen);
  const rightDocks = sanitizeColumns(rec.rightDocks, seen);
  const bottomDock = sanitizeBottomDock(rec.bottomDock ?? rec.bottomDocks, seen);
  const floatingPanels = sanitizeFloatingPanels(rec.floatingPanels, seen);
  if (
    leftDocks.length === 0 &&
    rightDocks.length === 0 &&
    floatingPanels.length === 0 &&
    !bottomDock
  ) {
    return null;
  }
  return withOptionalBottomDock({ leftDocks, rightDocks, floatingPanels }, bottomDock);
}

function sanitizeQuickAccessItems(raw: unknown): QuickAccessItem[] {
  if (!Array.isArray(raw)) return DEFAULT_QUICK_ACCESS_ITEMS.map((x) => ({ ...x }));
  const items: QuickAccessItem[] = [];
  for (const item of raw) {
    if (!item || typeof item !== 'object') continue;
    const r = item as Record<string, unknown>;
    const id = typeof r.id === 'string' && r.id.trim() ? r.id : makeUid('qa');
    const label = typeof r.label === 'string' && r.label.trim() ? r.label.slice(0, 48) : 'Action';
    if (r.kind === 'command' && typeof r.commandId === 'string' && VALID_COMMAND_SET.has(r.commandId)) {
      items.push({ id, kind: 'command', label, commandId: r.commandId as CommandActionId });
    } else if (r.kind === 'tool' && typeof r.toolId === 'string') {
      items.push({ id, kind: 'tool', label, toolId: r.toolId as QuickAccessItem['toolId'] });
    } else if (
      r.kind === 'color' &&
      typeof r.color === 'string' &&
      /^#[0-9a-fA-F]{3,6}$/.test(r.color)
    ) {
      items.push({ id, kind: 'color', label, color: r.color });
    } else if (r.kind === 'brush' && typeof r.brushPresetId === 'string' && r.brushPresetId.trim()) {
      items.push({ id, kind: 'brush', label, brushPresetId: r.brushPresetId });
    }
  }
  return items;
}

function sanitizeCommandBarIds(raw: unknown): CommandActionId[] {
  if (!Array.isArray(raw)) return [...DEFAULT_COMMAND_BAR_IDS];
  const seen = new Set<CommandActionId>();
  const out: CommandActionId[] = [];
  for (const item of raw) {
    if (typeof item === 'string' && VALID_COMMAND_SET.has(item)) {
      const id = item as CommandActionId;
      if (!seen.has(id)) {
        seen.add(id);
        out.push(id);
      }
    }
  }
  return out;
}

const AUTO_MIGRATED_PANELS: DockPanelId[] = ['info'];

function attachMigratedPanelToLayout(
  layout: WorkspaceLayout,
  panelId: DockPanelId
): WorkspaceLayout {
  if (findPanelLocation(layout, panelId) || findFloatingPanelLocation(layout, panelId)) return layout;
  const anchor =
    findPanelLocation(layout, 'navigator') ?? findPanelLocation(layout, 'sub-view');
  if (anchor) {
    return movePanelInLayout(layout, panelId, {
      side: anchor.side,
      targetColId: anchor.colId,
      targetGroupId: anchor.groupId,
      ...(anchor.cellId ? { targetCellId: anchor.cellId } : {}),
    });
  }
  return togglePanelInLayout(layout, panelId);
}

export function sanitizeQuickBrushPanelState(raw: unknown): QuickBrushPanelState {
  const defaults = createDefaultQuickBrushPanelState();
  if (!raw || typeof raw !== 'object') return defaults;
  const r = raw as Record<string, unknown>;

  const orientation: QuickBrushPanelOrientation =
    r.orientation === 'horizontal' ? 'horizontal' : 'vertical';

  const tileSize: QuickBrushTileSize =
    r.tileSize === 'compact' || r.tileSize === 'large' ? r.tileSize : 'medium';

  const previewStyle: QuickBrushPreviewStyle = r.previewStyle === 'stroke' ? 'stroke' : 'tip';

  const columns: 1 | 2 = r.columns === 2 ? 2 : 1;

  let position: { x: number; y: number } | null = null;
  if (r.position && typeof r.position === 'object') {
    const pos = r.position as Record<string, unknown>;
    if (
      typeof pos.x === 'number' &&
      Number.isFinite(pos.x) &&
      typeof pos.y === 'number' &&
      Number.isFinite(pos.y)
    ) {
      position = { x: Math.round(pos.x), y: Math.round(pos.y) };
    }
  }

  const opacity =
    typeof r.opacity === 'number' && Number.isFinite(r.opacity)
      ? Math.max(0.4, Math.min(1, Math.round(r.opacity * 100) / 100))
      : defaults.opacity;

  const title =
    typeof r.title === 'string' && r.title.trim().length > 0
      ? r.title.trim().slice(0, 28)
      : defaults.title;

  let brushIds: BrushPresetId[] = defaults.brushIds;
  if (Array.isArray(r.brushIds)) {
    const seen = new Set<string>();
    const cleaned: BrushPresetId[] = [];
    for (const item of r.brushIds) {
      if (typeof item === 'string' && item.trim()) {
        const migrated = migrateLegacyPresetId(item.trim());
        if (!seen.has(migrated)) {
          seen.add(migrated);
          cleaned.push(migrated);
        }
      }
    }
    brushIds = cleaned;
  }

  return {
    visible: typeof r.visible === 'boolean' ? r.visible : defaults.visible,
    orientation,
    position,
    locked: typeof r.locked === 'boolean' ? r.locked : defaults.locked,
    keepVisibleWhenPalettesHidden:
      typeof r.keepVisibleWhenPalettesHidden === 'boolean'
        ? r.keepVisibleWhenPalettesHidden
        : defaults.keepVisibleWhenPalettesHidden,
    tileSize,
    columns,
    previewStyle,
    showNames: typeof r.showNames === 'boolean' ? r.showNames : defaults.showNames,
    showTitle: typeof r.showTitle === 'boolean' ? r.showTitle : defaults.showTitle,
    title,
    showCategoryColors:
      typeof r.showCategoryColors === 'boolean'
        ? r.showCategoryColors
        : defaults.showCategoryColors,
    opacity,
    showHideUiButton:
      typeof r.showHideUiButton === 'boolean' ? r.showHideUiButton : defaults.showHideUiButton,
    brushIds,
  };
}

export function sanitizeFocusHudConfig(
  raw: unknown,
  fallbackKeepQuickBrushPanel?: boolean
): FocusHudConfig {
  const defaults = createDefaultFocusHudConfig();
  if (!raw || typeof raw !== 'object') {
    if (typeof fallbackKeepQuickBrushPanel === 'boolean') {
      return { ...defaults, keepQuickBrushPanel: fallbackKeepQuickBrushPanel };
    }
    return defaults;
  }
  const r = raw as Record<string, unknown>;

  const preset: FocusHudPresetId =
    r.preset === 'pure-canvas' || r.preset === 'custom' ? r.preset : 'atelier-hud';

  const quickActionIds = Array.isArray(r.quickActionIds)
    ? sanitizeCommandBarIds(r.quickActionIds)
    : [...DEFAULT_FOCUS_QUICK_ACTION_IDS];

  const hudPositions: FocusHudPositions = {};
  if (r.hudPositions && typeof r.hudPositions === 'object' && !Array.isArray(r.hudPositions)) {
    const rawPos = r.hudPositions as Record<string, unknown>;
    for (const wid of FOCUS_HUD_WIDGET_IDS) {
      const pt = rawPos[wid];
      if (pt && typeof pt === 'object') {
        const rec = pt as Record<string, unknown>;
        if (
          typeof rec.x === 'number' &&
          Number.isFinite(rec.x) &&
          typeof rec.y === 'number' &&
          Number.isFinite(rec.y)
        ) {
          hudPositions[wid] = { x: Math.round(rec.x), y: Math.round(rec.y) };
        }
      }
    }
  }

  return {
    preset,
    showToolRail: typeof r.showToolRail === 'boolean' ? r.showToolRail : defaults.showToolRail,
    showBrushSlidersHud:
      typeof r.showBrushSlidersHud === 'boolean'
        ? r.showBrushSlidersHud
        : defaults.showBrushSlidersHud,
    showQuickActionDock:
      typeof r.showQuickActionDock === 'boolean'
        ? r.showQuickActionDock
        : defaults.showQuickActionDock,
    showFloatingColorWheel:
      typeof r.showFloatingColorWheel === 'boolean'
        ? r.showFloatingColorWheel
        : defaults.showFloatingColorWheel,
    keepQuickBrushPanel:
      typeof r.keepQuickBrushPanel === 'boolean'
        ? r.keepQuickBrushPanel
        : (fallbackKeepQuickBrushPanel ?? defaults.keepQuickBrushPanel),
    hideHeaderInFocus:
      typeof r.hideHeaderInFocus === 'boolean'
        ? r.hideHeaderInFocus
        : defaults.hideHeaderInFocus,
    autoFadeWhileDrawing:
      typeof r.autoFadeWhileDrawing === 'boolean'
        ? r.autoFadeWhileDrawing
        : defaults.autoFadeWhileDrawing,
    quickActionIds,
    hudPositions,
  };
}

export function sanitizeWorkspaceLocks(raw: unknown): WorkspaceLocks {
  if (!raw || typeof raw !== 'object') {
    return { ...DEFAULT_WORKSPACE_LOCKS };
  }
  const r = raw as Record<string, unknown>;
  return {
    lockWidth: Boolean(r.lockWidth),
    lockHeight: Boolean(r.lockHeight),
    lockMove: Boolean(r.lockMove),
  };
}

export function sanitizeStatusBarModules(raw: unknown): StatusBarModulesConfig {
  if (!raw || typeof raw !== 'object') {
    return { ...DEFAULT_STATUS_BAR_MODULES };
  }
  const r = raw as Record<string, unknown>;
  return {
    toolInfo: typeof r.toolInfo === 'boolean' ? r.toolInfo : DEFAULT_STATUS_BAR_MODULES.toolInfo,
    canvasInfo:
      typeof r.canvasInfo === 'boolean' ? r.canvasInfo : DEFAULT_STATUS_BAR_MODULES.canvasInfo,
    valueCheck:
      typeof r.valueCheck === 'boolean' ? r.valueCheck : DEFAULT_STATUS_BAR_MODULES.valueCheck,
    cursorCoords:
      typeof r.cursorCoords === 'boolean' ? r.cursorCoords : DEFAULT_STATUS_BAR_MODULES.cursorCoords,
    pressureMeter:
      typeof r.pressureMeter === 'boolean'
        ? r.pressureMeter
        : DEFAULT_STATUS_BAR_MODULES.pressureMeter,
    rotationZoom:
      typeof r.rotationZoom === 'boolean' ? r.rotationZoom : DEFAULT_STATUS_BAR_MODULES.rotationZoom,
  };
}

export function sanitizeSavedWorkspaces(raw: unknown): SavedWorkspaceProfile[] {
  if (!Array.isArray(raw)) return [];
  const seenIds = new Set<string>();
  const out: SavedWorkspaceProfile[] = [];
  for (const item of raw) {
    if (!item || typeof item !== 'object') continue;
    const r = item as Record<string, unknown>;
    const layout = sanitizeLayout(r.layout);
    if (!layout) continue;
    const rawId = typeof r.id === 'string' && r.id.trim() ? r.id.trim().slice(0, 64) : makeUid('ws');
    const id = seenIds.has(rawId) ? makeUid('ws') : rawId;
    seenIds.add(id);
    const name =
      typeof r.name === 'string' && r.name.trim().length > 0
        ? r.name.trim().slice(0, 48)
        : `Workspace ${out.length + 1}`;
    const nowIso = new Date().toISOString();
    const createdAt =
      typeof r.createdAt === 'string' && r.createdAt.trim() ? r.createdAt.trim().slice(0, 64) : nowIso;
    const updatedAt =
      typeof r.updatedAt === 'string' && r.updatedAt.trim() ? r.updatedAt.trim().slice(0, 64) : createdAt;

    let appearance: AppearanceConfig | undefined;
    if (r.appearance && typeof r.appearance === 'object' && !Array.isArray(r.appearance)) {
      appearance = sanitizeAppearanceConfig(r.appearance);
    }

    out.push({
      id,
      name,
      createdAt,
      updatedAt,
      layout,
      leftHandedMode: Boolean(r.leftHandedMode),
      showToolOptionsBar: Boolean(r.showToolOptionsBar),
      showStatusBar: typeof r.showStatusBar === 'boolean' ? r.showStatusBar : true,
      showDocumentTabs: typeof r.showDocumentTabs === 'boolean' ? r.showDocumentTabs : true,
      showCommandBar: typeof r.showCommandBar === 'boolean' ? r.showCommandBar : true,
      ...(r.statusBarModules ? { statusBarModules: sanitizeStatusBarModules(r.statusBarModules) } : {}),
      ...(r.workspaceLocks ? { workspaceLocks: sanitizeWorkspaceLocks(r.workspaceLocks) } : {}),
      ...(appearance ? { appearance } : {}),
    });
  }
  return out.slice(0, 64);
}

const MAX_WORKSPACE_BUNDLE_BYTES = 256 * 1024;

export interface SerializeWorkspaceBundleInput {
  name: string;
  author?: string;
  createdAt?: string;
  layout: WorkspaceLayout;
  leftHandedMode: boolean;
  showToolOptionsBar: boolean;
  showStatusBar: boolean;
  showDocumentTabs: boolean;
  showCommandBar: boolean;
  statusBarModules?: StatusBarModulesConfig;
  workspaceLocks?: WorkspaceLocks;
  appearance?: AppearanceConfig;
}

/**
 * Serializes a workspace layout + bar configuration (+ optional Appearance preset)
 * into a portable versioned `.inkworkspace` JSON bundle.
 */
export function serializeWorkspaceBundle(input: SerializeWorkspaceBundleInput): string {
  const safeName =
    typeof input.name === 'string' && input.name.trim().length > 0
      ? input.name.trim().slice(0, 64)
      : 'Custom Workspace';
  const payload: InkWorkspaceBundleFile = {
    format: INK_WORKSPACE_FORMAT_ID,
    version: INK_WORKSPACE_SCHEMA_VERSION,
    name: safeName,
    ...(typeof input.author === 'string' && input.author.trim()
      ? { author: input.author.trim().slice(0, 80) }
      : {}),
    createdAt:
      typeof input.createdAt === 'string' && input.createdAt.trim()
        ? input.createdAt.trim().slice(0, 64)
        : new Date().toISOString(),
    layout: cloneLayout(input.layout),
    leftHandedMode: Boolean(input.leftHandedMode),
    showToolOptionsBar: Boolean(input.showToolOptionsBar),
    showStatusBar: Boolean(input.showStatusBar),
    showDocumentTabs: Boolean(input.showDocumentTabs),
    showCommandBar: Boolean(input.showCommandBar),
    ...(input.statusBarModules
      ? { statusBarModules: sanitizeStatusBarModules(input.statusBarModules) }
      : {}),
    ...(input.workspaceLocks
      ? { workspaceLocks: sanitizeWorkspaceLocks(input.workspaceLocks) }
      : {}),
    ...(input.appearance ? { appearance: sanitizeAppearanceConfig(input.appearance) } : {}),
  };
  return JSON.stringify(payload, null, 2);
}

/**
 * Parses and strictly validates an `.inkworkspace` JSON bundle without throwing.
 * Validates bundled Appearance config via `parseThemePreset` so malicious token overrides are rejected.
 */
export function parseWorkspaceBundle(rawJson: string): ParseWorkspaceBundleResult {
  if (typeof rawJson !== 'string' || rawJson.trim().length === 0) {
    return { ok: false, error: t('Workspace file is empty.') };
  }
  if (rawJson.length > MAX_WORKSPACE_BUNDLE_BYTES) {
    return { ok: false, error: t('Workspace file exceeds maximum allowed size (256 KB).') };
  }

  let parsed: unknown;
  try {
    parsed = JSON.parse(rawJson);
  } catch {
    return { ok: false, error: t('Workspace file is not valid JSON.') };
  }

  if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
    return { ok: false, error: t('Workspace file root must be a JSON object.') };
  }

  const root = parsed as Record<string, unknown>;
  if (root.format !== INK_WORKSPACE_FORMAT_ID) {
    return {
      ok: false,
      error: t('Invalid workspace format identifier. Expected "{expected}".', {
        expected: INK_WORKSPACE_FORMAT_ID,
      }),
    };
  }
  if (root.version !== INK_WORKSPACE_SCHEMA_VERSION) {
    return {
      ok: false,
      error: t('Unsupported workspace schema version: {version}. Expected version {expected}.', {
        version: String(root.version),
        expected: INK_WORKSPACE_SCHEMA_VERSION,
      }),
    };
  }
  if (typeof root.name !== 'string' || root.name.trim().length === 0) {
    return { ok: false, error: t('Workspace file must include a non-empty "name" string.') };
  }

  const layout = sanitizeLayout(root.layout);
  if (!layout) {
    return { ok: false, error: t('Workspace file contains no valid dock or floating panels.') };
  }

  const warnings: string[] = [];
  let appearance: AppearanceConfig | undefined;
  if (root.appearance !== undefined) {
    if (!root.appearance || typeof root.appearance !== 'object' || Array.isArray(root.appearance)) {
      return { ok: false, error: t('Bundled "appearance" field must be an object.') };
    }
    const themeCheck = parseThemePreset(
      JSON.stringify({
        format: INK_THEME_FORMAT_ID,
        version: INK_THEME_SCHEMA_VERSION,
        name: root.name.trim(),
        appearance: root.appearance,
      })
    );
    if (!themeCheck.ok) {
      return {
        ok: false,
        error: t('Invalid bundled appearance: {error}', { error: themeCheck.error }),
      };
    }
    appearance = themeCheck.preset.appearance;
    warnings.push(...themeCheck.warnings);
  }

  const bundle: InkWorkspaceBundleFile = {
    format: INK_WORKSPACE_FORMAT_ID,
    version: INK_WORKSPACE_SCHEMA_VERSION,
    name: root.name.trim().slice(0, 64),
    ...(typeof root.author === 'string' && root.author.trim()
      ? { author: root.author.trim().slice(0, 80) }
      : {}),
    ...(typeof root.createdAt === 'string' && root.createdAt.trim()
      ? { createdAt: root.createdAt.trim().slice(0, 64) }
      : {}),
    layout,
    leftHandedMode: Boolean(root.leftHandedMode),
    showToolOptionsBar: Boolean(root.showToolOptionsBar),
    showStatusBar: typeof root.showStatusBar === 'boolean' ? root.showStatusBar : true,
    showDocumentTabs: typeof root.showDocumentTabs === 'boolean' ? root.showDocumentTabs : true,
    showCommandBar: typeof root.showCommandBar === 'boolean' ? root.showCommandBar : true,
    ...(root.statusBarModules
      ? { statusBarModules: sanitizeStatusBarModules(root.statusBarModules) }
      : {}),
    ...(root.workspaceLocks
      ? { workspaceLocks: sanitizeWorkspaceLocks(root.workspaceLocks) }
      : {}),
    ...(appearance ? { appearance } : {}),
  };

  return { ok: true, bundle, warnings };
}

export function createDefaultPersistedWorkspace(): PersistedWorkspaceState {
  return {
    version: 1,
    activePreset: 'default-illustration',
    activeSavedWorkspaceId: null,
    layout: cloneLayout(DEFAULT_ILLUSTRATION_LAYOUT),
    savedCustomLayout: null,
    savedWorkspaces: [],
    leftHandedMode: false,
    quickAccessItems: DEFAULT_QUICK_ACCESS_ITEMS.map((x) => ({ ...x })),
    quickAccessViewMode: 'grid',
    quickBrushPanel: createDefaultQuickBrushPanelState(),
    focusHud: createDefaultFocusHudConfig(),
    commandBarIds: [...DEFAULT_COMMAND_BAR_IDS],
    showStatusBar: true,
    showDocumentTabs: true,
    showCommandBar: true,
    showToolOptionsBar: false,
    statusBarModules: { ...DEFAULT_STATUS_BAR_MODULES },
    workspaceLocks: { ...DEFAULT_WORKSPACE_LOCKS },
    navigatorPreviewMode: 'color',
    navigatorSplitRatio: DEFAULT_NAVIGATOR_SPLIT_RATIO,
    migratedPanels: [...AUTO_MIGRATED_PANELS],
    migratedQuickBrushDefaults: true,
  };
}

export function loadWorkspaceState(): PersistedWorkspaceState {
  const fallback = createDefaultPersistedWorkspace();
  try {
    if (typeof localStorage === 'undefined') return fallback;
    const raw = localStorage.getItem(WORKSPACE_STORAGE_KEY);
    if (!raw) return fallback;
    const parsed = JSON.parse(raw) as Record<string, unknown>;
    if (!parsed || typeof parsed !== 'object') return fallback;

    const validPresets: WorkspacePresetId[] = [...BUILT_IN_WORKSPACE_PRESET_IDS, 'custom'];
    const activePreset: WorkspacePresetId = validPresets.includes(parsed.activePreset as WorkspacePresetId)
      ? (parsed.activePreset as WorkspacePresetId)
      : 'default-illustration';

    const existingMigrated = new Set<DockPanelId>(
      Array.isArray(parsed.migratedPanels)
        ? parsed.migratedPanels.filter(
            (id): id is DockPanelId => typeof id === 'string' && VALID_PANEL_SET.has(id)
          )
        : []
    );

    let layout = sanitizeLayout(parsed.layout) ?? fallback.layout;
    let savedCustomLayout = sanitizeLayout(parsed.savedCustomLayout);
    for (const panelId of AUTO_MIGRATED_PANELS) {
      if (!existingMigrated.has(panelId)) {
        layout = attachMigratedPanelToLayout(layout, panelId);
        if (savedCustomLayout) {
          savedCustomLayout = attachMigratedPanelToLayout(savedCustomLayout, panelId);
        }
        existingMigrated.add(panelId);
      }
    }

    const savedWorkspaces = sanitizeSavedWorkspaces(parsed.savedWorkspaces);
    const activeSavedWorkspaceId =
      typeof parsed.activeSavedWorkspaceId === 'string' &&
      savedWorkspaces.some((ws) => ws.id === parsed.activeSavedWorkspaceId)
        ? parsed.activeSavedWorkspaceId
        : null;
    const leftHandedMode = Boolean(parsed.leftHandedMode);
    const showToolOptionsBar =
      typeof parsed.showToolOptionsBar === 'boolean'
        ? parsed.showToolOptionsBar
        : activePreset === 'photoshop-studio';
    const statusBarModules = sanitizeStatusBarModules(parsed.statusBarModules);
    const workspaceLocks = sanitizeWorkspaceLocks(parsed.workspaceLocks);

    const quickAccessItems = sanitizeQuickAccessItems(parsed.quickAccessItems);
    const quickAccessViewMode: QuickAccessViewMode =
      parsed.quickAccessViewMode === 'list' ? 'list' : 'grid';
    let quickBrushPanel = sanitizeQuickBrushPanelState(parsed.quickBrushPanel);
    const alreadyMigratedQuickBrushDefaults = parsed.migratedQuickBrushDefaults === true;
    let shouldPersistMigration = false;
    if (!alreadyMigratedQuickBrushDefaults) {
      if (isLegacyDefaultQuickBrushIds(quickBrushPanel.brushIds)) {
        quickBrushPanel = {
          ...quickBrushPanel,
          brushIds: [],
        };
      }
      shouldPersistMigration = true;
    }
    const focusHud = sanitizeFocusHudConfig(
      parsed.focusHud,
      quickBrushPanel.keepVisibleWhenPalettesHidden
    );
    // Keep QuickBrushPanel flag synced with persisted focusHud
    if (quickBrushPanel.keepVisibleWhenPalettesHidden !== focusHud.keepQuickBrushPanel) {
      quickBrushPanel = {
        ...quickBrushPanel,
        keepVisibleWhenPalettesHidden: focusHud.keepQuickBrushPanel,
      };
    }
    const commandBarIds = sanitizeCommandBarIds(parsed.commandBarIds);
    const navigatorPreviewMode: NavigatorPreviewMode =
      parsed.navigatorPreviewMode === 'bw' || parsed.navigatorPreviewMode === 'split'
        ? parsed.navigatorPreviewMode
        : 'color';
    const navigatorSplitRatio =
      typeof parsed.navigatorSplitRatio === 'number'
        ? clampNavigatorSplitRatio(parsed.navigatorSplitRatio)
        : DEFAULT_NAVIGATOR_SPLIT_RATIO;

    const result: PersistedWorkspaceState = {
      version: 1,
      activePreset,
      activeSavedWorkspaceId,
      layout,
      savedCustomLayout,
      savedWorkspaces,
      leftHandedMode,
      quickAccessItems,
      quickAccessViewMode,
      quickBrushPanel,
      focusHud,
      commandBarIds,
      showStatusBar: typeof parsed.showStatusBar === 'boolean' ? parsed.showStatusBar : true,
      showDocumentTabs: typeof parsed.showDocumentTabs === 'boolean' ? parsed.showDocumentTabs : true,
      showCommandBar: typeof parsed.showCommandBar === 'boolean' ? parsed.showCommandBar : true,
      showToolOptionsBar,
      statusBarModules,
      workspaceLocks,
      navigatorPreviewMode,
      navigatorSplitRatio,
      migratedPanels: Array.from(existingMigrated),
      migratedQuickBrushDefaults: true,
    };

    if (shouldPersistMigration) {
      saveWorkspaceState(result);
    }

    return result;
  } catch {
    return fallback;
  }
}

export function saveWorkspaceState(state: PersistedWorkspaceState): void {
  safeLocalStorageSetItem(WORKSPACE_STORAGE_KEY, JSON.stringify(state), 'workspace layout');
}