Skip to content

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

148 KB
Raw Blame
import React, { useState, useRef, useEffect, useMemo } from 'react';
import {
  ChevronDown,
  ChevronRight,
  Scaling,
  Maximize2,
  Minimize2,
  RotateCcw,
  Feather,
  Sliders,
  Scissors,
  Copy,
  ClipboardPaste,
  Layers,
  Trash2,
  Crop,
  AlertTriangle,
  Bold,
  Italic,
  Underline,
  AlignLeft,
  AlignCenter,
  AlignRight,
  Pipette,
} from 'lucide-react';
import {
  BrushSettings,
  BrushPresetId,
  CspBrush,
  BrushDynamics,
  DEFAULT_BRUSH_DYNAMICS,
  DEFAULT_NATURAL_PAINT_SETTINGS,
  LiquifyMode,
  CspAngleDynamicsMode,
  CspBlendTipsMode,
  CspPaperTextureMode,
  CspTipFlipMode,
  CspTaperSettings,
  CspSpraySettings,
  ShapeKind,
  ShapeDrawMode,
  ShapeFillColorMode,
  GradientType,
  GradientRepeatMode,
  GradientBlendMode,
  RetouchMode,
  RetouchTonalRange,
  CloneSampleMode,
  PenToolMode,
  isBrushLikeTool,
  isPaintTool,
} from '../types/editor';
import { isOpenShape } from '../utils/shapeEngine';
import {
  getTextFontOptions,
  queryInstalledSystemFonts,
  TEXT_QUICK_COLORS,
} from '../utils/textSettings';
import {
  GRADIENT_PRESETS,
  getSelectedMeshNodeIndices,
  resolveGradientStops,
} from '../utils/toolConfigs';
import { saveCustomBrushDebounced } from '../utils/brushStorage';
import { resolveBrushTipImage } from '../utils/brushOutline';
import { ALL_BUILTIN_BRUSHES } from '../utils/presetBrushes';
import {
  resetBrushSettingsToDefault,
  ERASER_PRESET_ID,
  DEFAULT_BRUSH_PRESET_ID,
} from '../utils/brushPresetManager';
import { renderBrushStrokePreview } from '../utils/brushPreview';
import { CSP_PRESSURE_CURVE_PRESETS } from '../utils/brushMath';
import {
  useToolStore,
  toolStoreActions,
  interactiveToolBridge,
  useUiStore,
  uiStoreActions,
} from '../stores';
import { Tool3DPropertyInspector } from './Tool3DPropertyInspector';
import { PigmentBlendControl } from './PigmentBlendControl';
import { resolveBrushCursorRotationSpec } from './canvasArea/types';
import { resolveAppearanceTokens } from '../utils/themeEngine';
import {
  PrecisionNumberInput,
  ScrubSlider,
  SectionDisclosure,
  SegmentedControl,
  ToggleSwitch,
  formatNumericValue,
  type ScrubSliderVariant,
} from './ui';
import { useI18n } from '../i18n';

interface CompactSliderProps {
  label: string;
  valueLabel: string;
  min: number;
  max: number;
  step?: number;
  defaultValue?: number;
  variant?: ScrubSliderVariant;
  logarithmic?: boolean;
  value: number;
  onChange: (val: number) => void;
}

function inferUnitFromValueLabel(valueLabel: string): string {
  const match = valueLabel.trim().match(/(%|px|°|deg|mm|x)$/i);
  return match ? match[1] : '';
}

function inferCompactVariant(label: string): ScrubSliderVariant {
  const lower = label.toLowerCase();
  if (lower.includes('opacity') || label.includes('不透明度')) return 'opacity';
  if (
    (lower.includes('size') ||
      lower.includes('stroke') ||
      lower.includes('radius') ||
      lower.includes('width') ||
      label.includes('サイズ') ||
      label.includes('線幅') ||
      label.includes('半径') ||
      label.includes('太さ') ||
      label.includes('幅')) &&
    !lower.includes('jitter') &&
    !lower.includes('min') &&
    !lower.includes('adjust') &&
    !label.includes('ジッター') &&
    !label.includes('最小') &&
    !label.includes('調整')
  ) {
    return 'size';
  }
  return 'default';
}

const CompactSlider: React.FC<CompactSliderProps> = ({
  label,
  valueLabel,
  min,
  max,
  step = 1,
  defaultValue,
  variant,
  logarithmic,
  value,
  onChange,
}) => {
  const unit = inferUnitFromValueLabel(valueLabel);
  const resolvedVariant = variant ?? inferCompactVariant(label);

  return (
    <ScrubSlider
      label={label}
      min={min}
      max={max}
      step={step}
      defaultValue={defaultValue}
      variant={resolvedVariant}
      logarithmic={logarithmic}
      unit={unit}
      value={value}
      formatValue={(v) =>
        Math.abs(v - value) < 1e-6 ? valueLabel : formatNumericValue(v, step, unit)
      }
      onChange={onChange}
    />
  );
};

const LIQUIFY_MODES: Array<{ id: LiquifyMode; label: string }> = [
  { id: 'push', label: 'Push' },
  { id: 'expand', label: 'Expand' },
  { id: 'pinch', label: 'Pinch' },
  { id: 'push-left', label: 'Push Left' },
  { id: 'push-right', label: 'Push Right' },
  { id: 'twirl-cw', label: 'Twirl CW' },
  { id: 'twirl-ccw', label: 'Twirl CCW' },
  { id: 'reconstruct', label: 'Reconstruct' },
];

type InspectorAccordionId = 'ink' | 'tip' | 'stroke' | 'mixing' | 'texture' | 'dynamics';

const DEFAULT_TAPER: CspTaperSettings = {
  useIn: false,
  inLength: 24,
  inRatio: 0.9,
  useOut: false,
  outLength: 32,
  outRatio: 0.9,
  startingSharpness: 0.85,
  endingSharpness: 0.85,
  affectSize: true,
};

const DEFAULT_SPRAY: CspSpraySettings = {
  enabled: false,
  size: 4,
  density: 12,
  bias: 0.5,
};

export interface ToolPropertyInspectorProps {
  width: number;
  customBrushes: CspBrush[];
  setCustomBrushes: React.Dispatch<React.SetStateAction<CspBrush[]>>;
  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;
}

export const ToolPropertyInspector: React.FC<ToolPropertyInspectorProps> = React.memo(
  ({
    width,
    customBrushes,
    setCustomBrushes,
    onDeselect,
    onTransformSelection,
    onClearSelection,
    onDeleteOutsideSelection,
    onCutSelection,
    onCopySelection,
    onPasteSelection,
    onMoveSelectionToNewLayer,
    onExpandSelection,
    onContractSelection,
    onFeatherSelection,
    onInvertSelection,
  }) => {
    const { t, tc, td } = useI18n();
    const currentTool = useToolStore((s) => s.tool);
    const brushSettings = useToolStore((s) => s.brushSettings);
    const fillSettings = useToolStore((s) => s.fillSettings);
    const textSettings = useToolStore((s) => s.textSettings);
    const frameSettings = useToolStore((s) => s.frameSettings);
    const liquifySettings = useToolStore((s) => s.liquifySettings);
    const shapeSettings = useToolStore((s) => s.shapeSettings);
    const gradientSettings = useToolStore((s) => s.gradientSettings);
    const activeGradientMesh = useToolStore((s) => s.activeGradientMesh);
    const retouchSettings = useToolStore((s) => s.retouchSettings);
    const isPickingCloneSource = useToolStore((s) => s.isPickingCloneSource);
    const cloneSourceAnchor = useToolStore((s) => s.cloneSourceAnchor);
    const penSettings = useToolStore((s) => s.penSettings);
    const activePenPointCount = useToolStore((s) => s.activePenPointCount);
    const activePenClosed = useToolStore((s) => s.activePenClosed);
    const activePenSelectedAnchor = useToolStore((s) => s.activePenSelectedAnchor);
    const primaryColor = useToolStore((s) => s.primaryColor);
    const secondaryColor = useToolStore((s) => s.secondaryColor);
    const isTransparentColor = useToolStore((s) => s.isTransparentColor);
    const balloonSettings = useToolStore((s) => s.balloonSettings);
    const vectorEditSettings = useToolStore((s) => s.vectorEditSettings);
    const wandSettings = useToolStore((s) => s.wandSettings);
    const isHidden = useUiStore((s) => s.isLeftPanelHidden);
    const appearance = useUiStore((s) => s.appSettings.appearance);

    const resolvedTheme = useMemo(() => resolveAppearanceTokens(appearance), [appearance]);
    const previewStrokeColor = resolvedTheme.tokens['--ui-text-primary'];
    const previewBgColor = resolvedTheme.tokens['--ui-bg-input'];

    const [openAccordion, setOpenAccordion] = useState<InspectorAccordionId | null>(null);
    const [warningsExpanded, setWarningsExpanded] = useState<boolean>(false);
    const previewCanvasRef = useRef<HTMLCanvasElement>(null);

    const isBrushOrEraser = isBrushLikeTool(currentTool);

    useEffect(() => {
      setWarningsExpanded(false);
    }, [brushSettings.preset]);

    useEffect(() => {
      if (isHidden || !isBrushOrEraser) return;
      const canvas = previewCanvasRef.current;
      if (!canvas) return;
      const cssWidth = Math.max(96, width - 16);
      const cssHeight = 32;
      let loadListenerCleanup: (() => void) | null = null;
      const drawPreview = () => {
        const resolvedTip = resolveBrushTipImage(brushSettings);
        if (resolvedTip && !resolvedTip.complete) {
          const onLoad = () => drawPreview();
          resolvedTip.addEventListener('load', onLoad, { once: true });
          loadListenerCleanup = () => resolvedTip.removeEventListener('load', onLoad);
        }
        renderBrushStrokePreview(
          canvas,
          cssWidth,
          cssHeight,
          {
            preset: brushSettings.preset,
            size: brushSettings.size,
            flow: brushSettings.flow,
            brushDensity: brushSettings.brushDensity,
            opacity: brushSettings.opacity,
            grain: brushSettings.grain,
            textureDensity: brushSettings.textureDensity,
            paperTexture: brushSettings.paperTexture,
            paperTextureImage: brushSettings.paperTextureImage,
            paperTextureMode: brushSettings.paperTextureMode,
            paperTextureScale: brushSettings.paperTextureScale,
            paperTextureRotate: brushSettings.paperTextureRotate,
            paperTextureOffsetX: brushSettings.paperTextureOffsetX,
            paperTextureOffsetY: brushSettings.paperTextureOffsetY,
            paperTextureContrast: brushSettings.paperTextureContrast,
            paperTextureBrightness: brushSettings.paperTextureBrightness,
            paperTextureApplyEachPlot: brushSettings.paperTextureApplyEachPlot,
            paperTextureEmphasizeDensity: brushSettings.paperTextureEmphasizeDensity,
            paperTextureInverted: brushSettings.paperTextureInverted,
            hardness: brushSettings.hardness,
            spacing: brushSettings.spacing,
            minSizeFactor: brushSettings.minSizeFactor,
            usePressure: brushSettings.usePressure,
            useTilt: brushSettings.useTilt,
            tiltScale: brushSettings.tiltScale,
            useVelocity: brushSettings.useVelocity,
            color: previewStrokeColor,
            secondaryColor: secondaryColor || brushSettings.secondaryColor || '#60a5fa',
            backgroundColor: previewBgColor,
            tool: currentTool === 'eraser' ? 'eraser' : 'brush',
            customTipDataUrl: brushSettings.customTipDataUrl,
            customTipImage: resolvedTip,
            customTipAngle: brushSettings.customTipAngle,
            customTipAngleDynamics: brushSettings.customTipAngleDynamics,
            customTipRotationRandomScale: brushSettings.customTipRotationRandomScale,
            isColorTip: brushSettings.isColorTip,
            isDualToneTip: brushSettings.isDualToneTip,
            isRibbon: brushSettings.isRibbon,
            subTips: brushSettings.subTips,
            subTipOrder: brushSettings.subTipOrder,
            subTipImages: brushSettings.subTipImages,
            thickness: brushSettings.thickness,
            thicknessVertical: brushSettings.thicknessVertical,
            thicknessSensor: brushSettings.thicknessSensor,
            flipH: brushSettings.flipH,
            flipV: brushSettings.flipV,
            blendTipsMode: brushSettings.blendTipsMode,
            brushCombineMode: brushSettings.brushCombineMode,
            adjustDensityByGap: brushSettings.adjustDensityByGap,
            antiAlias: brushSettings.antiAlias,
            pressureCurve: brushSettings.pressureCurve,
            velocityCurve: brushSettings.velocityCurve,
            sizeSensor: brushSettings.sizeSensor,
            opacitySensor: brushSettings.opacitySensor,
            densitySensor: brushSettings.densitySensor,
            intervalSensor: brushSettings.intervalSensor,
            textureDensitySensor: brushSettings.textureDensitySensor,
            angleSensor: brushSettings.angleSensor,
            scatterSensor: brushSettings.scatterSensor,
            spray: brushSettings.spray,
            taper: brushSettings.taper,
            dynamics: brushSettings.dynamics,
            colorMixing: brushSettings.colorMixing,
            perceptualMixing: brushSettings.perceptualMixing,
            amountOfPaint: brushSettings.amountOfPaint,
            densityOfPaint: brushSettings.densityOfPaint,
            colorStretch: brushSettings.colorStretch,
            amountOfPaintSensor: brushSettings.amountOfPaintSensor,
            densityOfPaintSensor: brushSettings.densityOfPaintSensor,
            colorStretchSensor: brushSettings.colorStretchSensor,
            useBlur: brushSettings.useBlur,
            blurStrength: brushSettings.blurStrength,
            mixingMode: brushSettings.mixingMode,
            wetEdge: brushSettings.wetEdge,
            wetEdgeRadius: brushSettings.wetEdgeRadius,
            wetEdgeAlphaPower: brushSettings.wetEdgeAlphaPower,
            wetEdgeValuePower: brushSettings.wetEdgeValuePower,
            dualBrush: brushSettings.dualBrush,
            dualBrushConfig: brushSettings.dualBrushConfig,
            dualBrushCompositeMode: brushSettings.dualBrushCompositeMode,
            dualTipDataUrl: brushSettings.dualTipDataUrl,
            dualTipImage: brushSettings.dualTipImage,
            dualSize: brushSettings.dualSize,
            dualLinkSize: brushSettings.dualLinkSize,
            dualSpacing: brushSettings.dualSpacing,
            dualScatter: brushSettings.dualScatter,
            dualThickness: brushSettings.dualThickness,
            dualThicknessVertical: brushSettings.dualThicknessVertical,
            dualAngle: brushSettings.dualAngle,
            dualAngleDynamics: brushSettings.dualAngleDynamics,
            dualAngleSensor: brushSettings.dualAngleSensor,
            dualHardness: brushSettings.dualHardness,
            dualDensity: brushSettings.dualDensity,
            dualSubTips: brushSettings.dualSubTips,
            dualSubTipImages: brushSettings.dualSubTipImages,
            dualSubTipOrder: brushSettings.dualSubTipOrder,
            dualFlipH: brushSettings.dualFlipH,
            dualFlipV: brushSettings.dualFlipV,
            dualSpray: brushSettings.dualSpray,
            dualIsRibbon: brushSettings.dualIsRibbon,
            dualScale: brushSettings.dualScale,
            renderMode: brushSettings.renderMode,
            bristle: brushSettings.bristle,
            naturalPaint: brushSettings.naturalPaint,
            impasto: brushSettings.impasto,
            surfaceTextureId: brushSettings.surfaceTextureId,
            grainMappingMode: brushSettings.grainMappingMode,
          },
          true
        );
      };
      const rafId = requestAnimationFrame(drawPreview);
      return () => {
        cancelAnimationFrame(rafId);
        loadListenerCleanup?.();
      };
    }, [
      isHidden,
      isBrushOrEraser,
      width,
      currentTool,
      brushSettings,
      secondaryColor,
      previewStrokeColor,
      previewBgColor,
    ]);

    const activePreset: BrushPresetId = brushSettings.preset || DEFAULT_BRUSH_PRESET_ID;
    const activeBuiltinBrush = ALL_BUILTIN_BRUSHES.find((b) => b.id === activePreset);
    const isCustomBrushActive =
      isPaintTool(currentTool) &&
      (activePreset.startsWith('csp-') ||
        (Boolean(brushSettings.customTipDataUrl) && !activeBuiltinBrush));
    const activeCustomBrush = isCustomBrushActive
      ? customBrushes.find((b) => b.id === activePreset)
      : null;

    const handleUpdateBrushSettings = (newSettings: Partial<BrushSettings>) => {
      toolStoreActions.updateBrushSettings(newSettings);
      if (isCustomBrushActive && activeCustomBrush) {
        const updatedBrush: CspBrush = {
          ...activeCustomBrush,
          size: newSettings.size ?? activeCustomBrush.size,
          opacity: newSettings.opacity ?? activeCustomBrush.opacity,
          flow: newSettings.flow ?? activeCustomBrush.flow,
          brushDensity:
            newSettings.brushDensity ?? newSettings.flow ?? activeCustomBrush.brushDensity,
          adjustDensityByGap:
            newSettings.adjustDensityByGap ?? activeCustomBrush.adjustDensityByGap,
          blendTipsMode: newSettings.blendTipsMode ?? activeCustomBrush.blendTipsMode,
          spacing: newSettings.spacing ?? activeCustomBrush.spacing,
          hardness: newSettings.hardness ?? activeCustomBrush.hardness,
          thickness: newSettings.thickness ?? activeCustomBrush.thickness,
          thicknessVertical:
            newSettings.thicknessVertical ?? activeCustomBrush.thicknessVertical,
          antiAlias: newSettings.antiAlias ?? activeCustomBrush.antiAlias,
          stabilization: newSettings.stabilization ?? activeCustomBrush.stabilization,
          postCorrection: newSettings.postCorrection ?? activeCustomBrush.postCorrection,
          sharpCorners: newSettings.sharpCorners ?? activeCustomBrush.sharpCorners,
          angle: newSettings.customTipAngle ?? activeCustomBrush.angle,
          angleDynamics: newSettings.customTipAngleDynamics ?? activeCustomBrush.angleDynamics,
          rotateCursor:
            'rotateCursor' in newSettings
              ? newSettings.rotateCursor
              : activeCustomBrush.rotateCursor,
          flipH: newSettings.flipH ?? activeCustomBrush.flipH,
          flipV: newSettings.flipV ?? activeCustomBrush.flipV,
          isRibbon: newSettings.isRibbon ?? activeCustomBrush.isRibbon,
          usePressure: newSettings.usePressure ?? activeCustomBrush.usePressure,
          useTilt: newSettings.useTilt ?? activeCustomBrush.useTilt,
          useVelocity: newSettings.useVelocity ?? activeCustomBrush.useVelocity,
          pressureCurve: newSettings.pressureCurve ?? activeCustomBrush.pressureCurve,
          taper: newSettings.taper ?? activeCustomBrush.taper,
          spray: newSettings.spray ?? activeCustomBrush.spray,
          colorMixing: newSettings.colorMixing ?? activeCustomBrush.colorMixing,
          perceptualMixing: newSettings.perceptualMixing ?? activeCustomBrush.perceptualMixing,
          mixingMode: newSettings.mixingMode ?? activeCustomBrush.mixingMode,
          naturalPaint: newSettings.naturalPaint ?? activeCustomBrush.naturalPaint,
          amountOfPaint: newSettings.amountOfPaint ?? activeCustomBrush.amountOfPaint,
          densityOfPaint: newSettings.densityOfPaint ?? activeCustomBrush.densityOfPaint,
          colorStretch: newSettings.colorStretch ?? activeCustomBrush.colorStretch,
          wetEdge: newSettings.wetEdge ?? activeCustomBrush.wetEdge,
          wetEdgeRadius: newSettings.wetEdgeRadius ?? activeCustomBrush.wetEdgeRadius,
          textureDensity: newSettings.grain ?? activeCustomBrush.textureDensity,
          paperTextureMode: newSettings.paperTextureMode ?? activeCustomBrush.paperTextureMode,
          paperTextureScale: newSettings.paperTextureScale ?? activeCustomBrush.paperTextureScale,
          paperTextureInverted:
            newSettings.paperTextureInverted ?? activeCustomBrush.paperTextureInverted,
          dynamics: newSettings.dynamics ?? activeCustomBrush.dynamics,
        };
        setCustomBrushes((prev) =>
          prev.map((b) => (b.id === updatedBrush.id ? updatedBrush : b))
        );
        saveCustomBrushDebounced(updatedBrush);
      }
    };

    const handleUpdateDynamics = (patch: Partial<BrushDynamics>) => {
      const cur = brushSettings.dynamics || DEFAULT_BRUSH_DYNAMICS;
      handleUpdateBrushSettings({ dynamics: { ...cur, ...patch } });
    };

    const handleUpdateTaper = (patch: Partial<CspTaperSettings>) => {
      const cur = brushSettings.taper || DEFAULT_TAPER;
      handleUpdateBrushSettings({ taper: { ...cur, ...patch } });
    };

    const handleUpdateSpray = (patch: Partial<CspSpraySettings>) => {
      const cur = brushSettings.spray || DEFAULT_SPRAY;
      handleUpdateBrushSettings({ spray: { ...cur, ...patch } });
    };

    const toggleAccordion = (id: InspectorAccordionId) => {
      setOpenAccordion((prev) => (prev === id ? null : id));
    };

    if (!isBrushOrEraser) {
      if (currentTool === '3d') {
        return <Tool3DPropertyInspector />;
      }

      if (currentTool === 'fill') {
        const method = fillSettings.method ?? 'refer-all';
        const isSmartFill = method === 'enclose-and-fill' || method === 'paint-unfilled';
        const smartReferMode = fillSettings.smartReferMode ?? 'refer-reference';
        const encloseTarget = fillSettings.encloseTarget ?? 'all-enclosed';
        const paintUnfilledSize = Math.max(2, Math.min(300, Math.round(fillSettings.brushSize ?? 24)));
        return (
          <div className="p-2.5 space-y-3 overflow-y-auto flex-1">
            <div className="text-[11px] font-medium text-ui-primary">{t('Fill')}</div>
            <div className="space-y-1">
              <div className="text-[10px] uppercase tracking-wider text-ui-muted px-1 pb-0.5">
                {t('Bucket Fill')}
              </div>
              {(
                [
                  { id: 'refer-all', label: 'All Visible' },
                  { id: 'refer-active', label: 'Active Layer' },
                  { id: 'refer-reference', label: 'Reference Layer' },
                ] as const
              ).map((m) => (
                <button
                  key={m.id}
                  type="button"
                  onClick={() => toolStoreActions.updateFillSettings({ method: m.id })}
                  className={`w-full px-2 py-1 rounded-ui-sm text-left text-[11px] transition-colors cursor-pointer ${
                    method === m.id
                      ? 'bg-ui-control-active text-ui-primary font-medium'
                      : 'text-ui-secondary hover:text-ui-primary hover:bg-ui-control-hover'
                  }`}
                >
                  {t(m.label)}
                </button>
              ))}
              <div className="text-[10px] uppercase tracking-wider text-ui-muted px-1 pt-1.5 pb-0.5">
                {t('Smart Line Fill')}
              </div>
              {(
                [
                  {
                    id: 'enclose-and-fill',
                    label: 'Enclose and Fill',
                    title: 'Draw a lasso around complex line art to fill all closed areas inside without affecting the background',
                  },
                  {
                    id: 'paint-unfilled',
                    label: 'Paint Unfilled Area',
                    title: 'Brush over outlines to fill only tiny enclosed unfilled corners and crevices',
                  },
                  {
                    id: 'lasso',
                    label: 'Lasso Fill',
                    title: 'Draw a freehand shape to fill directly',
                  },
                ] as const
              ).map((m) => (
                <button
                  key={m.id}
                  type="button"
                  title={t(m.title)}
                  onClick={() => toolStoreActions.updateFillSettings({ method: m.id })}
                  className={`w-full px-2 py-1 rounded-ui-sm text-left text-[11px] transition-colors cursor-pointer ${
                    method === m.id
                      ? 'bg-ui-control-active text-ui-primary font-medium'
                      : 'text-ui-secondary hover:text-ui-primary hover:bg-ui-control-hover'
                  }`}
                >
                  {t(m.label)}
                </button>
              ))}
            </div>
            {method === 'lasso' ? (
              <div className="space-y-2.5 pt-1 border-t border-ui-subtle">
                <CompactSlider
                  label={t('Opacity')}
                  valueLabel={`${Math.round((fillSettings.opacity ?? 1) * 100)}%`}
                  min={1}
                  max={100}
                  defaultValue={100}
                  variant="opacity"
                  value={Math.round((fillSettings.opacity ?? 1) * 100)}
                  onChange={(v) => toolStoreActions.updateFillSettings({ opacity: v / 100 })}
                />
                <ToggleSwitch
                  size="xs"
                  label={t('Transparent (Erase)')}
                  checked={isTransparentColor}
                  onChange={() => toolStoreActions.toggleTransparentColor()}
                />
                <div className="text-[10px] text-ui-muted">
                  {t('Draw a closed shape on canvas to fill. Press Esc to cancel.')}
                </div>
              </div>
            ) : isSmartFill ? (
              <div className="space-y-2.5 pt-1 border-t border-ui-subtle">
                {method === 'paint-unfilled' && (
                  <CompactSlider
                    label={t('Brush Size')}
                    valueLabel={`${paintUnfilledSize}px`}
                    min={2}
                    max={300}
                    defaultValue={24}
                    variant="size"
                    logarithmic
                    value={paintUnfilledSize}
                    onChange={(v) => toolStoreActions.updateFillSettings({ brushSize: v })}
                  />
                )}
                <div className="space-y-1">
                  <div className="text-[10px] text-ui-muted">{t('Refer Source')}</div>
                  <SegmentedControl
                    size="xs"
                    fullWidth
                    aria-label={t('Refer Source')}
                    value={smartReferMode}
                    onChange={(id) => toolStoreActions.updateFillSettings({ smartReferMode: id })}
                    options={[
                      { value: 'refer-reference', label: t('Reference') },
                      { value: 'refer-all', label: t('All') },
                      { value: 'active', label: t('Active') },
                    ]}
                  />
                </div>
                {method === 'enclose-and-fill' && (
                  <div className="space-y-1">
                    <div className="text-[10px] text-ui-muted">{t('Target Area')}</div>
                    <SegmentedControl
                      size="xs"
                      fullWidth
                      aria-label={t('Target Area')}
                      value={encloseTarget}
                      onChange={(id) => toolStoreActions.updateFillSettings({ encloseTarget: id })}
                      options={[
                        { value: 'all-enclosed', label: t('All Enclosed') },
                        { value: 'unfilled-only', label: t('Unfilled Only') },
                      ]}
                    />
                  </div>
                )}
                <CompactSlider
                  label={t('Opacity')}
                  valueLabel={`${Math.round((fillSettings.opacity ?? 1) * 100)}%`}
                  min={1}
                  max={100}
                  defaultValue={100}
                  variant="opacity"
                  value={Math.round((fillSettings.opacity ?? 1) * 100)}
                  onChange={(v) => toolStoreActions.updateFillSettings({ opacity: v / 100 })}
                />
                <CompactSlider
                  label={t('Tolerance')}
                  valueLabel={`${fillSettings.tolerance ?? 32}`}
                  min={0}
                  max={100}
                  defaultValue={32}
                  value={fillSettings.tolerance ?? 32}
                  onChange={(v) => toolStoreActions.updateFillSettings({ tolerance: v })}
                />
                <CompactSlider
                  label={tc('fill', 'Close Gap')}
                  valueLabel={`${fillSettings.smartCloseGap ?? 10}px`}
                  min={0}
                  max={40}
                  defaultValue={10}
                  value={fillSettings.smartCloseGap ?? 10}
                  onChange={(v) => toolStoreActions.updateFillSettings({ smartCloseGap: v })}
                />
                <CompactSlider
                  label={t('Area Scaling')}
                  valueLabel={`${(fillSettings.smartAreaScale ?? 1) > 0 ? '+' : ''}${fillSettings.smartAreaScale ?? 1}px`}
                  min={-20}
                  max={20}
                  defaultValue={1}
                  value={fillSettings.smartAreaScale ?? 1}
                  onChange={(v) => toolStoreActions.updateFillSettings({ smartAreaScale: v })}
                />
                <ToggleSwitch
                  size="xs"
                  label={t('Anti-Alias')}
                  checked={fillSettings.antiAlias ?? true}
                  onChange={(checked) =>
                    toolStoreActions.updateFillSettings({ antiAlias: checked })
                  }
                />
                {method === 'enclose-and-fill' && (
                  <ToggleSwitch
                    size="xs"
                    label={t('Transparent (Erase)')}
                    checked={isTransparentColor}
                    onChange={() => toolStoreActions.toggleTransparentColor()}
                  />
                )}
                <div className="text-[10px] text-ui-muted">
                  {method === 'enclose-and-fill'
                    ? t('Lasso around line art (e.g. hair strands) to fill all closed areas inside without affecting the background. Press Esc to cancel.')
                    : t('Brush over outlines and tight corners to fill only tiny enclosed unfilled pixels. Press [ / ] to resize, Esc to cancel.')}
                </div>
              </div>
            ) : (
              <>
                <CompactSlider
                  label={t('Tolerance')}
                  valueLabel={`${fillSettings.tolerance ?? 32}`}
                  min={0}
                  max={100}
                  defaultValue={32}
                  value={fillSettings.tolerance ?? 32}
                  onChange={(v) => toolStoreActions.updateFillSettings({ tolerance: v })}
                />
                <CompactSlider
                  label={tc('fill', 'Close Gap')}
                  valueLabel={`${fillSettings.closeGap ?? 0}px`}
                  min={0}
                  max={20}
                  defaultValue={0}
                  value={fillSettings.closeGap ?? 0}
                  onChange={(v) => toolStoreActions.updateFillSettings({ closeGap: v })}
                />
                <CompactSlider
                  label={t('Area Scaling')}
                  valueLabel={`${(fillSettings.areaScale ?? 0) > 0 ? '+' : ''}${fillSettings.areaScale ?? 0}px`}
                  min={-20}
                  max={20}
                  defaultValue={0}
                  value={fillSettings.areaScale ?? 0}
                  onChange={(v) => toolStoreActions.updateFillSettings({ areaScale: v })}
                />
                <ToggleSwitch
                  size="xs"
                  label={t('Anti-Alias')}
                  checked={fillSettings.antiAlias ?? true}
                  onChange={(checked) =>
                    toolStoreActions.updateFillSettings({ antiAlias: checked })
                  }
                />
              </>
            )}
          </div>
        );
      }

      if (currentTool === 'gradient') {
        const resolvedStops = resolveGradientStops(gradientSettings, primaryColor, secondaryColor);
        const cssStops = (gradientSettings.reverse ? [...resolvedStops].reverse() : resolvedStops)
          .map((s) => {
            const pct = Math.round((gradientSettings.reverse ? 1 - s.offset : s.offset) * 100);
            return `rgba(${Math.round(s.r)},${Math.round(s.g)},${Math.round(s.b)},${(s.a / 255).toFixed(2)}) ${pct}%`;
          })
          .join(', ');

        const selectedMeshIndices = activeGradientMesh
          ? getSelectedMeshNodeIndices(activeGradientMesh)
          : [];
        const primarySelectedMeshIdx =
          activeGradientMesh &&
          activeGradientMesh.selectedNodeIndex !== null &&
          selectedMeshIndices.includes(activeGradientMesh.selectedNodeIndex)
            ? activeGradientMesh.selectedNodeIndex
            : selectedMeshIndices.length > 0
              ? selectedMeshIndices[0]
              : null;
        const selectedMeshNode =
          activeGradientMesh && primarySelectedMeshIdx !== null
            ? activeGradientMesh.nodes[primarySelectedMeshIdx]
            : null;
        const meshRotationDeg = Math.round(activeGradientMesh?.rotationDeg ?? 0);
        const hasMixedMeshNodeColors =
          Boolean(activeGradientMesh && selectedMeshNode && selectedMeshIndices.length > 1) &&
          selectedMeshIndices.some(
            (idx) =>
              activeGradientMesh!.nodes[idx]?.color.toLowerCase() !==
              selectedMeshNode!.color.toLowerCase()
          );
        const selectedMeshAvgOpacity =
          activeGradientMesh && selectedMeshIndices.length > 0
            ? selectedMeshIndices.reduce(
                (acc, idx) => acc + (activeGradientMesh.nodes[idx]?.opacity ?? 1),
                0
              ) / selectedMeshIndices.length
            : 1;

        return (
          <div className="p-2 space-y-3 overflow-y-auto flex-1">
            <div className="px-0.5 text-[11px] font-medium text-ui-primary">{t('Gradient')}</div>

            <SegmentedControl<GradientType>
              size="xs"
              fullWidth
              aria-label={t('Gradient Type')}
              value={gradientSettings.type}
              onChange={(gradType) => toolStoreActions.updateGradientSettings({ type: gradType })}
              options={[
                { value: 'linear', label: t('Linear') },
                { value: 'radial', label: t('Radial') },
                { value: 'mesh', label: t('Mesh') },
              ]}
            />

            {gradientSettings.type !== 'mesh' ? (
              <>
                <div
                  className="h-5 rounded-ui-sm border border-ui-default"
                  style={{
                    backgroundImage: `linear-gradient(90deg, ${cssStops}), repeating-conic-gradient(#555 0% 25%, #888 0% 50%)`,
                    backgroundSize: '100% 100%, 8px 8px',
                  }}
                />

                <div className="grid grid-cols-2 gap-1">
                  {GRADIENT_PRESETS.map((preset) => (
                    <button
                      key={preset.id}
                      type="button"
                      onClick={() =>
                        toolStoreActions.updateGradientSettings({
                          useForegroundBackground: Boolean(preset.useForegroundBackground),
                          stops: preset.stops.map((s, idx) => ({
                            id: `stop-${preset.id}-${idx}`,
                            offset: s.offset,
                            color: s.color,
                            opacity: s.opacity,
                          })),
                        })
                      }
                      className="px-1.5 py-1 rounded-ui-sm text-[10px] text-left bg-ui-input border border-ui-subtle text-ui-secondary hover:text-ui-primary hover:bg-ui-control-hover cursor-pointer truncate"
                    >
                      {td(preset.name, 'gradientPreset')}
                    </button>
                  ))}
                </div>

                <ToggleSwitch
                  size="xs"
                  label={t('Use FG / BG')}
                  checked={gradientSettings.useForegroundBackground}
                  onChange={(checked) =>
                    toolStoreActions.updateGradientSettings({
                      useForegroundBackground: checked,
                    })
                  }
                />

                {/* Color Stops Editor */}
                <div className="space-y-1.5 pt-1 border-t border-ui-subtle">
                  <div className="flex items-center justify-between text-[10px] text-ui-muted">
                    <span className="tabular-nums">
                      {t('Stops ({count})', { count: gradientSettings.stops.length })}
                    </span>
                    <button
                      type="button"
                      onClick={() => {
                        const nextStops = [
                          ...gradientSettings.stops,
                          {
                            id: `stop-${Date.now()}`,
                            offset: 0.5,
                            color: primaryColor || '#38bdf8',
                            opacity: 1,
                          },
                        ];
                        toolStoreActions.updateGradientSettings({
                          useForegroundBackground: false,
                          stops: nextStops,
                        });
                      }}
                      className="px-1.5 py-0.5 rounded-ui-xs bg-ui-control border border-ui-subtle text-ui-primary hover:bg-ui-control-hover cursor-pointer"
                    >
                      {t('+ Add')}
                    </button>
                  </div>
                  <div className="space-y-1 max-h-32 overflow-y-auto pr-0.5">
                    {gradientSettings.stops.map((stop, idx) => (
                      <div key={stop.id} className="flex items-center gap-1 text-[10px]">
                        <input
                          type="color"
                          value={stop.color}
                          onChange={(e) => {
                            const next = gradientSettings.stops.map((s, i) =>
                              i === idx ? { ...s, color: e.target.value } : s
                            );
                            toolStoreActions.updateGradientSettings({
                              useForegroundBackground: false,
                              stops: next,
                            });
                          }}
                          className="w-5 h-4 bg-transparent border-0 cursor-pointer shrink-0"
                        />
                        <ScrubSlider
                          aria-label={t('Stop {n} Position', { n: idx + 1 })}
                          size="xs"
                          hideLabel
                          hideValue
                          min={0}
                          max={100}
                          step={1}
                          value={Math.round(stop.offset * 100)}
                          onChange={(v) => {
                            const next = gradientSettings.stops.map((s, i) =>
                              i === idx ? { ...s, offset: v / 100 } : s
                            );
                            toolStoreActions.updateGradientSettings({ stops: next });
                          }}
                          className="flex-1 min-w-0"
                          title={t('Position: {pct}%', { pct: Math.round(stop.offset * 100) })}
                        />
                        <PrecisionNumberInput
                          aria-label={t('Stop {n} Opacity', { n: idx + 1 })}
                          size="xs"
                          min={0}
                          max={100}
                          step={1}
                          defaultValue={100}
                          unit="%"
                          value={Math.round(stop.opacity * 100)}
                          onChange={(v) => {
                            const next = gradientSettings.stops.map((s, i) =>
                              i === idx ? { ...s, opacity: v / 100 } : s
                            );
                            toolStoreActions.updateGradientSettings({ stops: next });
                          }}
                          className="w-14 shrink-0"
                          title={t('Stop Opacity %')}
                        />
                        {gradientSettings.stops.length > 2 && (
                          <button
                            type="button"
                            onClick={() =>
                              toolStoreActions.updateGradientSettings({
                                stops: gradientSettings.stops.filter((_, i) => i !== idx),
                              })
                            }
                            className="text-ui-muted hover:text-ui-danger px-0.5 cursor-pointer"
                            title={t('Remove Stop')}
                          >
                            ×
                          </button>
                        )}
                      </div>
                    ))}
                  </div>
                </div>

                <div className="flex items-center justify-between text-[11px]">
                  <span className="text-ui-secondary">{t('Repeat')}</span>
                  <select
                    value={gradientSettings.repeat}
                    onChange={(e) =>
                      toolStoreActions.updateGradientSettings({
                        repeat: e.target.value as GradientRepeatMode,
                      })
                    }
                    className="px-1.5 py-0.5 text-[11px] bg-ui-input border border-ui-subtle text-ui-primary rounded-ui-sm cursor-pointer"
                  >
                    <option value="clamp">{t('None')}</option>
                    <option value="repeat">{t('Repeat')}</option>
                    <option value="reflect">{t('Reflect')}</option>
                  </select>
                </div>

                <ToggleSwitch
                  size="xs"
                  label={t('Reverse')}
                  checked={gradientSettings.reverse}
                  onChange={(checked) =>
                    toolStoreActions.updateGradientSettings({ reverse: checked })
                  }
                />
              </>
            ) : (
              <div className="space-y-2 pt-1 border-t border-ui-subtle">
                <CompactSlider
                  label={t('Columns')}
                  valueLabel={`${gradientSettings.meshCols}`}
                  min={2}
                  max={6}
                  value={gradientSettings.meshCols}
                  onChange={(v) => toolStoreActions.updateGradientSettings({ meshCols: v })}
                />
                <CompactSlider
                  label={t('Rows')}
                  valueLabel={`${gradientSettings.meshRows}`}
                  min={2}
                  max={6}
                  value={gradientSettings.meshRows}
                  onChange={(v) => toolStoreActions.updateGradientSettings({ meshRows: v })}
                />

                {activeGradientMesh && (
                  <div className="space-y-1.5 p-1.5 rounded-ui-sm bg-ui-input border border-ui-subtle">
                    <CompactSlider
                      label={t('Rotate Mesh')}
                      valueLabel={`${meshRotationDeg}°`}
                      min={-180}
                      max={180}
                      value={meshRotationDeg}
                      onChange={(v) => toolStoreActions.setActiveGradientMeshRotation(v)}
                    />
                    <div className="grid grid-cols-4 gap-1">
                      {(
                        [
                          { label: '-45°', onClick: () => toolStoreActions.rotateActiveGradientMesh(-45) },
                          { label: '+45°', onClick: () => toolStoreActions.rotateActiveGradientMesh(45) },
                          { label: '+90°', onClick: () => toolStoreActions.rotateActiveGradientMesh(90) },
                          { label: '0°', onClick: () => toolStoreActions.setActiveGradientMeshRotation(0) },
                        ] as const
                      ).map((btn) => (
                        <button
                          key={btn.label}
                          type="button"
                          onClick={btn.onClick}
                          className="py-0.5 rounded-ui-xs bg-ui-control border border-ui-subtle text-ui-secondary hover:text-ui-primary hover:bg-ui-control-hover text-[10px] font-ui-mono tabular-nums cursor-pointer"
                        >
                          {btn.label}
                        </button>
                      ))}
                    </div>
                  </div>
                )}

                {activeGradientMesh && (
                  <div className="space-y-1.5 p-1.5 rounded-ui-sm bg-ui-input border border-ui-subtle">
                    <div className="flex items-center justify-between text-[10px] text-ui-muted tabular-nums">
                      <span>
                        {t('Vertices ({selected}/{total})', {
                          selected: selectedMeshIndices.length,
                          total: activeGradientMesh.nodes.length,
                        })}
                      </span>
                    </div>
                    <div className="grid grid-cols-3 gap-1">
                      <button
                        type="button"
                        onClick={() => toolStoreActions.selectAllActiveGradientMeshNodes()}
                        className="py-0.5 rounded-ui-xs bg-ui-control border border-ui-subtle text-ui-secondary hover:text-ui-primary hover:bg-ui-control-hover text-[10px] cursor-pointer"
                      >
                        {t('Select All')}
                      </button>
                      <button
                        type="button"
                        onClick={() => toolStoreActions.invertActiveGradientMeshSelection()}
                        className="py-0.5 rounded-ui-xs bg-ui-control border border-ui-subtle text-ui-secondary hover:text-ui-primary hover:bg-ui-control-hover text-[10px] cursor-pointer"
                      >
                        {t('Invert')}
                      </button>
                      <button
                        type="button"
                        onClick={() => toolStoreActions.clearActiveGradientMeshSelection()}
                        className="py-0.5 rounded-ui-xs bg-ui-control border border-ui-subtle text-ui-secondary hover:text-ui-primary hover:bg-ui-control-hover text-[10px] cursor-pointer"
                      >
                        {t('Clear')}
                      </button>
                    </div>
                    <div className="text-[9px] text-ui-muted">
                      {t('Shift+Click or drag box to multi-select vertices')}
                    </div>
                  </div>
                )}

                {selectedMeshNode && selectedMeshIndices.length > 0 && (
                  <div className="space-y-1.5 p-1.5 rounded-ui-sm bg-ui-input border border-ui-subtle">
                    <div className="flex items-center justify-between gap-1 text-[10px]">
                      <span className="text-ui-secondary truncate tabular-nums">
                        {selectedMeshIndices.length === 1
                          ? t('Node #{n}', { n: selectedMeshIndices[0] + 1 })
                          : hasMixedMeshNodeColors
                            ? t('{count} Nodes (Mixed)', { count: selectedMeshIndices.length })
                            : t('{count} Nodes', { count: selectedMeshIndices.length })}
                      </span>
                      <div className="flex items-center gap-1 shrink-0">
                        <button
                          type="button"
                          onClick={() =>
                            toolStoreActions.updateActiveGradientMeshNodes(selectedMeshIndices, {
                              color: primaryColor,
                            })
                          }
                          title={t('Apply current foreground color to selected vertices')}
                          className="px-1.5 py-0.5 rounded-ui-xs bg-ui-control border border-ui-subtle text-ui-secondary hover:text-ui-primary hover:bg-ui-control-hover text-[9px] cursor-pointer"
                        >
                          {t('Use FG')}
                        </button>
                        <input
                          type="color"
                          value={selectedMeshNode.color}
                          onChange={(e) =>
                            toolStoreActions.updateActiveGradientMeshNodes(selectedMeshIndices, {
                              color: e.target.value,
                            })
                          }
                          className="w-6 h-5 bg-transparent border-0 cursor-pointer"
                        />
                      </div>
                    </div>
                    <CompactSlider
                      label={selectedMeshIndices.length > 1 ? t('Nodes Opacity') : t('Node Opacity')}
                      valueLabel={`${Math.round(selectedMeshAvgOpacity * 100)}%`}
                      min={0}
                      max={100}
                      value={Math.round(selectedMeshAvgOpacity * 100)}
                      onChange={(v) =>
                        toolStoreActions.updateActiveGradientMeshNodes(selectedMeshIndices, {
                          opacity: v / 100,
                        })
                      }
                    />
                  </div>
                )}

                <div className="grid grid-cols-2 gap-1">
                  <button
                    type="button"
                    onClick={() => interactiveToolBridge.initGradientMesh?.()}
                    className="py-1 rounded-ui-sm bg-ui-control border border-ui-subtle text-ui-primary text-[10px] hover:bg-ui-control-hover cursor-pointer"
                  >
                    {activeGradientMesh ? t('Reset Mesh') : t('Create Mesh')}
                  </button>
                  {activeGradientMesh && (
                    <button
                      type="button"
                      onClick={() => interactiveToolBridge.applyGradientMesh?.()}
                      className="py-1 rounded-ui-sm bg-ui-accent text-ui-accent-contrast text-[10px] font-medium cursor-pointer"
                    >
                      {t('Apply (Enter)')}
                    </button>
                  )}
                </div>
                {activeGradientMesh && (
                  <button
                    type="button"
                    onClick={() => interactiveToolBridge.cancelGradientMesh?.()}
                    className="w-full py-1 rounded-ui-sm bg-ui-input border border-ui-subtle text-ui-muted hover:text-ui-primary hover:bg-ui-control-hover text-[10px] cursor-pointer"
                  >
                    {t('Cancel (Esc)')}
                  </button>
                )}
              </div>
            )}

            <div className="space-y-2 pt-1 border-t border-ui-subtle">
              <CompactSlider
                label={t('Opacity')}
                valueLabel={`${Math.round(gradientSettings.opacity * 100)}%`}
                min={5}
                max={100}
                value={Math.round(gradientSettings.opacity * 100)}
                onChange={(v) => toolStoreActions.updateGradientSettings({ opacity: v / 100 })}
              />
              <div className="flex items-center justify-between text-[11px]">
                <span className="text-ui-secondary">{t('Blend')}</span>
                <select
                  value={gradientSettings.blendMode}
                  onChange={(e) =>
                    toolStoreActions.updateGradientSettings({
                      blendMode: e.target.value as GradientBlendMode,
                    })
                  }
                  className="px-1.5 py-0.5 text-[11px] bg-ui-input border border-ui-subtle text-ui-primary rounded-ui-sm cursor-pointer"
                >
                  <option value="normal">{tc('blendMode', 'Normal')}</option>
                  <option value="multiply">{tc('blendMode', 'Multiply')}</option>
                  <option value="screen">{tc('blendMode', 'Screen')}</option>
                  <option value="overlay">{tc('blendMode', 'Overlay')}</option>
                </select>
              </div>
              <div className="pt-1 border-t border-ui-subtle">
                <PigmentBlendControl
                  label="Color Blending"
                  enabled={Boolean(gradientSettings.pigmentBlending)}
                  onEnabledChange={(enabled) =>
                    toolStoreActions.updateGradientSettings({ pigmentBlending: enabled })
                  }
                  primaryColor={primaryColor}
                  secondaryColor={secondaryColor}
                />
              </div>
              <ToggleSwitch
                size="xs"
                label={t('Dither')}
                checked={gradientSettings.dither}
                onChange={(checked) =>
                  toolStoreActions.updateGradientSettings({ dither: checked })
                }
              />
            </div>
          </div>
        );
      }

      if (currentTool === 'retouch') {
        const retouchModes: Array<{ id: RetouchMode; label: string }> = [
          { id: 'smudge', label: 'Smudge' },
          { id: 'blur', label: 'Blur' },
          { id: 'dodge', label: 'Dodge' },
          { id: 'burn', label: 'Burn' },
          { id: 'clone-stamp', label: 'Clone Stamp' },
        ];
        const strengthLabel =
          retouchSettings.mode === 'dodge' || retouchSettings.mode === 'burn'
            ? t('Exposure')
            : retouchSettings.mode === 'clone-stamp'
              ? t('Opacity')
              : t('Strength');
        return (
          <div className="p-2 space-y-3 overflow-y-auto flex-1">
            <div className="px-0.5 text-[11px] font-medium text-ui-primary">{t('Retouch')}</div>
            <div className="space-y-0.5">
              {retouchModes.map((m) => (
                <button
                  key={m.id}
                  type="button"
                  onClick={() => toolStoreActions.updateRetouchSettings({ mode: m.id })}
                  className={`w-full px-2 py-1 rounded-ui-sm text-left text-[11px] transition-colors cursor-pointer ${
                    retouchSettings.mode === m.id
                      ? 'bg-ui-control-active text-ui-primary font-medium'
                      : 'text-ui-secondary hover:text-ui-primary hover:bg-ui-control-hover'
                  }`}
                >
                  {t(m.label)}
                </button>
              ))}
            </div>

            <CompactSlider
              label={t('Size')}
              valueLabel={`${retouchSettings.size}px`}
              min={2}
              max={300}
              value={retouchSettings.size}
              onChange={(v) => toolStoreActions.updateRetouchSettings({ size: v })}
            />
            <CompactSlider
              label={strengthLabel}
              valueLabel={`${retouchSettings.strength}%`}
              min={1}
              max={100}
              value={retouchSettings.strength}
              onChange={(v) => toolStoreActions.updateRetouchSettings({ strength: v })}
            />
            <CompactSlider
              label={t('Hardness')}
              valueLabel={`${retouchSettings.hardness}%`}
              min={0}
              max={100}
              value={retouchSettings.hardness}
              onChange={(v) => toolStoreActions.updateRetouchSettings({ hardness: v })}
            />
            <CompactSlider
              label={t('Spacing')}
              valueLabel={`${Math.round(retouchSettings.spacing * 100)}%`}
              min={5}
              max={50}
              value={Math.round(retouchSettings.spacing * 100)}
              onChange={(v) => toolStoreActions.updateRetouchSettings({ spacing: v / 100 })}
            />

            <ToggleSwitch
              size="xs"
              label={t('Pressure')}
              checked={retouchSettings.usePressure}
              onChange={(checked) =>
                toolStoreActions.updateRetouchSettings({ usePressure: checked })
              }
            />

            {(retouchSettings.mode === 'smudge' || retouchSettings.mode === 'blur') && (
              <div className="space-y-2.5 pt-2 border-t border-ui-subtle">
                <PigmentBlendControl
                  label="Blending"
                  strengthLabel="Pigment Strength"
                  enabled={Boolean(retouchSettings.pigmentBlending)}
                  onEnabledChange={(enabled) =>
                    toolStoreActions.updateRetouchSettings({ pigmentBlending: enabled })
                  }
                  strength={(retouchSettings.pigmentStrength ?? 100) / 100}
                  onStrengthChange={(s) =>
                    toolStoreActions.updateRetouchSettings({
                      pigmentStrength: Math.round(s * 100),
                    })
                  }
                  primaryColor={primaryColor}
                  secondaryColor={secondaryColor}
                />

                {retouchSettings.mode === 'smudge' && (
                  <div className="pt-1.5 border-t border-ui-subtle">
                    <ToggleSwitch
                      size="xs"
                      label={t('Finger Painting')}
                      checked={retouchSettings.smudgeFingerPainting}
                      onChange={(checked) =>
                        toolStoreActions.updateRetouchSettings({
                          smudgeFingerPainting: checked,
                        })
                      }
                    />
                  </div>
                )}
              </div>
            )}

            {(retouchSettings.mode === 'dodge' || retouchSettings.mode === 'burn') && (
              <div className="space-y-2 pt-1 border-t border-ui-subtle">
                <div className="space-y-1">
                  <div className="text-[11px] text-ui-muted">{t('Range')}</div>
                  <SegmentedControl<RetouchTonalRange>
                    size="xs"
                    fullWidth
                    aria-label={t('Tonal Range')}
                    value={retouchSettings.tonalRange}
                    onChange={(r) => toolStoreActions.updateRetouchSettings({ tonalRange: r })}
                    options={[
                      { value: 'shadows', label: t('Shadows') },
                      { value: 'midtones', label: t('Mid') },
                      { value: 'highlights', label: t('High') },
                    ]}
                  />
                </div>
                <ToggleSwitch
                  size="xs"
                  label={t('Protect Tones')}
                  checked={retouchSettings.protectTones}
                  onChange={(checked) =>
                    toolStoreActions.updateRetouchSettings({ protectTones: checked })
                  }
                />
              </div>
            )}

            {retouchSettings.mode === 'clone-stamp' && (
              <div className="space-y-2 pt-1 border-t border-ui-subtle">
                <button
                  type="button"
                  onClick={() => toolStoreActions.setIsPickingCloneSource(!isPickingCloneSource)}
                  className={`w-full py-1 rounded-ui-sm text-[11px] transition-colors cursor-pointer border ${
                    isPickingCloneSource
                      ? 'bg-ui-accent text-ui-accent-contrast border-transparent font-medium'
                      : 'bg-ui-control text-ui-primary border-ui-subtle hover:bg-ui-control-hover'
                  }`}
                >
                  {isPickingCloneSource
                    ? t('Click Canvas to Set Origin...')
                    : t('Pick Source (Alt+Click)')}
                </button>
                <div className="text-[10px] font-ui-mono tabular-nums text-ui-muted">
                  {cloneSourceAnchor
                    ? t('Origin: {x}, {y}', {
                        x: Math.round(cloneSourceAnchor.x),
                        y: Math.round(cloneSourceAnchor.y),
                      })
                    : t('No source set')}
                </div>
                <ToggleSwitch
                  size="xs"
                  label={t('Aligned')}
                  checked={retouchSettings.cloneAligned}
                  onChange={(checked) =>
                    toolStoreActions.updateRetouchSettings({ cloneAligned: checked })
                  }
                />
                <div className="flex items-center justify-between text-[11px]">
                  <span className="text-ui-secondary">{t('Sample')}</span>
                  <select
                    value={retouchSettings.cloneSampleMode}
                    onChange={(e) =>
                      toolStoreActions.updateRetouchSettings({
                        cloneSampleMode: e.target.value as CloneSampleMode,
                      })
                    }
                    className="px-1.5 py-0.5 text-[11px] bg-ui-input border border-ui-subtle text-ui-primary rounded-ui-sm cursor-pointer"
                  >
                    <option value="active">{t('Active Layer')}</option>
                    <option value="all-visible">{t('All Visible')}</option>
                  </select>
                </div>
              </div>
            )}
          </div>
        );
      }

      if (currentTool === 'pen') {
        return (
          <div className="p-2 space-y-3 overflow-y-auto flex-1">
            <div className="px-0.5 text-[11px] font-medium text-ui-primary">{t('Bézier Pen')}</div>

            <SegmentedControl<PenToolMode>
              size="xs"
              fullWidth
              aria-label={t('Pen Mode')}
              value={penSettings.mode}
              onChange={(m) => toolStoreActions.updatePenSettings({ mode: m })}
              options={[
                { value: 'draw', label: t('Draw') },
                { value: 'edit', label: t('Edit Nodes') },
              ]}
            />

            <CompactSlider
              label={t('Stroke Width')}
              valueLabel={`${penSettings.strokeWidth}px`}
              min={1}
              max={100}
              defaultValue={4}
              value={penSettings.strokeWidth}
              onChange={(v) => toolStoreActions.updatePenSettings({ strokeWidth: v })}
            />
            <CompactSlider
              label={t('Opacity')}
              valueLabel={`${Math.round(penSettings.opacity * 100)}%`}
              min={5}
              max={100}
              defaultValue={100}
              value={Math.round(penSettings.opacity * 100)}
              onChange={(v) => toolStoreActions.updatePenSettings({ opacity: v / 100 })}
            />

            <div className="space-y-1.5 pt-1 border-t border-ui-subtle">
              <ToggleSwitch
                size="xs"
                label={t('Stroke Path')}
                checked={penSettings.strokeEnabled}
                onChange={(checked) =>
                  toolStoreActions.updatePenSettings({ strokeEnabled: checked })
                }
              />
              <ToggleSwitch
                size="xs"
                label={t('Fill Closed Path')}
                checked={penSettings.fillEnabled}
                onChange={(checked) =>
                  toolStoreActions.updatePenSettings({ fillEnabled: checked })
                }
              />
              {penSettings.fillEnabled && (
                <div className="space-y-1.5">
                  <SegmentedControl
                    size="xs"
                    fullWidth
                    aria-label={t('Fill Color Source')}
                    value={penSettings.fillColorMode}
                    onChange={(m) => toolStoreActions.updatePenSettings({ fillColorMode: m })}
                    options={[
                      { value: 'primary', label: t('Primary') },
                      { value: 'secondary', label: t('Sub') },
                      { value: 'custom', label: t('Custom') },
                    ]}
                  />
                  {penSettings.fillColorMode === 'custom' && (
                    <div className="flex items-center justify-between">
                      <span className="text-[10px] font-ui-mono text-ui-muted">
                        {penSettings.customFillColor}
                      </span>
                      <input
                        type="color"
                        value={penSettings.customFillColor}
                        onChange={(e) =>
                          toolStoreActions.updatePenSettings({ customFillColor: e.target.value })
                        }
                        className="w-6 h-5 bg-transparent border-0 cursor-pointer"
                      />
                    </div>
                  )}
                </div>
              )}
              <ToggleSwitch
                size="xs"
                label={t('Rubber Band')}
                checked={penSettings.rubberBandPreview}
                onChange={(checked) =>
                  toolStoreActions.updatePenSettings({ rubberBandPreview: checked })
                }
              />
            </div>

            {activePenPointCount > 0 && (
              <div className="space-y-1.5 pt-1 border-t border-ui-subtle">
                <div className="text-[10px] font-ui-mono tabular-nums text-ui-muted">
                  {activePenClosed
                    ? activePenPointCount === 1
                      ? t('Path: {count} anchor (Closed)', { count: activePenPointCount })
                      : t('Path: {count} anchors (Closed)', { count: activePenPointCount })
                    : activePenPointCount === 1
                      ? t('Path: {count} anchor', { count: activePenPointCount })
                      : t('Path: {count} anchors', { count: activePenPointCount })}
                </div>
                <div className="grid grid-cols-2 gap-1">
                  <button
                    type="button"
                    onClick={() => interactiveToolBridge.toggleClosePenPath?.()}
                    disabled={activePenPointCount < 2}
                    className="py-1 rounded-ui-sm bg-ui-control hover:bg-ui-control-hover border border-ui-subtle text-ui-primary text-[10px] disabled:opacity-40 cursor-pointer"
                  >
                    {activePenClosed ? t('Open Path') : t('Close Path')}
                  </button>
                  <button
                    type="button"
                    onClick={() => interactiveToolBridge.toggleSelectedPenAnchorSmooth?.()}
                    disabled={activePenSelectedAnchor === null}
                    className="py-1 rounded-ui-sm bg-ui-control hover:bg-ui-control-hover border border-ui-subtle text-ui-primary text-[10px] disabled:opacity-40 cursor-pointer"
                  >
                    {t('Smooth / Corner')}
                  </button>
                  <button
                    type="button"
                    onClick={() => interactiveToolBridge.deleteSelectedPenAnchor?.()}
                    className="py-1 rounded-ui-sm bg-ui-control hover:bg-ui-control-hover border border-ui-subtle text-ui-primary text-[10px] cursor-pointer"
                  >
                    {t('Delete Node')}
                  </button>
                  <button
                    type="button"
                    onClick={() => interactiveToolBridge.commitPenPath?.()}
                    disabled={activePenPointCount < 2}
                    className="py-1 rounded-ui-sm bg-ui-accent text-ui-accent-contrast text-[10px] font-medium disabled:opacity-40 cursor-pointer"
                  >
                    {t('Commit (Enter)')}
                  </button>
                </div>
                <button
                  type="button"
                  onClick={() => interactiveToolBridge.cancelPenPath?.()}
                  className="w-full py-1 rounded-ui-sm bg-ui-input border border-ui-subtle text-ui-muted hover:text-ui-primary hover:bg-ui-control-hover text-[10px] cursor-pointer"
                >
                  {t('Cancel (Esc)')}
                </button>
              </div>
            )}

            <div className="text-[10px] text-ui-muted leading-relaxed pt-1 border-t border-ui-subtle">
              {t('Click: corner · Drag: handles · Alt+Drag: break · Ctrl: edit nodes · Click curve in Edit: split')}
            </div>
          </div>
        );
      }

      if (currentTool === 'shape') {
        const openShape = isOpenShape(shapeSettings.shape);
        const shapeOptions: Array<{ id: ShapeKind; label: string }> = [
          { id: 'rectangle', label: 'Rect' },
          { id: 'rounded-rect', label: 'Rounded' },
          { id: 'ellipse', label: 'Ellipse' },
          { id: 'triangle', label: 'Triangle' },
          { id: 'polygon', label: 'Polygon' },
          { id: 'star', label: 'Star' },
          { id: 'line', label: 'Line' },
          { id: 'arrow', label: 'Arrow' },
        ];
        return (
          <div className="p-2 space-y-3 overflow-y-auto flex-1">
            <div className="px-0.5 text-[11px] font-medium text-ui-primary">
              {t('Geometric Shape')}
            </div>

            <div className="grid grid-cols-2 gap-1">
              {shapeOptions.map((opt) => (
                <button
                  key={opt.id}
                  type="button"
                  onClick={() => toolStoreActions.updateShapeSettings({ shape: opt.id })}
                  className={`px-2 py-1 rounded-ui-sm text-[11px] text-left transition-colors cursor-pointer ${
                    shapeSettings.shape === opt.id
                      ? 'bg-ui-control-active text-ui-primary font-medium'
                      : 'text-ui-secondary hover:text-ui-primary hover:bg-ui-control-hover'
                  }`}
                >
                  {t(opt.label)}
                </button>
              ))}
            </div>

            {!openShape && (
              <div className="space-y-1">
                <div className="text-[11px] text-ui-muted">{t('Style')}</div>
                <SegmentedControl<ShapeDrawMode>
                  size="xs"
                  fullWidth
                  aria-label={t('Shape Style')}
                  value={shapeSettings.mode}
                  onChange={(m) => toolStoreActions.updateShapeSettings({ mode: m })}
                  options={[
                    { value: 'stroke', label: tc('shapeDrawMode', 'Stroke') },
                    { value: 'fill', label: t('Fill') },
                    { value: 'both', label: t('Both') },
                  ]}
                />
              </div>
            )}

            {(openShape || shapeSettings.mode !== 'fill') && (
              <CompactSlider
                label={tc('shapeDrawMode', 'Stroke')}
                variant="size"
                valueLabel={`${shapeSettings.strokeWidth}px`}
                min={1}
                max={120}
                defaultValue={4}
                value={shapeSettings.strokeWidth}
                onChange={(v) => toolStoreActions.updateShapeSettings({ strokeWidth: v })}
              />
            )}

            <CompactSlider
              label={t('Opacity')}
              valueLabel={`${Math.round(shapeSettings.opacity * 100)}%`}
              min={5}
              max={100}
              defaultValue={100}
              value={Math.round(shapeSettings.opacity * 100)}
              onChange={(v) => toolStoreActions.updateShapeSettings({ opacity: v / 100 })}
            />

            {!openShape && shapeSettings.mode !== 'stroke' && (
              <div className="space-y-1.5">
                <div className="text-[11px] text-ui-muted">{t('Fill Color')}</div>
                <SegmentedControl<ShapeFillColorMode>
                  size="xs"
                  fullWidth
                  aria-label={t('Shape Fill Color')}
                  value={shapeSettings.fillColorMode}
                  onChange={(m) => toolStoreActions.updateShapeSettings({ fillColorMode: m })}
                  options={[
                    { value: 'primary', label: t('Primary') },
                    { value: 'secondary', label: t('Sub') },
                    { value: 'custom', label: t('Custom') },
                  ]}
                />
                {shapeSettings.fillColorMode === 'custom' && (
                  <div className="flex items-center justify-between">
                    <span className="text-[10px] text-ui-muted font-ui-mono">
                      {shapeSettings.customFillColor}
                    </span>
                    <input
                      type="color"
                      value={shapeSettings.customFillColor}
                      onChange={(e) =>
                        toolStoreActions.updateShapeSettings({ customFillColor: e.target.value })
                      }
                      className="w-6 h-5 bg-transparent border-0 cursor-pointer"
                    />
                  </div>
                )}
              </div>
            )}

            {shapeSettings.shape === 'rounded-rect' && (
              <CompactSlider
                label={t('Corner Radius')}
                valueLabel={`${shapeSettings.cornerRadius}px`}
                min={0}
                max={200}
                value={shapeSettings.cornerRadius}
                onChange={(v) => toolStoreActions.updateShapeSettings({ cornerRadius: v })}
              />
            )}

            {(shapeSettings.shape === 'polygon' || shapeSettings.shape === 'star') && (
              <CompactSlider
                label={shapeSettings.shape === 'star' ? t('Points') : t('Sides')}
                valueLabel={`${shapeSettings.polygonSides}`}
                min={3}
                max={12}
                value={shapeSettings.polygonSides}
                onChange={(v) => toolStoreActions.updateShapeSettings({ polygonSides: v })}
              />
            )}

            {shapeSettings.shape === 'star' && (
              <CompactSlider
                label={t('Inner Ratio')}
                valueLabel={`${Math.round(shapeSettings.starInnerRatio * 100)}%`}
                min={15}
                max={85}
                value={Math.round(shapeSettings.starInnerRatio * 100)}
                onChange={(v) => toolStoreActions.updateShapeSettings({ starInnerRatio: v / 100 })}
              />
            )}

            {(openShape || shapeSettings.mode !== 'fill') && (
              <div className="space-y-2 pt-1 border-t border-ui-subtle">
                <ToggleSwitch
                  size="xs"
                  label={t('Dashed Line')}
                  checked={shapeSettings.dashed}
                  onChange={(checked) =>
                    toolStoreActions.updateShapeSettings({ dashed: checked })
                  }
                />
                {shapeSettings.dashed && (
                  <>
                    <CompactSlider
                      label={t('Dash Length')}
                      valueLabel={`${shapeSettings.dashLength}px`}
                      min={2}
                      max={100}
                      value={shapeSettings.dashLength}
                      onChange={(v) => toolStoreActions.updateShapeSettings({ dashLength: v })}
                    />
                    <CompactSlider
                      label={t('Dash Gap')}
                      valueLabel={`${shapeSettings.dashGap}px`}
                      min={2}
                      max={100}
                      value={shapeSettings.dashGap}
                      onChange={(v) => toolStoreActions.updateShapeSettings({ dashGap: v })}
                    />
                  </>
                )}

                <div className="flex items-center justify-between text-[11px]">
                  <span className="text-ui-secondary">{t('Cap')}</span>
                  <select
                    value={shapeSettings.lineCap}
                    onChange={(e) =>
                      toolStoreActions.updateShapeSettings({
                        lineCap: e.target.value as 'round' | 'butt' | 'square',
                      })
                    }
                    className="px-1.5 py-0.5 text-[11px] bg-ui-input border border-ui-subtle text-ui-primary rounded-ui-sm cursor-pointer"
                  >
                    <option value="round">{tc('lineCap', 'Round')}</option>
                    <option value="butt">{tc('lineCap', 'Flat')}</option>
                    <option value="square">{tc('lineCap', 'Square')}</option>
                  </select>
                </div>

                {!openShape && (
                  <div className="flex items-center justify-between text-[11px]">
                    <span className="text-ui-secondary">{t('Corner')}</span>
                    <select
                      value={shapeSettings.lineJoin}
                      onChange={(e) =>
                        toolStoreActions.updateShapeSettings({
                          lineJoin: e.target.value as 'miter' | 'round' | 'bevel',
                        })
                      }
                      className="px-1.5 py-0.5 text-[11px] bg-ui-input border border-ui-subtle text-ui-primary rounded-ui-sm cursor-pointer"
                    >
                      <option value="miter">{tc('lineJoin', 'Sharp')}</option>
                      <option value="round">{tc('lineJoin', 'Round')}</option>
                      <option value="bevel">{tc('lineJoin', 'Bevel')}</option>
                    </select>
                  </div>
                )}
              </div>
            )}

            <div className="space-y-1.5 pt-1 border-t border-ui-subtle">
              <ToggleSwitch
                size="xs"
                label={t('Anti-aliasing')}
                checked={shapeSettings.antiAlias}
                onChange={(checked) =>
                  toolStoreActions.updateShapeSettings({ antiAlias: checked })
                }
              />
              <ToggleSwitch
                size="xs"
                label={t('Constrain (Shift)')}
                title={t('Lock 1:1 aspect ratio or 15° angle increments (or hold Shift while dragging)')}
                checked={shapeSettings.constrainAspect}
                onChange={(checked) =>
                  toolStoreActions.updateShapeSettings({ constrainAspect: checked })
                }
              />
              <ToggleSwitch
                size="xs"
                label={t('From Center (Alt)')}
                title={t('Draw symmetrically from center (or hold Alt while dragging)')}
                checked={shapeSettings.fromCenter}
                onChange={(checked) =>
                  toolStoreActions.updateShapeSettings({ fromCenter: checked })
                }
              />
            </div>
          </div>
        );
      }

      if (currentTool === 'liquify') {
        const activeMode = liquifySettings.mode ?? 'push';
        return (
          <div className="p-2 space-y-3 overflow-y-auto flex-1">
            <div className="px-0.5 text-[11px] font-medium text-ui-primary">{t('Liquify')}</div>
            <div className="space-y-0.5">
              {LIQUIFY_MODES.map((sub) => (
                <button
                  key={sub.id}
                  type="button"
                  onClick={() => toolStoreActions.updateLiquifySettings({ mode: sub.id })}
                  className={`w-full px-2 py-1 rounded-ui-sm text-left text-[11px] transition-colors cursor-pointer ${
                    activeMode === sub.id
                      ? 'bg-ui-control-active text-ui-primary font-medium'
                      : 'text-ui-secondary hover:text-ui-primary hover:bg-ui-control-hover'
                  }`}
                >
                  {t(sub.label)}
                </button>
              ))}
            </div>
            <CompactSlider
              label={t('Size')}
              valueLabel={`${liquifySettings.size ?? 80}px`}
              min={4}
              max={500}
              value={liquifySettings.size ?? 80}
              onChange={(v) => toolStoreActions.updateLiquifySettings({ size: v })}
            />
            <CompactSlider
              label={t('Strength')}
              valueLabel={`${liquifySettings.strength ?? 50}%`}
              min={1}
              max={100}
              value={liquifySettings.strength ?? 50}
              onChange={(v) => toolStoreActions.updateLiquifySettings({ strength: v })}
            />
            <CompactSlider
              label={t('Hardness')}
              valueLabel={`${liquifySettings.hardness ?? 50}%`}
              min={0}
              max={100}
              value={liquifySettings.hardness ?? 50}
              onChange={(v) => toolStoreActions.updateLiquifySettings({ hardness: v })}
            />
            <ToggleSwitch
              size="xs"
              label={t('Pressure')}
              checked={liquifySettings.usePressure ?? true}
              onChange={(checked) =>
                toolStoreActions.updateLiquifySettings({ usePressure: checked })
              }
            />
            <ToggleSwitch
              size="xs"
              label={t('Multi-layer')}
              title={t('Apply Liquify simultaneously to all visible unlocked layers (or multi-selected layers / active folder)')}
              checked={liquifySettings.multiLayer ?? false}
              onChange={(checked) =>
                toolStoreActions.updateLiquifySettings({ multiLayer: checked })
              }
            />
          </div>
        );
      }

      if (
        currentTool === 'select-rect' ||
        currentTool === 'select-lasso' ||
        currentTool === 'select-wand' ||
        currentTool === 'select-pen' ||
        currentTool === 'select-eraser'
      ) {
        return (
          <div className="p-2.5 space-y-3 overflow-y-auto flex-1">
            <div className="text-[11px] font-medium text-ui-primary">{t('Selection')}</div>
            <div className="grid grid-cols-2 gap-1">
              {(
                [
                  { id: 'select-rect', label: 'Rect' },
                  { id: 'select-lasso', label: 'Lasso' },
                  { id: 'select-wand', label: 'Wand' },
                  { id: 'select-pen', label: 'Pen' },
                  { id: 'select-eraser', label: 'Erase' },
                ] as const
              ).map((s) => (
                <button
                  key={s.id}
                  type="button"
                  onClick={() => toolStoreActions.selectTool(s.id)}
                  className={`py-1 px-1.5 rounded-ui-sm text-[11px] transition-colors cursor-pointer ${
                    currentTool === s.id
                      ? 'bg-ui-control-active text-ui-primary font-medium'
                      : 'text-ui-secondary hover:text-ui-primary hover:bg-ui-control-hover'
                  }`}
                >
                  {t(s.label)}
                </button>
              ))}
            </div>

            {(currentTool === 'select-pen' || currentTool === 'select-eraser') && (
              <CompactSlider
                label={t('Brush Size')}
                valueLabel={`${brushSettings.size}px`}
                min={1}
                max={250}
                value={Math.round(brushSettings.size)}
                onChange={(v) => toolStoreActions.updateBrushSettings({ size: v })}
              />
            )}

            {currentTool === 'select-wand' && (
              <div className="space-y-2.5 pt-1">
                <CompactSlider
                  label={t('Tolerance')}
                  valueLabel={`${wandSettings.tolerance}`}
                  min={0}
                  max={255}
                  value={wandSettings.tolerance}
                  onChange={(v) => toolStoreActions.updateWandSettings({ tolerance: v })}
                />
                <ToggleSwitch
                  size="xs"
                  label={t('Contiguous')}
                  checked={wandSettings.contiguous}
                  onChange={(checked) =>
                    toolStoreActions.updateWandSettings({ contiguous: checked })
                  }
                />
                <ToggleSwitch
                  size="xs"
                  label={t('Anti-Alias')}
                  checked={wandSettings.antiAlias}
                  onChange={(checked) =>
                    toolStoreActions.updateWandSettings({ antiAlias: checked })
                  }
                />
                <SegmentedControl
                  size="xs"
                  fullWidth
                  aria-label={t('Wand Refer Mode')}
                  value={wandSettings.referMode}
                  onChange={(mode) => toolStoreActions.updateWandSettings({ referMode: mode })}
                  options={[
                    { value: 'active', label: t('Active') },
                    { value: 'all', label: t('All') },
                    { value: 'reference', label: t('Ref') },
                  ]}
                />
              </div>
            )}

            <div className="space-y-1 pt-1">
              <div className="grid grid-cols-3 gap-1">
                <button
                  type="button"
                  onClick={() => onExpandSelection?.(5)}
                  title={t('Expand 5px')}
                  className="py-1 rounded-ui-sm bg-ui-input border border-ui-subtle hover:bg-ui-control-hover text-ui-muted hover:text-ui-primary flex items-center justify-center cursor-pointer"
                >
                  <Maximize2 className="w-3 h-3" />
                </button>
                <button
                  type="button"
                  onClick={() => onContractSelection?.(5)}
                  title={t('Contract 5px')}
                  className="py-1 rounded-ui-sm bg-ui-input border border-ui-subtle hover:bg-ui-control-hover text-ui-muted hover:text-ui-primary flex items-center justify-center cursor-pointer"
                >
                  <Minimize2 className="w-3 h-3" />
                </button>
                <button
                  type="button"
                  onClick={() => onFeatherSelection?.(5)}
                  title={t('Feather 5px')}
                  className="py-1 rounded-ui-sm bg-ui-input border border-ui-subtle hover:bg-ui-control-hover text-ui-muted hover:text-ui-primary flex items-center justify-center cursor-pointer"
                >
                  <Feather className="w-3 h-3" />
                </button>
              </div>
              <div className="grid grid-cols-3 gap-1 pt-1">
                <button
                  type="button"
                  onClick={onCutSelection}
                  title={t('Cut Selection (Ctrl+X)')}
                  className="py-1 rounded-ui-sm bg-ui-input border border-ui-subtle hover:bg-ui-control-hover text-[10px] text-ui-secondary hover:text-ui-primary flex items-center justify-center gap-1 cursor-pointer"
                >
                  <Scissors className="w-3 h-3" />
                  <span>{t('Cut')}</span>
                </button>
                <button
                  type="button"
                  onClick={onCopySelection}
                  title={t('Copy Selection (Ctrl+C)')}
                  className="py-1 rounded-ui-sm bg-ui-input border border-ui-subtle hover:bg-ui-control-hover text-[10px] text-ui-secondary hover:text-ui-primary flex items-center justify-center gap-1 cursor-pointer"
                >
                  <Copy className="w-3 h-3" />
                  <span>{t('Copy')}</span>
                </button>
                <button
                  type="button"
                  onClick={onPasteSelection}
                  title={t('Paste to New Layer (Ctrl+V)')}
                  className="py-1 rounded-ui-sm bg-ui-input border border-ui-subtle hover:bg-ui-control-hover text-[10px] text-ui-secondary hover:text-ui-primary flex items-center justify-center gap-1 cursor-pointer"
                >
                  <ClipboardPaste className="w-3 h-3" />
                  <span>{t('Paste')}</span>
                </button>
              </div>
              <button
                type="button"
                onClick={onMoveSelectionToNewLayer}
                title={t('Move Selected Section to New Layer (Ctrl+Shift+J)')}
                className="w-full py-1 px-2 rounded-ui-sm bg-ui-input border border-ui-subtle hover:bg-ui-control-hover text-[11px] text-ui-accent hover:text-ui-primary flex items-center gap-1.5 cursor-pointer"
              >
                <Layers className="w-3 h-3" />
                <span>{t('Move to New Layer')}</span>
              </button>
              <button
                type="button"
                onClick={onClearSelection}
                title={t('Delete Selected Section (Del)')}
                className="w-full py-1 px-2 rounded-ui-sm bg-ui-input border border-ui-subtle hover:bg-ui-control-hover text-[11px] text-ui-secondary hover:text-ui-danger flex items-center gap-1.5 cursor-pointer"
              >
                <Trash2 className="w-3 h-3" />
                <span>{t('Delete Section')}</span>
              </button>
              <button
                type="button"
                onClick={onDeleteOutsideSelection}
                title={t('Delete Outside Selected Section')}
                className="w-full py-1 px-2 rounded-ui-sm bg-ui-input border border-ui-subtle hover:bg-ui-control-hover text-[11px] text-ui-secondary hover:text-ui-danger flex items-center gap-1.5 cursor-pointer"
              >
                <Crop className="w-3 h-3" />
                <span>{t('Delete Outside')}</span>
              </button>
              <button
                type="button"
                onClick={onInvertSelection}
                className="w-full py-1 px-2 rounded-ui-sm bg-ui-input border border-ui-subtle hover:bg-ui-control-hover text-[11px] text-ui-secondary hover:text-ui-primary flex items-center gap-1.5 cursor-pointer"
              >
                <RotateCcw className="w-3 h-3" />
                <span>{t('Invert')}</span>
              </button>
              <button
                type="button"
                onClick={onTransformSelection}
                className="w-full py-1 px-2 rounded-ui-sm bg-ui-input border border-ui-subtle hover:bg-ui-control-hover text-[11px] text-ui-secondary hover:text-ui-primary flex items-center gap-1.5 cursor-pointer"
              >
                <Scaling className="w-3 h-3" />
                <span>{t('Transform')}</span>
              </button>
              <button
                type="button"
                onClick={onDeselect}
                className="w-full py-1 px-2 rounded-ui-sm bg-ui-input border border-ui-subtle hover:bg-ui-control-hover text-[11px] text-ui-secondary hover:text-ui-primary cursor-pointer text-left"
              >
                {t('Deselect')}
              </button>
            </div>
          </div>
        );
      }

      if (currentTool === 'text') {
        const fontOptions = getTextFontOptions(textSettings.fontFamily);
        return (
          <div className="p-2.5 space-y-3 overflow-y-auto flex-1">
            <div className="flex items-center justify-between gap-2">
              <span className="text-[11px] font-medium text-ui-primary">{t('Text')}</span>
              <button
                type="button"
                onClick={() => toolStoreActions.resetTextSettings()}
                title={t('Reset to plain white text without outline')}
                className="inline-flex items-center gap-1 px-1.5 py-0.5 rounded-ui-xs bg-ui-input hover:bg-ui-control-hover border border-ui-subtle text-[10px] text-ui-secondary hover:text-ui-primary cursor-pointer transition-colors"
              >
                <RotateCcw className="w-2.5 h-2.5" />
                <span>{t('Plain White')}</span>
              </button>
            </div>

            <select
              aria-label={t('Font Family')}
              value={textSettings.fontFamily}
              onFocus={() => {
                void queryInstalledSystemFonts();
              }}
              onChange={(e) => toolStoreActions.updateTextSettings({ fontFamily: e.target.value })}
              className="w-full px-2 py-1 text-[11px] bg-ui-input border border-ui-subtle text-ui-primary rounded-ui-sm cursor-pointer"
              style={{ fontFamily: textSettings.fontFamily }}
            >
              {fontOptions.map((f) => (
                <option
                  key={f.value}
                  value={f.value}
                  className="bg-ui-elevated text-ui-primary"
                  style={{ fontFamily: f.value }}
                >
                  {td(f.label)}
                </option>
              ))}
            </select>

            <SegmentedControl
              size="xs"
              fullWidth
              aria-label={t('Text Orientation')}
              value={textSettings.writingMode === 'vertical-rl' ? 'vertical-rl' : 'horizontal-tb'}
              onChange={(mode) => toolStoreActions.updateTextSettings({ writingMode: mode })}
              options={[
                { value: 'horizontal-tb', label: t('Horizontal') },
                { value: 'vertical-rl', label: t('Vertical') },
              ]}
            />

            {/* Formatting & Alignment */}
            <div className="flex items-center justify-between gap-1.5">
              <div className="flex items-center gap-0.5 bg-ui-input border border-ui-subtle p-0.5 rounded-ui-sm">
                <button
                  type="button"
                  title={t('Bold (Ctrl+B)')}
                  onClick={() => toolStoreActions.updateTextSettings({ bold: !textSettings.bold })}
                  className={`w-6 h-5 rounded-ui-xs flex items-center justify-center cursor-pointer transition-colors ${
                    textSettings.bold
                      ? 'bg-ui-control-active text-ui-accent'
                      : 'text-ui-muted hover:text-ui-primary'
                  }`}
                >
                  <Bold className="w-3 h-3" />
                </button>
                <button
                  type="button"
                  title={t('Italic (Ctrl+I)')}
                  onClick={() =>
                    toolStoreActions.updateTextSettings({ italic: !textSettings.italic })
                  }
                  className={`w-6 h-5 rounded-ui-xs flex items-center justify-center cursor-pointer transition-colors ${
                    textSettings.italic
                      ? 'bg-ui-control-active text-ui-accent'
                      : 'text-ui-muted hover:text-ui-primary'
                  }`}
                >
                  <Italic className="w-3 h-3" />
                </button>
                <button
                  type="button"
                  title={t('Underline (Ctrl+U)')}
                  onClick={() =>
                    toolStoreActions.updateTextSettings({ underline: !textSettings.underline })
                  }
                  className={`w-6 h-5 rounded-ui-xs flex items-center justify-center cursor-pointer transition-colors ${
                    textSettings.underline
                      ? 'bg-ui-control-active text-ui-accent'
                      : 'text-ui-muted hover:text-ui-primary'
                  }`}
                >
                  <Underline className="w-3 h-3" />
                </button>
              </div>

              <div className="flex items-center gap-0.5 bg-ui-input border border-ui-subtle p-0.5 rounded-ui-sm">
                {(
                  [
                    { id: 'left', title: 'Align left', icon: <AlignLeft className="w-3 h-3" /> },
                    { id: 'center', title: 'Align center', icon: <AlignCenter className="w-3 h-3" /> },
                    { id: 'right', title: 'Align right', icon: <AlignRight className="w-3 h-3" /> },
                  ] as const
                ).map((a) => (
                  <button
                    key={a.id}
                    type="button"
                    title={t(a.title)}
                    onClick={() => toolStoreActions.updateTextSettings({ align: a.id })}
                    className={`w-6 h-5 rounded-ui-xs flex items-center justify-center cursor-pointer transition-colors ${
                      textSettings.align === a.id
                        ? 'bg-ui-control-active text-ui-accent'
                        : 'text-ui-muted hover:text-ui-primary'
                    }`}
                  >
                    {a.icon}
                  </button>
                ))}
              </div>
            </div>

            <CompactSlider
              label={t('Font Size')}
              valueLabel={`${textSettings.fontSize ?? 36}px`}
              min={6}
              max={400}
              value={textSettings.fontSize ?? 36}
              onChange={(v) => toolStoreActions.updateTextSettings({ fontSize: v })}
            />
            <CompactSlider
              label={t('Line Height')}
              valueLabel={`${(textSettings.lineSpacing ?? 1.25).toFixed(2)}×`}
              min={0.7}
              max={3.0}
              step={0.05}
              value={textSettings.lineSpacing ?? 1.25}
              onChange={(v) => toolStoreActions.updateTextSettings({ lineSpacing: v })}
            />
            <CompactSlider
              label={t('Letter Spacing')}
              valueLabel={`${(textSettings.letterSpacing ?? 0).toFixed(1)}px`}
              min={-10}
              max={40}
              step={0.5}
              value={textSettings.letterSpacing ?? 0}
              onChange={(v) => toolStoreActions.updateTextSettings({ letterSpacing: v })}
            />
            <CompactSlider
              label={t('Opacity')}
              valueLabel={`${Math.round((textSettings.opacity ?? 1) * 100)}%`}
              min={5}
              max={100}
              step={1}
              value={Math.round((textSettings.opacity ?? 1) * 100)}
              onChange={(v) => toolStoreActions.updateTextSettings({ opacity: v / 100 })}
            />

            {/* Text Color */}
            <div className="space-y-1.5 pt-2 border-t border-ui-subtle">
              <div className="flex items-center justify-between text-[10px] text-ui-muted">
                <span>{t('Text Color')}</span>
                <button
                  type="button"
                  onClick={() =>
                    toolStoreActions.updateTextSettings({
                      color: useToolStore.getState().primaryColor || '#ffffff',
                    })
                  }
                  title={t('Copy current brush color')}
                  className="inline-flex items-center gap-1 px-1.5 py-0.5 rounded-ui-xs bg-ui-input hover:bg-ui-control-hover border border-ui-subtle text-[10px] text-ui-secondary hover:text-ui-primary cursor-pointer"
                >
                  <Pipette className="w-2.5 h-2.5" />
                  <span>{t('Brush')}</span>
                </button>
              </div>
              <div className="flex items-center gap-1.5 flex-wrap">
                {TEXT_QUICK_COLORS.map((swatch) => (
                  <button
                    key={swatch.hex}
                    type="button"
                    title={td(swatch.label)}
                    onClick={() => toolStoreActions.updateTextSettings({ color: swatch.hex })}
                    className={`w-5 h-5 rounded-ui-xs border cursor-pointer ${
                      (textSettings.color || '#ffffff').toLowerCase() === swatch.hex
                        ? 'border-ui-accent ring-1 ring-ui-accent-border'
                        : 'border-ui-default hover:border-ui-strong'
                    }`}
                    style={{ backgroundColor: swatch.hex }}
                  />
                ))}
                <input
                  type="color"
                  aria-label={t('Custom Text Color')}
                  value={textSettings.color || '#ffffff'}
                  onChange={(e) => toolStoreActions.updateTextSettings({ color: e.target.value })}
                  className="w-6 h-5 bg-transparent cursor-pointer border border-ui-default rounded-ui-xs"
                />
              </div>
            </div>

            {/* Optional Outline (off by default) */}
            <div className="space-y-2 pt-2 border-t border-ui-subtle">
              <label className="flex items-center justify-between text-[11px] text-ui-primary cursor-pointer">
                <span>{t('Outline')}</span>
                <input
                  type="checkbox"
                  checked={Boolean(textSettings.outline)}
                  onChange={(e) =>
                    toolStoreActions.updateTextSettings({ outline: e.target.checked })
                  }
                  className="cursor-pointer"
                />
              </label>
              {textSettings.outline && (
                <div className="space-y-2">
                  <CompactSlider
                    label={t('Outline Width')}
                    valueLabel={`${textSettings.outlineWidth ?? 3}px`}
                    min={1}
                    max={24}
                    value={textSettings.outlineWidth ?? 3}
                    onChange={(v) => toolStoreActions.updateTextSettings({ outlineWidth: v })}
                  />
                  <div className="flex items-center justify-between text-[10px] text-ui-muted">
                    <span>{t('Outline Color')}</span>
                    <input
                      type="color"
                      aria-label={t('Outline Color')}
                      value={textSettings.outlineColor || '#000000'}
                      onChange={(e) =>
                        toolStoreActions.updateTextSettings({ outlineColor: e.target.value })
                      }
                      className="w-6 h-5 bg-transparent cursor-pointer border border-ui-default rounded-ui-xs"
                    />
                  </div>
                </div>
              )}
            </div>

            <div className="text-[10px] text-ui-muted leading-relaxed pt-2 border-t border-ui-subtle space-y-0.5">
              <div>{t('• Click canvas to type, or drag to create a wrapped text box')}</div>
              <div>{t('• Click existing text to re-edit non-destructively')}</div>
              <div>{t('• Latest typography settings save automatically')}</div>
            </div>
          </div>
        );
      }

      if (currentTool === 'transform') {
        return (
          <div className="p-2.5 space-y-2.5 overflow-y-auto flex-1">
            <div className="flex items-center gap-1.5 text-[11px] font-medium text-ui-primary">
              <Scaling className="w-3.5 h-3.5 text-ui-accent" />
              <span>{t('Transform & Warp')}</span>
            </div>
            <p className="text-[10px] text-ui-muted leading-relaxed">
              {t('Use the floating transform bar on the canvas to switch between {free}, {perspective}, {mesh}, {puppet}, and {cage}.')
                .split(/(\{free\}|\{perspective\}|\{mesh\}|\{puppet\}|\{cage\})/)
                .map((part, idx) => {
                  if (part === '{free}') {
                    return (
                      <span key={idx} className="text-ui-primary">
                        {tc('transformMode', 'Free')}
                      </span>
                    );
                  }
                  if (part === '{perspective}') {
                    return (
                      <span key={idx} className="text-ui-primary">
                        {tc('transformMode', 'Perspective')}
                      </span>
                    );
                  }
                  if (part === '{mesh}') {
                    return (
                      <span key={idx} className="text-ui-primary">
                        {t('Mesh')}
                      </span>
                    );
                  }
                  if (part === '{puppet}') {
                    return (
                      <span key={idx} className="text-ui-primary">
                        {t('Puppet Warp')}
                      </span>
                    );
                  }
                  if (part === '{cage}') {
                    return (
                      <span key={idx} className="text-ui-primary">
                        {t('Cage Transform')}
                      </span>
                    );
                  }
                  return <React.Fragment key={idx}>{part}</React.Fragment>;
                })}
            </p>
            <div className="space-y-1.5 rounded-ui-sm bg-ui-input border border-ui-subtle p-2 text-[10px] text-ui-secondary">
              <div className="text-ui-primary font-medium">{t('Puppet Warp Tips')}</div>
              <div>{t('• Click artwork to place 5–6 joint pins')}</div>
              <div>{t('• Drag pins to bend arms, head, or folds')}</div>
              <div>{t('• Drag ring handle or Alt+Drag to tilt/rotate')}</div>
              <div>{t('• Right-click or Delete removes a pin')}</div>
            </div>
            <div className="space-y-1.5 rounded-ui-sm bg-ui-input border border-ui-subtle p-2 text-[10px] text-ui-secondary">
              <div className="text-ui-primary font-medium">{t('Cage Transform Tips')}</div>
              <div>{t('• Drag vertices or edges to warp smoothly')}</div>
              <div>{t('• Switch to Edit Cage to add/shape points')}</div>
              <div>{t('• Click Redraw to outline a specific region')}</div>
            </div>
            <div className="text-[10px] text-ui-muted flex items-center justify-between pt-1 border-t border-ui-subtle">
              <span>{t('Apply: Enter')}</span>
              <span>{t('Cancel: Esc')}</span>
            </div>
          </div>
        );
      }

      if (currentTool === 'object') {
        return (
          <div className="p-2.5 space-y-2.5 overflow-y-auto flex-1">
            <div className="text-[11px] font-medium text-ui-primary">{t('Object Tool')}</div>
            <p className="text-[10px] text-ui-muted leading-relaxed">
              {t('Click any non-destructive Text or Speech Balloon layer on the canvas to reopen its editor without quality loss.')}
            </p>
          </div>
        );
      }

      if (currentTool === 'frame') {
        const frameMode = frameSettings.mode ?? 'create';
        const divideMode = frameSettings.divideMode ?? 'same-folder';
        return (
          <div className="p-2.5 space-y-3 overflow-y-auto flex-1">
            <div className="text-[11px] font-medium text-ui-primary">
              {t('Frame Border Folder')}
            </div>
            <SegmentedControl
              size="xs"
              fullWidth
              aria-label={t('Frame Mode')}
              value={frameMode}
              onChange={(mode) => toolStoreActions.updateFrameSettings({ mode })}
              options={[
                { value: 'create', label: t('Create') },
                { value: 'divide', label: t('Divide') },
              ]}
            />

            {frameMode === 'divide' ? (
              <div className="space-y-2.5">
                <div className="text-[10px] text-ui-muted">{t('Divide Method')}</div>
                <div className="grid grid-cols-1 gap-1 bg-ui-input border border-ui-subtle p-0.5 rounded-ui-sm">
                  <button
                    type="button"
                    onClick={() =>
                      toolStoreActions.updateFrameSettings({ divideMode: 'same-folder' })
                    }
                    className={`py-1 px-2 rounded-ui-xs text-left text-[10px] cursor-pointer ${
                      divideMode === 'same-folder'
                        ? 'bg-ui-control-active text-ui-primary font-medium'
                        : 'text-ui-muted hover:text-ui-primary'
                    }`}
                  >
                    {t('Divide Frame Border (Same Folder)')}
                  </button>
                  <button
                    type="button"
                    onClick={() =>
                      toolStoreActions.updateFrameSettings({ divideMode: 'split-folders' })
                    }
                    className={`py-1 px-2 rounded-ui-xs text-left text-[10px] cursor-pointer ${
                      divideMode === 'split-folders'
                        ? 'bg-ui-control-active text-ui-primary font-medium'
                        : 'text-ui-muted hover:text-ui-primary'
                    }`}
                  >
                    {t('Divide Frame Folder (2 Folders)')}
                  </button>
                </div>
                <CompactSlider
                  label={t('Vert Gutter')}
                  valueLabel={`${(frameSettings.gutterVerticalMm ?? 3.0).toFixed(1)}mm`}
                  min={0.5}
                  max={20}
                  step={0.5}
                  value={frameSettings.gutterVerticalMm ?? 3.0}
                  onChange={(v) => toolStoreActions.updateFrameSettings({ gutterVerticalMm: v })}
                />
                <CompactSlider
                  label={t('Horiz Gutter')}
                  valueLabel={`${(frameSettings.gutterHorizontalMm ?? 5.0).toFixed(1)}mm`}
                  min={0.5}
                  max={25}
                  step={0.5}
                  value={frameSettings.gutterHorizontalMm ?? 5.0}
                  onChange={(v) => toolStoreActions.updateFrameSettings({ gutterHorizontalMm: v })}
                />
              </div>
            ) : (
              <>
                <CompactSlider
                  label={t('Border Width')}
                  valueLabel={`${frameSettings.thickness ?? 4}px`}
                  min={1}
                  max={100}
                  value={frameSettings.thickness ?? 4}
                  onChange={(v) => toolStoreActions.updateFrameSettings({ thickness: v })}
                />
                <CompactSlider
                  label={t('Vert Gutter')}
                  valueLabel={`${(frameSettings.gutterVerticalMm ?? 3.0).toFixed(1)}mm`}
                  min={0.5}
                  max={20}
                  step={0.5}
                  value={frameSettings.gutterVerticalMm ?? 3.0}
                  onChange={(v) => toolStoreActions.updateFrameSettings({ gutterVerticalMm: v })}
                />
                <CompactSlider
                  label={t('Horiz Gutter')}
                  valueLabel={`${(frameSettings.gutterHorizontalMm ?? 5.0).toFixed(1)}mm`}
                  min={0.5}
                  max={25}
                  step={0.5}
                  value={frameSettings.gutterHorizontalMm ?? 5.0}
                  onChange={(v) => toolStoreActions.updateFrameSettings({ gutterHorizontalMm: v })}
                />
                <SegmentedControl<'white' | 'empty'>
                  size="xs"
                  fullWidth
                  aria-label={t('Frame Background')}
                  value={frameSettings.fillBackground ? 'white' : 'empty'}
                  onChange={(v) =>
                    toolStoreActions.updateFrameSettings({ fillBackground: v === 'white' })
                  }
                  options={[
                    { value: 'white', label: t('White') },
                    { value: 'empty', label: tc('fillOption', 'Empty') },
                  ]}
                />
              </>
            )}
          </div>
        );
      }

      if (currentTool === 'balloon') {
        return (
          <div className="p-2.5 space-y-3 overflow-y-auto flex-1">
            <div className="text-[11px] font-medium text-ui-primary">{t('Balloon')}</div>
            <div className="space-y-0.5">
              {(['ellipse', 'rounded-rect', 'jagged-flash', 'thought'] as const).map((shape) => (
                <button
                  key={shape}
                  type="button"
                  onClick={() => toolStoreActions.updateBalloonSettings({ shape })}
                  className={`w-full px-2 py-1 rounded-ui-sm text-left text-[11px] capitalize cursor-pointer ${
                    balloonSettings.shape === shape
                      ? 'bg-ui-control-active text-ui-primary font-medium'
                      : 'text-ui-secondary hover:text-ui-primary hover:bg-ui-control-hover'
                  }`}
                >
                  {tc('balloonShape', shape.replace('-', ' '))}
                </button>
              ))}
            </div>
            <CompactSlider
              label={t('Border')}
              valueLabel={`${balloonSettings.strokeWidth ?? 3}px`}
              min={1}
              max={15}
              value={balloonSettings.strokeWidth ?? 3}
              onChange={(v) => toolStoreActions.updateBalloonSettings({ strokeWidth: v })}
            />
          </div>
        );
      }

      if (currentTool === 'vector-edit') {
        const activeMode = vectorEditSettings.mode || 'pinch';
        return (
          <div className="p-2.5 space-y-3 overflow-y-auto flex-1">
            <div className="text-[11px] font-medium text-ui-primary">{t('Correct Line')}</div>
            <div className="space-y-0.5">
              {(['pinch', 'width', 'simplify'] as const).map((m) => (
                <button
                  key={m}
                  type="button"
                  onClick={() => toolStoreActions.updateVectorEditSettings({ mode: m })}
                  className={`w-full px-2 py-1 rounded-ui-sm text-left text-[11px] capitalize cursor-pointer ${
                    activeMode === m
                      ? 'bg-ui-control-active text-ui-primary font-medium'
                      : 'text-ui-secondary hover:text-ui-primary hover:bg-ui-control-hover'
                  }`}
                >
                  {tc('vectorEditMode', m)}
                </button>
              ))}
            </div>
            <CompactSlider
              label={t('Radius')}
              valueLabel={`${vectorEditSettings.radius ?? 30}px`}
              min={5}
              max={150}
              value={vectorEditSettings.radius ?? 30}
              onChange={(v) => toolStoreActions.updateVectorEditSettings({ radius: v })}
            />
            {activeMode === 'pinch' && (
              <CompactSlider
                label={t('Pinch Level')}
                valueLabel={`${Math.round((vectorEditSettings.pinchStrength ?? 0.65) * 100)}%`}
                min={10}
                max={100}
                value={Math.round((vectorEditSettings.pinchStrength ?? 0.65) * 100)}
                onChange={(v) =>
                  toolStoreActions.updateVectorEditSettings({ pinchStrength: v / 100 })
                }
              />
            )}
            {activeMode === 'width' && (
              <CompactSlider
                label={t('Adjust Width')}
                valueLabel={`${(vectorEditSettings.widthFactor ?? 1.2) >= 1 ? '+' : ''}${Math.round(((vectorEditSettings.widthFactor ?? 1.2) - 1) * 100)}%`}
                min={50}
                max={200}
                value={Math.round((vectorEditSettings.widthFactor ?? 1.2) * 100)}
                onChange={(v) =>
                  toolStoreActions.updateVectorEditSettings({ widthFactor: v / 100 })
                }
              />
            )}
            {activeMode === 'simplify' && (
              <CompactSlider
                label={t('Simplify')}
                valueLabel={`${(vectorEditSettings.simplifyTolerance ?? 2.0).toFixed(1)}px`}
                min={0.5}
                max={12}
                step={0.5}
                value={vectorEditSettings.simplifyTolerance ?? 2.0}
                onChange={(v) =>
                  toolStoreActions.updateVectorEditSettings({ simplifyTolerance: v })
                }
              />
            )}
            <button
              type="button"
              onClick={() => uiStoreActions.setMangaEffectsModalOpen(true)}
              className="w-full py-1.5 px-2 rounded-ui-sm bg-ui-control border border-ui-subtle hover:bg-ui-control-hover text-[11px] text-ui-primary cursor-pointer"
            >
              {t('Effect Lines...')}
            </button>
          </div>
        );
      }

      return (
        <div className="p-2.5 text-[11px] text-ui-muted">
          <div className="text-ui-primary font-medium capitalize mb-1">
            {td(currentTool, 'tool')}
          </div>
          <p className="leading-relaxed">{t('Click or drag directly on the canvas.')}</p>
        </div>
      );
    }

    const currentAntiAlias = brushSettings.antiAlias ?? 2;
    const activeImportWarnings =
      isPaintTool(currentTool)
        ? activeCustomBrush?.importWarnings?.length
          ? activeCustomBrush.importWarnings
          : brushSettings.importWarnings?.length
            ? brushSettings.importWarnings
            : []
        : [];

    return (
      <>
        {/* Live S-Curve Stroke Preview + Quick Size/Opacity Bar */}
        <div className="shrink-0 bg-ui-header border-t border-ui-subtle px-2 py-1.5 space-y-1.5">
          <div className="flex items-center gap-1">
            <canvas ref={previewCanvasRef} className="flex-1 h-8 rounded-ui-sm bg-ui-input border border-ui-subtle block min-w-0" />
            {isPaintTool(currentTool) && (
              <button
                type="button"
                onClick={() => uiStoreActions.setBrushStudioModalOpen(true)}
                title={t('Open Brush Studio')}
                className="h-8 px-1.5 rounded-ui-sm bg-ui-control hover:bg-ui-control-hover border border-ui-subtle text-ui-secondary hover:text-ui-primary flex items-center gap-1 text-[10px] shrink-0 cursor-pointer"
              >
                <Sliders className="w-3 h-3 text-ui-accent" />
                <span className="hidden sm:inline">{t('Studio')}</span>
              </button>
            )}
          </div>
          {activeImportWarnings.length > 0 && (
            <div
              data-testid="brush-import-warnings-badge"
              className="rounded-ui-sm bg-ui-warning/10 border border-ui-warning/35 px-1.5 py-1 text-[10px] text-ui-warning"
            >
              <button
                type="button"
                onClick={() => setWarningsExpanded((v) => !v)}
                className="w-full flex items-center justify-between gap-1 text-left cursor-pointer"
                title={activeImportWarnings.join('\n')}
              >
                <span className="flex items-center gap-1 min-w-0">
                  <AlertTriangle className="w-3 h-3 text-ui-warning shrink-0" />
                  <span className="truncate font-medium tabular-nums">
                    {activeImportWarnings.length === 1
                      ? t('1 CSP import notice')
                      : t('{count} CSP import notices', { count: activeImportWarnings.length })}
                  </span>
                </span>
                {warningsExpanded ? (
                  <ChevronDown className="w-3 h-3 shrink-0 text-ui-warning" />
                ) : (
                  <ChevronRight className="w-3 h-3 shrink-0 text-ui-warning" />
                )}
              </button>
              {warningsExpanded && (
                <ul className="mt-1 space-y-1 pl-4 list-disc text-[9.5px] leading-snug text-ui-primary/90">
                  {activeImportWarnings.map((w, idx) => (
                    <li key={idx}>{w}</li>
                  ))}
                </ul>
              )}
            </div>
          )}
          <ScrubSlider
            label={t('Size')}
            variant="size"
            logarithmic
            min={0.5}
            max={500}
            step={0.5}
            defaultValue={12}
            unit="px"
            formatValue={(v) => `${v < 10 ? v.toFixed(1) : Math.round(v)}px`}
            value={brushSettings.size}
            onChange={(v) => handleUpdateBrushSettings({ size: v })}
            title={t('Brush Size ([ / ]): {size}px', {
              size: brushSettings.size < 10 ? brushSettings.size.toFixed(1) : Math.round(brushSettings.size),
            })}
          />
          <ScrubSlider
            label={t('Opacity')}
            variant="opacity"
            min={1}
            max={100}
            step={1}
            defaultValue={100}
            unit="%"
            value={Math.round((brushSettings.opacity ?? 1.0) * 100)}
            onChange={(v) => handleUpdateBrushSettings({ opacity: v / 100 })}
          />
        </div>

        {/* CSP Sub-Tool Detail Accordions */}
        <div className="shrink-0 bg-ui-panel border-t border-ui-subtle max-h-[50%] overflow-y-auto">
          {/* 1. Ink */}
          <SectionDisclosure
            title={t('Ink')}
            dense
            open={openAccordion === 'ink'}
            onToggle={() => toggleAccordion('ink')}
            summary={`${Math.round((brushSettings.flow ?? 0.85) * 100)}%`}
          >
            <ScrubSlider
              label={t('Brush Density')}
              variant="opacity"
              min={1}
              max={100}
              step={1}
              defaultValue={85}
              unit="%"
              value={Math.round((brushSettings.flow ?? 0.85) * 100)}
              onChange={(v) =>
                handleUpdateBrushSettings({ flow: v / 100, brushDensity: v / 100 })
              }
            />
            <ToggleSwitch
              size="xs"
              label={t('Adjust by Gap')}
              checked={Boolean(brushSettings.adjustDensityByGap)}
              onChange={(checked) =>
                handleUpdateBrushSettings({ adjustDensityByGap: checked })
              }
            />
            <div className="space-y-1">
              <span className="text-[10.5px] text-ui-muted">{t('Blend Tips')}</span>
              <SegmentedControl<CspBlendTipsMode>
                size="xs"
                fullWidth
                aria-label={t('Blend Tips')}
                value={brushSettings.blendTipsMode ?? 'normal'}
                onChange={(mode) => handleUpdateBrushSettings({ blendTipsMode: mode })}
                options={[
                  { value: 'normal', label: tc('blendMode', 'Normal') },
                  { value: 'darken', label: tc('blendMode', 'Darken') },
                  { value: 'compare', label: tc('textureMode', 'Compare') },
                ]}
              />
            </div>
            <div className="space-y-1">
              <span className="text-[10.5px] text-ui-muted">{t('Anti-Aliasing')}</span>
              <SegmentedControl<'0' | '1' | '2' | '3'>
                size="xs"
                fullWidth
                aria-label={t('Anti-Aliasing')}
                value={String(currentAntiAlias) as '0' | '1' | '2' | '3'}
                onChange={(val) => handleUpdateBrushSettings({ antiAlias: Number(val) as 0 | 1 | 2 | 3 })}
                options={[
                  { value: '0', label: t('None') },
                  { value: '1', label: t('Weak') },
                  { value: '2', label: t('Med') },
                  { value: '3', label: t('Strong') },
                ]}
              />
            </div>
          </SectionDisclosure>

          {/* 2. Brush Tip */}
          <SectionDisclosure
            title={t('Brush Tip')}
            dense
            open={openAccordion === 'tip'}
            onToggle={() => toggleAccordion('tip')}
            summary={`${Math.round((brushSettings.hardness ?? 1.0) * 100)}%`}
          >
            <ScrubSlider
              label={t('Hardness')}
              min={5}
              max={100}
              step={1}
              defaultValue={100}
              unit="%"
              value={Math.round((brushSettings.hardness ?? 1.0) * 100)}
              onChange={(v) => handleUpdateBrushSettings({ hardness: v / 100 })}
            />
            <ScrubSlider
              label={t('Gap (Spacing)')}
              min={1}
              max={100}
              step={1}
              defaultValue={10}
              unit="%"
              value={Math.round((brushSettings.spacing ?? 0.1) * 100)}
              onChange={(v) => handleUpdateBrushSettings({ spacing: v / 100 })}
            />
            <ScrubSlider
              label={t('Thickness')}
              min={5}
              max={100}
              step={1}
              defaultValue={100}
              unit="%"
              value={Math.round((brushSettings.thickness ?? 1.0) * 100)}
              onChange={(v) => handleUpdateBrushSettings({ thickness: v / 100 })}
            />
            <SegmentedControl<'horizontal' | 'vertical'>
              size="xs"
              fullWidth
              aria-label={t('Thickness Axis')}
              value={brushSettings.thicknessVertical ? 'vertical' : 'horizontal'}
              onChange={(axis) =>
                handleUpdateBrushSettings({ thicknessVertical: axis === 'vertical' })
              }
              options={[
                { value: 'horizontal', label: t('Horizontal') },
                { value: 'vertical', label: t('Vertical') },
              ]}
            />
            <ScrubSlider
              label={t('Angle')}
              min={0}
              max={360}
              step={1}
              defaultValue={0}
              unit="°"
              value={Math.round(brushSettings.customTipAngle ?? 0)}
              onChange={(v) => handleUpdateBrushSettings({ customTipAngle: v })}
            />
            <div className="space-y-1">
              <span className="text-[10.5px] text-ui-muted">{t('Angle Dynamics')}</span>
              <select
                value={brushSettings.customTipAngleDynamics ?? 'none'}
                onChange={(e) =>
                  handleUpdateBrushSettings({
                    customTipAngleDynamics: e.target.value as CspAngleDynamicsMode,
                    rotateCursor: undefined,
                  })
                }
                className="w-full h-6 bg-ui-input border border-ui-subtle text-ui-primary text-[10px] px-1.5 rounded-ui-sm cursor-pointer"
              >
                <option value="none">{t('None')}</option>
                <option value="direction">{t('Direction of Line')}</option>
                <option value="initial-direction">{t('Initial Direction')}</option>
                <option value="tilt">{t('Pen Tilt')}</option>
                <option value="twist">{t('Barrel Twist')}</option>
                <option value="random">{t('Random')}</option>
                <option value="direction-random">{t('Direction + Random')}</option>
              </select>
            </div>
            <ToggleSwitch
              size="xs"
              label={t('This brush rotates')}
              title={t('Rotate the brush cursor silhouette as you move to track brush direction')}
              checked={resolveBrushCursorRotationSpec(brushSettings, currentTool).enabled}
              onChange={(checked) =>
                handleUpdateBrushSettings({ rotateCursor: checked })
              }
            />
            <div className="grid grid-cols-2 gap-1.5">
              <div className="space-y-0.5">
                <span className="text-[10px] text-ui-muted">{t('Flip H')}</span>
                <select
                  value={brushSettings.flipH ?? 'none'}
                  onChange={(e) =>
                    handleUpdateBrushSettings({ flipH: e.target.value as CspTipFlipMode })
                  }
                  className="w-full h-5 bg-ui-input border border-ui-subtle text-ui-primary text-[10px] px-1 rounded-ui-sm cursor-pointer"
                >
                  <option value="none">{t('None')}</option>
                  <option value="random">{t('Random')}</option>
                  <option value="alternate">{t('Alternate')}</option>
                </select>
              </div>
              <div className="space-y-0.5">
                <span className="text-[10px] text-ui-muted">{t('Flip V')}</span>
                <select
                  value={brushSettings.flipV ?? 'none'}
                  onChange={(e) =>
                    handleUpdateBrushSettings({ flipV: e.target.value as CspTipFlipMode })
                  }
                  className="w-full h-5 bg-ui-input border border-ui-subtle text-ui-primary text-[10px] px-1 rounded-ui-sm cursor-pointer"
                >
                  <option value="none">{t('None')}</option>
                  <option value="random">{t('Random')}</option>
                  <option value="alternate">{t('Alternate')}</option>
                </select>
              </div>
            </div>
            <ToggleSwitch
              size="xs"
              label={t('Ribbon')}
              checked={Boolean(brushSettings.isRibbon)}
              onChange={(checked) => handleUpdateBrushSettings({ isRibbon: checked })}
            />
          </SectionDisclosure>

          {/* 3. Stroke & Stabilization */}
          <SectionDisclosure
            title={t('Stabilization & Stroke')}
            dense
            open={openAccordion === 'stroke'}
            onToggle={() => toggleAccordion('stroke')}
            summary={`${brushSettings.stabilization ?? 15}`}
          >
            <ScrubSlider
              label={t('Stabilization')}
              min={0}
              max={50}
              step={1}
              defaultValue={15}
              value={brushSettings.stabilization ?? 15}
              onChange={(v) => handleUpdateBrushSettings({ stabilization: v })}
            />
            <ScrubSlider
              label={t('Post-Correction')}
              min={0}
              max={5}
              step={1}
              defaultValue={0}
              value={brushSettings.postCorrection ?? 0}
              onChange={(v) => handleUpdateBrushSettings({ postCorrection: v })}
            />
            <ToggleSwitch
              size="xs"
              label={t('Sharp Angles')}
              checked={brushSettings.sharpCorners ?? true}
              onChange={(checked) =>
                handleUpdateBrushSettings({ sharpCorners: checked })
              }
            />

            <div className="grid grid-cols-2 gap-1.5">
              <ToggleSwitch
                size="xs"
                label={t('Taper In')}
                checked={Boolean(brushSettings.taper?.useIn)}
                onChange={(checked) => handleUpdateTaper({ useIn: checked })}
              />
              <ToggleSwitch
                size="xs"
                label={t('Taper Out')}
                checked={Boolean(brushSettings.taper?.useOut)}
                onChange={(checked) => handleUpdateTaper({ useOut: checked })}
              />
            </div>
            {(brushSettings.taper?.useIn || brushSettings.taper?.useOut) && (
              <ScrubSlider
                label={t('Taper Length')}
                min={4}
                max={200}
                step={1}
                defaultValue={32}
                unit="px"
                value={Math.round(brushSettings.taper?.outLength ?? 32)}
                onChange={(v) => handleUpdateTaper({ inLength: v, outLength: v })}
              />
            )}

            <ToggleSwitch
              size="xs"
              label={t('Pen Pressure')}
              checked={brushSettings.usePressure}
              onChange={(checked) =>
                handleUpdateBrushSettings({ usePressure: checked })
              }
            />
            {brushSettings.usePressure && (
              <>
                <ScrubSlider
                  label={t('Min Width')}
                  min={0}
                  max={95}
                  step={1}
                  defaultValue={0}
                  unit="%"
                  value={Math.round(brushSettings.minSizeFactor * 100)}
                  onChange={(v) => handleUpdateBrushSettings({ minSizeFactor: v / 100 })}
                />
                <div className="space-y-1">
                  <span className="text-[10px] text-ui-muted">{t('Pressure Curve')}</span>
                  <div className="grid grid-cols-5 gap-0.5 bg-ui-input border border-ui-subtle p-0.5 rounded-ui-sm">
                    {(
                      [
                        { id: 'linear', short: 'Lin' },
                        { id: 'g-pen', short: 'G' },
                        { id: 'soft', short: 'Soft' },
                        { id: 'firm', short: 'Firm' },
                        { id: 'chisel', short: 'Hard' },
                      ] as const
                    ).map((p) => (
                      <button
                        key={p.id}
                        type="button"
                        title={
                          CSP_PRESSURE_CURVE_PRESETS[p.id]?.label
                            ? td(CSP_PRESSURE_CURVE_PRESETS[p.id].label)
                            : undefined
                        }
                        onClick={() =>
                          handleUpdateBrushSettings({
                            pressureCurve: CSP_PRESSURE_CURVE_PRESETS[p.id]?.points,
                          })
                        }
                        className="py-0.5 rounded-ui-xs text-[9px] text-ui-muted hover:text-ui-primary hover:bg-ui-control-hover cursor-pointer"
                      >
                        {tc('pressureShort', p.short)}
                      </button>
                    ))}
                  </div>
                </div>
              </>
            )}

            <ToggleSwitch
              size="xs"
              label={t('Stylus Tilt')}
              checked={Boolean(brushSettings.useTilt)}
              onChange={(checked) => handleUpdateBrushSettings({ useTilt: checked })}
            />
            <ToggleSwitch
              size="xs"
              label={t('Velocity Dynamics')}
              checked={Boolean(brushSettings.useVelocity)}
              onChange={(checked) =>
                handleUpdateBrushSettings({ useVelocity: checked })
              }
            />
            <ToggleSwitch
              size="xs"
              label={t('Bezier Smoothing')}
              checked={brushSettings.smoothing}
              onChange={(checked) => handleUpdateBrushSettings({ smoothing: checked })}
            />
            <button
              type="button"
              onClick={() => {
                const def = resetBrushSettingsToDefault(
                  currentTool === 'eraser'
                    ? ERASER_PRESET_ID
                    : brushSettings.preset || DEFAULT_BRUSH_PRESET_ID,
                  customBrushes
                );
                handleUpdateBrushSettings(def);
              }}
              className="w-full py-1 rounded-ui-sm bg-ui-input border border-ui-subtle hover:bg-ui-control-hover text-[10px] text-ui-secondary hover:text-ui-primary cursor-pointer transition-colors"
            >
              {t('Reset Brush to Default')}
            </button>
          </SectionDisclosure>

          {/* 4. Color Mixing & Blending */}
          <SectionDisclosure
            title={t('Blending & Mixing')}
            dense
            open={openAccordion === 'mixing'}
            onToggle={() => toggleAccordion('mixing')}
            summary={(brushSettings.perceptualMixing ?? true) ? t('Pigment') : t('Regular')}
            summaryTone={(brushSettings.perceptualMixing ?? true) ? 'success' : 'muted'}
          >
            <PigmentBlendControl
              label="Color Blending"
              strengthLabel="Pigment Strength"
              enabled={brushSettings.perceptualMixing ?? true}
              onEnabledChange={(enabled) =>
                handleUpdateBrushSettings({
                  perceptualMixing: enabled,
                })
              }
              strength={brushSettings.naturalPaint?.pigmentMixingStrength ?? 1.0}
              onStrengthChange={(s) =>
                handleUpdateBrushSettings({
                  perceptualMixing: true,
                  naturalPaint: {
                    ...DEFAULT_NATURAL_PAINT_SETTINGS,
                    ...(brushSettings.naturalPaint || {}),
                    pigmentMixingStrength: s,
                  },
                })
              }
              primaryColor={primaryColor}
              secondaryColor={secondaryColor}
            />
            <div className="pt-1 border-t border-ui-subtle">
              <ToggleSwitch
                size="xs"
                label={t('Color Mixing')}
                checked={Boolean(brushSettings.colorMixing)}
                onChange={(enabled) => {
                  handleUpdateBrushSettings({
                    colorMixing: enabled,
                    ...(brushSettings.naturalPaint
                      ? { naturalPaint: { ...brushSettings.naturalPaint, spatialMixing: enabled } }
                      : {}),
                  });
                }}
              />
            </div>
            {brushSettings.colorMixing && (
              <>
                <SegmentedControl<'blend' | 'running_color' | 'impasto_mix' | 'smear'>
                  size="xs"
                  fullWidth
                  aria-label={t('Mixing Mode')}
                  value={brushSettings.mixingMode || 'blend'}
                  onChange={(m) => handleUpdateBrushSettings({ mixingMode: m })}
                  options={
                    brushSettings.naturalPaint?.enabled
                      ? [
                          { value: 'blend', label: tc('mixingMode', 'Blend') },
                          { value: 'running_color', label: tc('mixingMode', 'Running') },
                          { value: 'impasto_mix', label: tc('mixingMode', 'Impasto') },
                          { value: 'smear', label: tc('mixingMode', 'Smear') },
                        ]
                      : [
                          { value: 'blend', label: tc('mixingMode', 'Blend') },
                          { value: 'running_color', label: tc('mixingMode', 'Running') },
                          { value: 'smear', label: tc('mixingMode', 'Smear') },
                        ]
                  }
                />
                <ScrubSlider
                  label={t('Amount of Paint')}
                  min={0}
                  max={100}
                  step={1}
                  defaultValue={70}
                  unit="%"
                  value={Math.round(
                    (brushSettings.amountOfPaint ?? brushSettings.naturalPaint?.paintLoad ?? 0.7) *
                      100
                  )}
                  onChange={(v) => {
                    const next = v / 100;
                    handleUpdateBrushSettings({
                      amountOfPaint: next,
                      ...(brushSettings.naturalPaint
                        ? { naturalPaint: { ...brushSettings.naturalPaint, paintLoad: next } }
                        : {}),
                    });
                  }}
                />
                <ScrubSlider
                  label={t('Density of Paint')}
                  min={1}
                  max={100}
                  step={1}
                  defaultValue={80}
                  unit="%"
                  value={Math.round((brushSettings.densityOfPaint ?? 0.8) * 100)}
                  onChange={(v) => handleUpdateBrushSettings({ densityOfPaint: v / 100 })}
                />
                <ScrubSlider
                  label={t('Color Stretch')}
                  min={0}
                  max={100}
                  step={1}
                  defaultValue={60}
                  unit="%"
                  value={Math.round((brushSettings.colorStretch ?? 0.6) * 100)}
                  onChange={(v) => handleUpdateBrushSettings({ colorStretch: v / 100 })}
                />
                <ToggleSwitch
                  size="xs"
                  label={t('Optical Blur')}
                  checked={Boolean(brushSettings.useBlur)}
                  onChange={(enabled) => {
                    handleUpdateBrushSettings({
                      useBlur: enabled,
                      ...(enabled && brushSettings.blurStrength === undefined
                        ? { blurStrength: 0.35 }
                        : {}),
                    });
                  }}
                />
                {brushSettings.useBlur && (
                  <ScrubSlider
                    label={t('Blur Strength')}
                    min={5}
                    max={100}
                    step={1}
                    defaultValue={35}
                    unit="%"
                    value={Math.round((brushSettings.blurStrength ?? 0.35) * 100)}
                    onChange={(v) => handleUpdateBrushSettings({ blurStrength: v / 100 })}
                  />
                )}
              </>
            )}
            <ScrubSlider
              label={t('Watercolor Edge')}
              min={0}
              max={100}
              step={1}
              defaultValue={0}
              unit="%"
              value={Math.round((brushSettings.wetEdge ?? 0) * 100)}
              onChange={(v) => handleUpdateBrushSettings({ wetEdge: v / 100 })}
            />
            {(brushSettings.wetEdge ?? 0) > 0.01 && (
              <ScrubSlider
                label={t('Edge Width')}
                variant="size"
                min={1}
                max={20}
                step={1}
                defaultValue={4}
                unit="px"
                value={Math.round(brushSettings.wetEdgeRadius ?? 4)}
                onChange={(v) => handleUpdateBrushSettings({ wetEdgeRadius: v })}
              />
            )}
          </SectionDisclosure>

          {/* 5. Texture & Spraying Effect */}
          <SectionDisclosure
            title={t('Texture & Spray')}
            dense
            open={openAccordion === 'texture'}
            onToggle={() => toggleAccordion('texture')}
            summary={
              (brushSettings.grain ?? 0) > 0.005
                ? `${Math.round((brushSettings.grain ?? 0) * 100)}%`
                : brushSettings.spray?.enabled
                  ? t('Spray')
                  : undefined
            }
          >
            <ScrubSlider
              label={t('Texture Density')}
              min={0}
              max={100}
              step={1}
              defaultValue={0}
              unit="%"
              value={Math.round((brushSettings.grain ?? 0) * 100)}
              onChange={(v) =>
                handleUpdateBrushSettings({ grain: v / 100, textureDensity: v / 100 })
              }
            />
            {(brushSettings.grain ?? 0) > 0.005 && (
              <>
                <div className="space-y-1">
                  <span className="text-[10.5px] text-ui-muted">{t('Texture Mode')}</span>
                  <select
                    value={brushSettings.paperTextureMode ?? 'subtract'}
                    onChange={(e) =>
                      handleUpdateBrushSettings({
                        paperTextureMode: e.target.value as CspPaperTextureMode,
                      })
                    }
                    className="w-full h-6 bg-ui-input border border-ui-subtle text-ui-primary text-[10px] px-1.5 rounded-ui-sm cursor-pointer"
                  >
                    <option value="normal">{tc('blendMode', 'Normal')}</option>
                    <option value="multiply">{tc('blendMode', 'Multiply')}</option>
                    <option value="subtract">{t('Subtract (Valley Fill)')}</option>
                    <option value="compare">{tc('blendMode', 'Compare Density')}</option>
                    <option value="overlay">{tc('blendMode', 'Overlay')}</option>
                    <option value="color-burn">{tc('blendMode', 'Color Burn')}</option>
                    <option value="linear-burn">{tc('blendMode', 'Linear Burn')}</option>
                    <option value="height">{tc('textureMode', 'Height')}</option>
                    <option value="outline">{tc('textureMode', 'Outline')}</option>
                  </select>
                </div>
                <ScrubSlider
                  label={t('Texture Scale')}
                  min={10}
                  max={400}
                  step={5}
                  defaultValue={100}
                  unit="%"
                  value={Math.round((brushSettings.paperTextureScale ?? 1.0) * 100)}
                  onChange={(v) =>
                    handleUpdateBrushSettings({ paperTextureScale: v / 100 })
                  }
                />
                <ToggleSwitch
                  size="xs"
                  label={t('Invert Texture')}
                  checked={Boolean(brushSettings.paperTextureInverted)}
                  onChange={(checked) =>
                    handleUpdateBrushSettings({
                      paperTextureInverted: checked,
                    })
                  }
                />
              </>
            )}

            <div className="pt-1 border-t border-ui-subtle">
              <ToggleSwitch
                size="xs"
                label={t('Spraying Effect')}
                checked={Boolean(brushSettings.spray?.enabled)}
                onChange={(checked) => handleUpdateSpray({ enabled: checked })}
              />
            </div>
            {brushSettings.spray?.enabled && (
              <>
                <ScrubSlider
                  label={t('Particle Size')}
                  variant="size"
                  min={1}
                  max={80}
                  step={1}
                  defaultValue={4}
                  unit="px"
                  value={Math.round(brushSettings.spray.size ?? 4)}
                  onChange={(v) => handleUpdateSpray({ size: v })}
                />
                <ScrubSlider
                  label={t('Spray Density')}
                  min={1}
                  max={64}
                  step={1}
                  defaultValue={12}
                  value={Math.round(brushSettings.spray.density ?? 12)}
                  onChange={(v) => handleUpdateSpray({ density: v })}
                />
              </>
            )}
          </SectionDisclosure>

          {/* 6. Dynamics & Jitter */}
          <SectionDisclosure
            title={t('Dynamics & Jitter')}
            dense
            open={openAccordion === 'dynamics'}
            onToggle={() => toggleAccordion('dynamics')}
          >
            <ScrubSlider
              label={t('Size Jitter')}
              min={0}
              max={100}
              step={1}
              defaultValue={0}
              unit="%"
              value={Math.round((brushSettings.dynamics?.sizeJitter ?? 0) * 100)}
              onChange={(v) => handleUpdateDynamics({ sizeJitter: v / 100 })}
            />
            <ScrubSlider
              label={t('Angle Jitter')}
              min={0}
              max={100}
              step={1}
              defaultValue={0}
              unit="%"
              value={Math.round((brushSettings.dynamics?.angleJitter ?? 0) * 100)}
              onChange={(v) => handleUpdateDynamics({ angleJitter: v / 100 })}
            />
            <ScrubSlider
              label={t('Roundness Jitter')}
              min={0}
              max={95}
              step={1}
              defaultValue={0}
              unit="%"
              value={Math.round((brushSettings.dynamics?.roundnessJitter ?? 0) * 100)}
              onChange={(v) => handleUpdateDynamics({ roundnessJitter: v / 100 })}
            />
            <ScrubSlider
              label={t('Scatter')}
              min={0}
              max={5}
              step={0.1}
              defaultValue={0}
              unit="x"
              value={brushSettings.dynamics?.scatter ?? 0}
              onChange={(v) => handleUpdateDynamics({ scatter: v })}
            />
            {(brushSettings.dynamics?.scatter ?? 0) > 0 && (
              <ToggleSwitch
                size="xs"
                label={t('Scatter Both Axes')}
                checked={Boolean(brushSettings.dynamics?.scatterBothAxes)}
                onChange={(checked) =>
                  handleUpdateDynamics({ scatterBothAxes: checked })
                }
              />
            )}
            <ScrubSlider
              label={t('Count')}
              min={1}
              max={10}
              step={1}
              defaultValue={1}
              value={brushSettings.dynamics?.count ?? 1}
              onChange={(v) => handleUpdateDynamics({ count: v })}
            />
            <ScrubSlider
              label={t('Flow Jitter')}
              min={0}
              max={100}
              step={1}
              defaultValue={0}
              unit="%"
              value={Math.round((brushSettings.dynamics?.flowJitter ?? 0) * 100)}
              onChange={(v) => handleUpdateDynamics({ flowJitter: v / 100 })}
            />
            <ToggleSwitch
              size="xs"
              label={t('Color Jitter')}
              checked={Boolean(brushSettings.dynamics?.colorJitterEnabled)}
              onChange={(checked) =>
                handleUpdateDynamics({ colorJitterEnabled: checked })
              }
            />
            {brushSettings.dynamics?.colorJitterEnabled && (
              <>
                <ScrubSlider
                  label={t('Hue')}
                  variant="hue"
                  min={0}
                  max={100}
                  step={1}
                  defaultValue={0}
                  unit="%"
                  value={Math.round((brushSettings.dynamics?.hueJitter ?? 0) * 100)}
                  onChange={(v) => handleUpdateDynamics({ hueJitter: v / 100 })}
                />
                <ScrubSlider
                  label={t('Saturation')}
                  min={0}
                  max={100}
                  step={1}
                  defaultValue={0}
                  unit="%"
                  value={Math.round((brushSettings.dynamics?.saturationJitter ?? 0) * 100)}
                  onChange={(v) => handleUpdateDynamics({ saturationJitter: v / 100 })}
                />
                <ScrubSlider
                  label={t('Brightness')}
                  min={0}
                  max={100}
                  step={1}
                  defaultValue={0}
                  unit="%"
                  value={Math.round((brushSettings.dynamics?.brightnessJitter ?? 0) * 100)}
                  onChange={(v) => handleUpdateDynamics({ brightnessJitter: v / 100 })}
                />
                <ScrubSlider
                  label={t('FG / BG Mix')}
                  min={0}
                  max={100}
                  step={1}
                  defaultValue={0}
                  unit="%"
                  value={Math.round(
                    (brushSettings.dynamics?.foregroundBackgroundJitter ?? 0) * 100
                  )}
                  onChange={(v) =>
                    handleUpdateDynamics({ foregroundBackgroundJitter: v / 100 })
                  }
                />
              </>
            )}
          </SectionDisclosure>
        </div>
      </>
    );
  }
);

ToolPropertyInspector.displayName = 'ToolPropertyInspector';