Skip to content

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

60.2 KB
Raw Blame
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
import {
  AlignCenter,
  AlignLeft,
  AlignRight,
  Bold,
  Box,
  ChevronDown,
  Eraser,
  FlipHorizontal,
  FlipVertical,
  Grid3x3,
  Italic,
  Magnet,
  PaintBucket,
  Paintbrush,
  PenTool,
  Pipette,
  RotateCcw,
  Scaling,
  Search,
  Shapes,
  Sliders,
  Sparkles,
  Spline,
  SquareDashed,
  Type,
  Underline,
  Waves,
  X,
} from 'lucide-react';
import {
  BrushCategory,
  CspBrush,
  CspBrushCombineMode,
  FillMethod,
  GradientBlendMode,
  GradientRepeatMode,
  GradientType,
  LiquifyMode,
  PenToolMode,
  RetouchMode,
  ShapeDrawMode,
  ShapeKind,
  ToolType,
  isBrushLikeTool,
  isPaintTool,
} from '../types/editor';
import { ALL_BUILTIN_BRUSHES } from '../utils/presetBrushes';
import {
  DEFAULT_BRUSH_PRESET_ID,
  ERASER_PRESET_ID,
  migrateLegacyPresetId,
} from '../utils/brushPresetManager';
import {
  CUSTOM_BRUSHES_CHANGED_EVENT,
  getCachedCustomBrushes,
  loadCustomBrushes,
} from '../utils/brushStorage';
import { activateQuickBrush, resolveQuickBrush } from '../utils/quickBrushUtils';
import { getTextFontOptions, queryInstalledSystemFonts } from '../utils/textSettings';
import { Gizmo3DMode, Shading3DMode, Tool3DMode } from '../utils/tool3DRules';
import {
  store3DActions,
  toolStoreActions,
  uiStoreActions,
  use3DStore,
  useToolStore,
  useWorkspaceStore,
  workspaceStoreActions,
} from '../stores';
import { ScrubSlider } from './ui';
import { isImeComposing, useI18n } from '../i18n';

export interface ToolOptionsBarProps {
  /** Optional override to force visibility (useful in isolated tests/previews). */
  forceVisible?: boolean;
  onDeselect?: () => void;
  onTransformSelection?: () => void;
  onInvertSelection?: () => void;
  onExpandSelection?: (pixels?: number) => void;
  onFeatherSelection?: (radius?: number) => void;
  onFlipHorizontal?: () => void;
  onFlipVertical?: () => void;
  onResetRotation?: () => void;
}

const BRUSH_COMBINE_OPTIONS: ReadonlyArray<{ value: CspBrushCombineMode; label: string }> = [
  { value: 'normal', label: 'Normal' },
  { value: 'behind', label: 'Behind' },
  { value: 'clear', label: 'Clear' },
  { value: 'compare-density', label: 'Compare Density' },
  { value: 'multiply', label: 'Multiply' },
  { value: 'darken', label: 'Darken' },
  { value: 'color-burn', label: 'Color Burn' },
  { value: 'linear-burn', label: 'Linear Burn' },
  { value: 'lighten', label: 'Lighten' },
  { value: 'screen', label: 'Screen' },
  { value: 'add', label: 'Add (Glow)' },
  { value: 'color-dodge', label: 'Color Dodge' },
  { value: 'overlay', label: 'Overlay' },
  { value: 'soft-light', label: 'Soft Light' },
  { value: 'hard-light', label: 'Hard Light' },
  { value: 'vivid-light', label: 'Vivid Light' },
  { value: 'difference', label: 'Difference' },
  { value: 'hue', label: 'Hue' },
  { value: 'saturation', label: 'Saturation' },
  { value: 'color', label: 'Color' },
  { value: 'luminosity', label: 'Luminosity' },
];

const FILL_METHOD_OPTIONS: ReadonlyArray<{ value: FillMethod; label: string }> = [
  { value: 'refer-all', label: 'Refer All Layers' },
  { value: 'refer-active', label: 'Active Layer' },
  { value: 'refer-reference', label: 'Reference Layer' },
  { value: 'lasso', label: 'Lasso Fill' },
  { value: 'enclose-and-fill', label: 'Enclose & Fill' },
  { value: 'paint-unfilled', label: 'Paint Unfilled' },
];

const SHAPE_KIND_OPTIONS: ReadonlyArray<{ value: ShapeKind; label: string }> = [
  { value: 'rectangle', label: 'Rectangle' },
  { value: 'rounded-rect', label: 'Rounded Rect' },
  { value: 'ellipse', label: 'Ellipse' },
  { value: 'line', label: 'Line' },
  { value: 'triangle', label: 'Triangle' },
  { value: 'polygon', label: 'Polygon' },
  { value: 'star', label: 'Star' },
  { value: 'arrow', label: 'Arrow' },
];

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

const RETOUCH_MODE_OPTIONS: ReadonlyArray<{ value: RetouchMode; label: string }> = [
  { value: 'smudge', label: 'Smudge' },
  { value: 'blur', label: 'Blur' },
  { value: 'dodge', label: 'Dodge' },
  { value: 'burn', label: 'Burn' },
  { value: 'clone-stamp', label: 'Clone Stamp' },
];

const BRUSH_FILTER_TABS: ReadonlyArray<{ id: 'all' | BrushCategory | 'custom'; label: string }> = [
  { id: 'all', label: 'All' },
  { id: 'pen', label: 'Pen' },
  { id: 'sketch', label: 'Sketch' },
  { id: 'brush', label: 'Brush' },
  { id: 'blend', label: 'Blend' },
  { id: 'natural-paint', label: 'Paint' },
  { id: 'texture-fx', label: 'FX' },
  { id: 'custom', label: 'Custom' },
];

const BarDivider: React.FC = () => (
  <span aria-hidden="true" className="h-4 w-px bg-ui-subtle shrink-0" />
);

const ToggleChip: React.FC<{
  active: boolean;
  label: string;
  title?: string;
  icon?: React.ReactNode;
  onClick: () => void;
  'data-testid'?: string;
}> = ({ active, label, title, icon, onClick, 'data-testid': dataTestId }) => (
  <button
    type="button"
    data-testid={dataTestId}
    aria-pressed={active}
    title={title ?? label}
    onClick={onClick}
    className={`h-[22px] px-1.5 rounded-ui-xs border text-[10.5px] leading-none flex items-center gap-1 transition-colors shrink-0 cursor-pointer ${
      active
        ? 'bg-ui-control-active border-ui-accent-border text-ui-primary font-medium'
        : 'bg-ui-input border-ui-subtle text-ui-secondary hover:text-ui-primary hover:bg-ui-control-hover'
    }`}
  >
    {icon}
    <span>{label}</span>
  </button>
);

const ActionChip: React.FC<{
  label: string;
  title?: string;
  icon?: React.ReactNode;
  onClick?: () => void;
  disabled?: boolean;
  'data-testid'?: string;
}> = ({ label, title, icon, onClick, disabled = false, 'data-testid': dataTestId }) => (
  <button
    type="button"
    data-testid={dataTestId}
    disabled={disabled || !onClick}
    title={title ?? label}
    onClick={onClick}
    className={`h-[22px] px-1.5 rounded-ui-xs border text-[10.5px] leading-none flex items-center gap-1 transition-colors shrink-0 ${
      disabled || !onClick
        ? 'bg-ui-input border-ui-subtle text-ui-disabled opacity-50 cursor-not-allowed'
        : 'bg-ui-control border-ui-subtle text-ui-secondary hover:text-ui-primary hover:bg-ui-control-hover cursor-pointer'
    }`}
  >
    {icon}
    <span>{label}</span>
  </button>
);

const ToolLabelBadge: React.FC<{ icon: React.ReactNode; label: string }> = ({ icon, label }) => (
  <div className="h-[22px] px-1.5 rounded-ui-xs bg-ui-control border border-ui-subtle flex items-center gap-1 text-[10.5px] font-medium text-ui-primary shrink-0">
    <span className="text-ui-accent flex items-center">{icon}</span>
    <span>{label}</span>
  </div>
);

const compactSelectClass =
  'h-[22px] px-1.5 rounded-ui-xs bg-ui-input border border-ui-subtle hover:border-ui-default text-[10.5px] text-ui-primary outline-none cursor-pointer shrink-0';

/**
 * Brush / Eraser / Decoration contextual controls — isolated subscription so brush scrubbing
 * only updates this row and never touches Header, DockWorkspace, or Layers.
 */
const BrushOptionsSegment: React.FC<{ tool: ToolType }> = React.memo(({ tool }) => {
  const { t, tc, td } = useI18n();
  const brushSettings = useToolStore((s) => s.brushSettings);
  const activePresetId = useToolStore((s) => s.activePresetId);
  const isTransparentColor = useToolStore((s) => s.isTransparentColor);

  const [customBrushes, setCustomBrushes] = useState<CspBrush[]>(() => getCachedCustomBrushes());
  const [pickerOpen, setPickerOpen] = useState(false);
  const [pickerPos, setPickerPos] = useState<{ top: number; left: number } | null>(null);
  const [searchQuery, setSearchQuery] = useState('');
  const [filterCat, setFilterCat] = useState<'all' | BrushCategory | 'custom'>('all');

  const triggerRef = useRef<HTMLButtonElement>(null);
  const popoverRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    let active = true;
    loadCustomBrushes()
      .then((brushes) => {
        if (active) setCustomBrushes(brushes);
      })
      .catch(() => {});
    const onChanged = () => setCustomBrushes([...getCachedCustomBrushes()]);
    window.addEventListener(CUSTOM_BRUSHES_CHANGED_EVENT, onChanged);
    return () => {
      active = false;
      window.removeEventListener(CUSTOM_BRUSHES_CHANGED_EVENT, onChanged);
    };
  }, []);

  const computePopoverPosition = useCallback(() => {
    const btn = triggerRef.current;
    if (!btn || typeof window === 'undefined') return null;
    const rect = btn.getBoundingClientRect();
    const width = 264;
    const left = Math.max(8, Math.min(window.innerWidth - width - 8, rect.left));
    const top = Math.min(window.innerHeight - 120, rect.bottom + 4);
    return { top, left };
  }, []);

  useEffect(() => {
    if (!pickerOpen) return;
    const onOutside = (e: MouseEvent) => {
      const target = e.target as Node;
      if (triggerRef.current?.contains(target) || popoverRef.current?.contains(target)) return;
      setPickerOpen(false);
    };
    const onKey = (e: KeyboardEvent) => {
      if (isImeComposing(e)) return;
      if (e.key === 'Escape') setPickerOpen(false);
    };
    window.addEventListener('mousedown', onOutside);
    window.addEventListener('keydown', onKey);
    return () => {
      window.removeEventListener('mousedown', onOutside);
      window.removeEventListener('keydown', onKey);
    };
  }, [pickerOpen]);

  const isEraser = tool === 'eraser';
  const normalizedPresetId = migrateLegacyPresetId(
    isEraser ? ERASER_PRESET_ID : brushSettings.preset || activePresetId || DEFAULT_BRUSH_PRESET_ID
  );

  const activeBrushName = useMemo(() => {
    if (isEraser) return t('Eraser');
    if (brushSettings.brushName?.trim()) return td(brushSettings.brushName.trim(), 'brushName');
    const builtin = ALL_BUILTIN_BRUSHES.find((b) => b.id === normalizedPresetId);
    if (builtin) return td(builtin.name, 'brushName');
    const custom = customBrushes.find((b) => b.id === normalizedPresetId);
    if (custom) return custom.name;
    return td(String(normalizedPresetId || 'Brush'));
  }, [brushSettings.brushName, customBrushes, isEraser, normalizedPresetId, t, td]);

  const filteredBrushes = useMemo(() => {
    const q = searchQuery.trim().toLowerCase();
    const items: Array<{ id: string; name: string; category: string; isCustom?: boolean }> = [];
    for (const b of ALL_BUILTIN_BRUSHES) {
      if (filterCat !== 'all' && filterCat !== b.category) continue;
      if (
        q &&
        !b.name.toLowerCase().includes(q) &&
        !td(b.name, 'brushName').toLowerCase().includes(q) &&
        !b.category.toLowerCase().includes(q) &&
        !td(b.category, 'brushCategory').toLowerCase().includes(q)
      ) {
        continue;
      }
      items.push({ id: b.id, name: b.name, category: b.category });
    }
    if (filterCat === 'all' || filterCat === 'custom') {
      for (const cb of customBrushes) {
        if (q && !cb.name.toLowerCase().includes(q)) continue;
        items.push({ id: cb.id, name: cb.name, category: cb.category || 'custom', isCustom: true });
      }
    }
    return items;
  }, [customBrushes, filterCat, searchQuery, td]);

  const handleSelectBrushPreset = useCallback(
    (presetId: string) => {
      const resolved = resolveQuickBrush(presetId, customBrushes);
      if (resolved) {
        void activateQuickBrush(resolved, customBrushes);
      }
      setPickerOpen(false);
    },
    [customBrushes]
  );

  const sizeVal = brushSettings.size ?? 12;
  const opacityPct = Math.round((brushSettings.opacity ?? 1) * 100);
  const flowPct = Math.round((brushSettings.flow ?? brushSettings.brushDensity ?? 1) * 100);
  const stabVal = Math.round(brushSettings.stabilization ?? 0);
  const combineMode: CspBrushCombineMode = brushSettings.brushCombineMode ?? 'normal';

  return (
    <>
      {/* Active Brush Preset Popover Trigger */}
      <button
        ref={triggerRef}
        type="button"
        data-testid="tool-options-brush-picker"
        aria-expanded={pickerOpen}
        title={t('Active Brush: {name} — Click to switch preset', { name: activeBrushName })}
        onClick={() => {
          setPickerOpen((prev) => {
            if (!prev) {
              setPickerPos(computePopoverPosition());
              setSearchQuery('');
              return true;
            }
            return false;
          });
        }}
        className={`h-[22px] px-2 rounded-ui-xs border text-[10.5px] font-medium flex items-center gap-1.5 max-w-[152px] shrink-0 transition-colors cursor-pointer ${
          pickerOpen
            ? 'bg-ui-control-active border-ui-accent-border text-ui-primary'
            : 'bg-ui-control border-ui-subtle hover:border-ui-default text-ui-primary'
        }`}
      >
        {isEraser ? (
          <Eraser className="w-3 h-3 text-ui-accent shrink-0" />
        ) : (
          <Paintbrush className="w-3 h-3 text-ui-accent shrink-0" />
        )}
        <span className="truncate">{activeBrushName}</span>
        <ChevronDown className="w-3 h-3 text-ui-muted shrink-0" />
      </button>

      {pickerOpen &&
        typeof document !== 'undefined' &&
        createPortal(
          <div
            ref={popoverRef}
            data-testid="tool-options-brush-popover"
            style={{
              position: 'fixed',
              top: pickerPos?.top ?? 68,
              left: pickerPos?.left ?? 8,
            }}
            className="w-[264px] rounded-ui-md bg-ui-elevated border border-ui-default shadow-ui-popover p-1.5 z-[1000] text-[11px] text-ui-primary select-none"
          >
            <div className="relative mb-1.5">
              <Search className="w-3 h-3 text-ui-muted absolute left-2 top-1/2 -translate-y-1/2 pointer-events-none" />
              <input
                type="text"
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                placeholder={t('Search brushes...')}
                aria-label={t('Search brush presets')}
                className="w-full h-6 pl-6 pr-2 rounded-ui-xs bg-ui-input border border-ui-subtle text-[10.5px] text-ui-primary"
              />
            </div>

            <div className="flex items-center gap-0.5 overflow-x-auto no-scrollbar pb-1 mb-1 border-b border-ui-subtle">
              {BRUSH_FILTER_TABS.map((cat) => (
                <button
                  key={cat.id}
                  type="button"
                  onClick={() => setFilterCat(cat.id)}
                  className={`px-1.5 py-0.5 rounded-ui-xs text-[10px] shrink-0 cursor-pointer transition-colors ${
                    filterCat === cat.id
                      ? 'bg-ui-control-active text-ui-primary font-medium'
                      : 'text-ui-muted hover:text-ui-primary hover:bg-ui-control-hover'
                  }`}
                >
                  {t(cat.label)}
                </button>
              ))}
            </div>

            <div className="max-h-56 overflow-y-auto space-y-0.5 pr-0.5">
              {filteredBrushes.length === 0 ? (
                <div className="py-3 text-center text-[10px] text-ui-muted">
                  {t('No matching brushes')}
                </div>
              ) : (
                filteredBrushes.map((item) => {
                  const isCurrent = !isEraser && item.id === normalizedPresetId;
                  return (
                    <button
                      key={item.id}
                      type="button"
                      onClick={() => handleSelectBrushPreset(item.id)}
                      className={`w-full flex items-center justify-between gap-2 px-2 py-1 rounded-ui-xs text-left text-[10.5px] cursor-pointer transition-colors ${
                        isCurrent
                          ? 'bg-ui-control-active text-ui-primary font-medium'
                          : 'text-ui-secondary hover:bg-ui-control-hover hover:text-ui-primary'
                      }`}
                    >
                      <span className="truncate">{item.isCustom ? item.name : td(item.name, 'brushName')}</span>
                      <span className="text-[9px] uppercase font-ui-mono text-ui-muted shrink-0">
                        {item.isCustom ? t('Custom') : td(item.category, 'brushCategory')}
                      </span>
                    </button>
                  );
                })
              )}
            </div>
          </div>,
          document.body
        )}

      {/* Blend Mode (Combine Mode) */}
      {isPaintTool(tool) && (
        <>
          <BarDivider />
          <label className="flex items-center gap-1 shrink-0">
            <span className="text-[10px] text-ui-muted">{t('Mode')}</span>
            <select
              aria-label={t('Brush Blend Mode')}
              data-testid="tool-options-blend-mode"
              value={combineMode}
              onChange={(e) =>
                toolStoreActions.updateBrushSettings({
                  brushCombineMode: e.target.value as CspBrushCombineMode,
                })
              }
              className={`${compactSelectClass} max-w-[116px]`}
            >
              {BRUSH_COMBINE_OPTIONS.map((opt) => (
                <option key={opt.value} value={opt.value}>
                  {tc('blendMode', opt.label)}
                </option>
              ))}
            </select>
          </label>
        </>
      )}

      <BarDivider />

      {/* Size ScrubSlider */}
      <div className="w-[118px] shrink-0">
        <ScrubSlider
          data-testid="tool-options-size-slider"
          label={t('Size')}
          size="xs"
          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={sizeVal}
          onChange={(v) => toolStoreActions.updateBrushSettings({ size: v })}
        />
      </div>

      {/* Opacity ScrubSlider */}
      <div className="w-[104px] shrink-0">
        <ScrubSlider
          data-testid="tool-options-opacity-slider"
          label={t('Opacity')}
          size="xs"
          variant="opacity"
          min={1}
          max={100}
          step={1}
          defaultValue={100}
          unit="%"
          value={opacityPct}
          onChange={(v) => toolStoreActions.updateBrushSettings({ opacity: v / 100 })}
        />
      </div>

      {/* Flow / Ink ScrubSlider */}
      <div className="w-[96px] shrink-0">
        <ScrubSlider
          data-testid="tool-options-flow-slider"
          label={t('Flow')}
          size="xs"
          variant="opacity"
          min={1}
          max={100}
          step={1}
          defaultValue={85}
          unit="%"
          value={flowPct}
          onChange={(v) =>
            toolStoreActions.updateBrushSettings({ flow: v / 100, brushDensity: v / 100 })
          }
        />
      </div>

      {/* Stabilization ScrubSlider */}
      <div className="w-[92px] shrink-0">
        <ScrubSlider
          data-testid="tool-options-stab-slider"
          label={t('Stab')}
          size="xs"
          min={0}
          max={100}
          step={1}
          defaultValue={0}
          value={stabVal}
          onChange={(v) => toolStoreActions.updateBrushSettings({ stabilization: v })}
        />
      </div>

      <BarDivider />

      {/* Quick Ergonomic Toggles */}
      <ToggleChip
        data-testid="tool-options-pressure-toggle"
        active={Boolean(brushSettings.usePressure)}
        label={t('Pressure')}
        title={t('Toggle Stylus Pressure Sensitivity')}
        onClick={() =>
          toolStoreActions.updateBrushSettings({ usePressure: !brushSettings.usePressure })
        }
      />

      <ToggleChip
        data-testid="tool-options-smoothing-toggle"
        active={Boolean(brushSettings.smoothing)}
        label={t('Smooth')}
        title={t('Toggle Bézier Stroke Smoothing')}
        onClick={() =>
          toolStoreActions.updateBrushSettings({ smoothing: !brushSettings.smoothing })
        }
      />

      {isPaintTool(tool) && (
        <ToggleChip
          data-testid="tool-options-transparent-toggle"
          active={isTransparentColor}
          label={t('Erase Ink')}
          title={t('Paint with Transparent Ink (C)')}
          onClick={() => toolStoreActions.toggleTransparentColor()}
        />
      )}

      {/* Quick Brush Studio Trigger */}
      {isPaintTool(tool) && (
        <>
          <BarDivider />
          <ActionChip
            data-testid="tool-options-brush-studio-btn"
            icon={<Sliders className="w-3 h-3 text-ui-accent" />}
            label={t('Brush Studio')}
            title={t('Open Full Brush Studio')}
            onClick={() => uiStoreActions.setBrushStudioModalOpen(true)}
          />
        </>
      )}
    </>
  );
});
BrushOptionsSegment.displayName = 'BrushOptionsSegment';

const FillOptionsSegment: React.FC = React.memo(() => {
  const { t, tc } = useI18n();
  const fillSettings = useToolStore((s) => s.fillSettings);
  const isTransparentColor = useToolStore((s) => s.isTransparentColor);
  const method = fillSettings.method ?? 'refer-all';
  const isSmart = method === 'enclose-and-fill' || method === 'paint-unfilled';

  return (
    <>
      <ToolLabelBadge icon={<PaintBucket className="w-3 h-3" />} label={t('Fill')} />
      <select
        aria-label={t('Fill Method')}
        data-testid="tool-options-fill-method"
        value={method}
        onChange={(e) => toolStoreActions.updateFillSettings({ method: e.target.value as FillMethod })}
        className={compactSelectClass}
      >
        {FILL_METHOD_OPTIONS.map((opt) => (
          <option key={opt.value} value={opt.value}>
            {t(opt.label)}
          </option>
        ))}
      </select>

      <BarDivider />

      {method === 'paint-unfilled' && (
        <div className="w-[104px] shrink-0">
          <ScrubSlider
            label={t('Size')}
            size="xs"
            variant="size"
            logarithmic
            min={2}
            max={300}
            step={1}
            defaultValue={24}
            unit="px"
            value={fillSettings.brushSize ?? 24}
            onChange={(v) => toolStoreActions.updateFillSettings({ brushSize: v })}
          />
        </div>
      )}

      <div className="w-[102px] shrink-0">
        <ScrubSlider
          label={t('Opacity')}
          size="xs"
          variant="opacity"
          min={1}
          max={100}
          step={1}
          defaultValue={100}
          unit="%"
          value={Math.round((fillSettings.opacity ?? 1) * 100)}
          onChange={(v) => toolStoreActions.updateFillSettings({ opacity: v / 100 })}
        />
      </div>

      {method !== 'lasso' && (
        <>
          <div className="w-[100px] shrink-0">
            <ScrubSlider
              label={t('Tol')}
              size="xs"
              min={0}
              max={100}
              step={1}
              defaultValue={32}
              value={fillSettings.tolerance ?? 32}
              onChange={(v) => toolStoreActions.updateFillSettings({ tolerance: v })}
            />
          </div>

          <div className="w-[96px] shrink-0">
            <ScrubSlider
              label={t('Gap')}
              size="xs"
              min={0}
              max={isSmart ? 40 : 20}
              step={1}
              defaultValue={isSmart ? 10 : 0}
              unit="px"
              value={isSmart ? (fillSettings.smartCloseGap ?? 10) : (fillSettings.closeGap ?? 0)}
              onChange={(v) =>
                toolStoreActions.updateFillSettings(isSmart ? { smartCloseGap: v } : { closeGap: v })
              }
            />
          </div>

          <div className="w-[98px] shrink-0">
            <ScrubSlider
              label={tc('fill', 'Scale')}
              size="xs"
              min={-20}
              max={20}
              step={1}
              defaultValue={isSmart ? 1 : 0}
              unit="px"
              value={isSmart ? (fillSettings.smartAreaScale ?? 1) : (fillSettings.areaScale ?? 0)}
              onChange={(v) =>
                toolStoreActions.updateFillSettings(
                  isSmart ? { smartAreaScale: v } : { areaScale: v }
                )
              }
            />
          </div>
        </>
      )}

      <BarDivider />

      <ToggleChip
        active={fillSettings.antiAlias ?? true}
        label={t('Anti-Alias')}
        onClick={() =>
          toolStoreActions.updateFillSettings({ antiAlias: !(fillSettings.antiAlias ?? true) })
        }
      />

      {(method === 'lasso' || method === 'enclose-and-fill') && (
        <ToggleChip
          active={isTransparentColor}
          label={t('Erase')}
          onClick={() => toolStoreActions.toggleTransparentColor()}
        />
      )}
    </>
  );
});
FillOptionsSegment.displayName = 'FillOptionsSegment';

const SelectionOptionsSegment: React.FC<{
  tool: ToolType;
  onDeselect?: () => void;
  onTransformSelection?: () => void;
  onInvertSelection?: () => void;
  onExpandSelection?: (pixels?: number) => void;
  onFeatherSelection?: (radius?: number) => void;
}> = React.memo(
  ({
    tool,
    onDeselect,
    onTransformSelection,
    onInvertSelection,
    onExpandSelection,
    onFeatherSelection,
  }) => {
    const { t } = useI18n();
    const wandSettings = useToolStore((s) => s.wandSettings);
    const brushSize = useToolStore((s) => s.brushSettings.size);

    const subTools: ReadonlyArray<{ id: ToolType; label: string }> = [
      { 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' },
    ];

    return (
      <>
        <ToolLabelBadge icon={<SquareDashed className="w-3 h-3" />} label={t('Select')} />
        <div className="flex items-center gap-0.5 bg-ui-input border border-ui-subtle rounded-ui-xs p-0.5 shrink-0">
          {subTools.map((st) => (
            <button
              key={st.id}
              type="button"
              onClick={() => toolStoreActions.selectTool(st.id)}
              className={`h-[18px] px-1.5 rounded-[2px] text-[10px] transition-colors cursor-pointer ${
                tool === st.id
                  ? 'bg-ui-control-active text-ui-primary font-medium'
                  : 'text-ui-muted hover:text-ui-primary'
              }`}
            >
              {t(st.label)}
            </button>
          ))}
        </div>

        {tool === 'select-wand' && (
          <>
            <BarDivider />
            <div className="w-[104px] shrink-0">
              <ScrubSlider
                label={t('Tol')}
                size="xs"
                min={0}
                max={100}
                step={1}
                defaultValue={32}
                value={wandSettings.tolerance}
                onChange={(v) => toolStoreActions.updateWandSettings({ tolerance: v })}
              />
            </div>
            <ToggleChip
              active={wandSettings.contiguous}
              label={t('Contiguous')}
              onClick={() =>
                toolStoreActions.updateWandSettings({ contiguous: !wandSettings.contiguous })
              }
            />
            <ToggleChip
              active={wandSettings.antiAlias}
              label={t('Anti-Alias')}
              onClick={() =>
                toolStoreActions.updateWandSettings({ antiAlias: !wandSettings.antiAlias })
              }
            />
            <ToggleChip
              active={wandSettings.referMode === 'all'}
              label={wandSettings.referMode === 'all' ? t('Refer: All') : t('Refer: Active')}
              onClick={() =>
                toolStoreActions.updateWandSettings({
                  referMode: wandSettings.referMode === 'all' ? 'active' : 'all',
                })
              }
            />
          </>
        )}

        {(tool === 'select-pen' || tool === 'select-eraser') && (
          <>
            <BarDivider />
            <div className="w-[114px] shrink-0">
              <ScrubSlider
                label={t('Size')}
                size="xs"
                variant="size"
                logarithmic
                min={1}
                max={300}
                step={1}
                defaultValue={24}
                unit="px"
                value={brushSize}
                onChange={(v) => toolStoreActions.updateBrushSettings({ size: v })}
              />
            </div>
          </>
        )}

        <BarDivider />
        <ActionChip
          icon={<Scaling className="w-3 h-3" />}
          label={t('Transform')}
          title={t('Transform Selection (Ctrl+T)')}
          onClick={onTransformSelection}
        />
        <ActionChip label={t('Invert')} title={t('Invert Selection')} onClick={onInvertSelection} />
        <ActionChip
          label={t('Expand +5px')}
          title={t('Expand Selection by 5px')}
          onClick={onExpandSelection ? () => onExpandSelection(5) : undefined}
        />
        <ActionChip
          label={t('Feather')}
          title={t('Feather Selection (5px)')}
          onClick={onFeatherSelection ? () => onFeatherSelection(5) : undefined}
        />
        <ActionChip label={t('Deselect')} title={t('Deselect (Ctrl+D)')} onClick={onDeselect} />
      </>
    );
  }
);
SelectionOptionsSegment.displayName = 'SelectionOptionsSegment';

const GradientOptionsSegment: React.FC = React.memo(() => {
  const { t, tc } = useI18n();
  const gs = useToolStore((s) => s.gradientSettings);

  return (
    <>
      <ToolLabelBadge icon={<Sparkles className="w-3 h-3" />} label={t('Gradient')} />
      <div className="flex items-center gap-0.5 bg-ui-input border border-ui-subtle rounded-ui-xs p-0.5 shrink-0">
        {(['linear', 'radial', 'mesh'] as GradientType[]).map((gt) => (
          <button
            key={gt}
            type="button"
            onClick={() => toolStoreActions.updateGradientSettings({ type: gt })}
            className={`h-[18px] px-1.5 rounded-[2px] text-[10px] capitalize cursor-pointer transition-colors ${
              gs.type === gt
                ? 'bg-ui-control-active text-ui-primary font-medium'
                : 'text-ui-muted hover:text-ui-primary'
            }`}
          >
            {tc('gradientType', gt)}
          </button>
        ))}
      </div>

      <BarDivider />

      <div className="w-[104px] shrink-0">
        <ScrubSlider
          label={t('Opacity')}
          size="xs"
          variant="opacity"
          min={1}
          max={100}
          step={1}
          defaultValue={100}
          unit="%"
          value={Math.round((gs.opacity ?? 1) * 100)}
          onChange={(v) => toolStoreActions.updateGradientSettings({ opacity: v / 100 })}
        />
      </div>

      {gs.type !== 'mesh' && (
        <>
          <select
            aria-label={t('Gradient Repeat')}
            value={gs.repeat}
            onChange={(e) =>
              toolStoreActions.updateGradientSettings({
                repeat: e.target.value as GradientRepeatMode,
              })
            }
            className={compactSelectClass}
          >
            <option value="none">{t('Clamp')}</option>
            <option value="repeat">{t('Repeat')}</option>
            <option value="mirror">{t('Mirror')}</option>
          </select>

          <select
            aria-label={t('Gradient Blend Mode')}
            value={gs.blendMode}
            onChange={(e) =>
              toolStoreActions.updateGradientSettings({
                blendMode: e.target.value as GradientBlendMode,
              })
            }
            className={compactSelectClass}
          >
            <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>
            <option value="darken">{tc('blendMode', 'Darken')}</option>
            <option value="lighten">{tc('blendMode', 'Lighten')}</option>
          </select>

          <ToggleChip
            active={gs.useForegroundBackground}
            label={t('FG/BG')}
            onClick={() =>
              toolStoreActions.updateGradientSettings({
                useForegroundBackground: !gs.useForegroundBackground,
              })
            }
          />
          <ToggleChip
            active={gs.reverse}
            label={t('Reverse')}
            onClick={() => toolStoreActions.updateGradientSettings({ reverse: !gs.reverse })}
          />
          <ToggleChip
            active={gs.dither}
            label={t('Dither')}
            onClick={() => toolStoreActions.updateGradientSettings({ dither: !gs.dither })}
          />
        </>
      )}
    </>
  );
});
GradientOptionsSegment.displayName = 'GradientOptionsSegment';

const TransformOptionsSegment: React.FC<{
  tool: ToolType;
  onTransformSelection?: () => void;
  onFlipHorizontal?: () => void;
  onFlipVertical?: () => void;
  onResetRotation?: () => void;
}> = React.memo(
  ({ tool, onTransformSelection, onFlipHorizontal, onFlipVertical, onResetRotation }) => {
    const { t } = useI18n();
    return (
      <>
        <ToolLabelBadge
          icon={<Scaling className="w-3 h-3" />}
          label={tool === 'object' ? t('Object') : t('Transform')}
        />
        <ActionChip
          icon={<Scaling className="w-3 h-3 text-ui-accent" />}
          label={t('Free Transform')}
          title={t('Start Free Transform (Ctrl+T)')}
          onClick={onTransformSelection}
        />
        <BarDivider />
        <ActionChip
          icon={<FlipHorizontal className="w-3 h-3" />}
          label={t('Flip View H')}
          onClick={onFlipHorizontal}
        />
        <ActionChip
          icon={<FlipVertical className="w-3 h-3" />}
          label={t('Flip View V')}
          onClick={onFlipVertical}
        />
        <ActionChip
          icon={<RotateCcw className="w-3 h-3" />}
          label={t('Reset Angle')}
          onClick={onResetRotation}
        />
        <span className="text-[10px] text-ui-muted pl-1">
          {t('Shift: keep aspect · Enter: apply · Esc: cancel')}
        </span>
      </>
    );
  }
);
TransformOptionsSegment.displayName = 'TransformOptionsSegment';

const TextOptionsSegment: React.FC = React.memo(() => {
  const { t } = useI18n();
  const ts = useToolStore((s) => s.textSettings);
  const [systemFonts, setSystemFonts] = useState<string[]>([]);
  const fontOptions = useMemo(
    () => getTextFontOptions(ts.fontFamily, systemFonts),
    [ts.fontFamily, systemFonts]
  );

  const handleLoadSystemFonts = useCallback(() => {
    if (systemFonts.length > 0) return;
    void queryInstalledSystemFonts().then((fonts) => {
      if (fonts.length > 0) setSystemFonts(fonts);
    });
  }, [systemFonts.length]);

  return (
    <>
      <ToolLabelBadge icon={<Type className="w-3 h-3" />} label={t('Text')} />
      <select
        aria-label={t('Font Family')}
        value={ts.fontFamily}
        onFocus={handleLoadSystemFonts}
        onChange={(e) => toolStoreActions.updateTextSettings({ fontFamily: e.target.value })}
        className={`${compactSelectClass} max-w-[144px]`}
        style={{ fontFamily: ts.fontFamily }}
      >
        {fontOptions.map((f) => (
          <option key={f.value} value={f.value} style={{ fontFamily: f.value }}>
            {f.label}
          </option>
        ))}
      </select>

      <div className="w-[100px] shrink-0">
        <ScrubSlider
          label={t('Size')}
          size="xs"
          min={6}
          max={400}
          step={1}
          defaultValue={36}
          unit="px"
          value={ts.fontSize}
          onChange={(v) => toolStoreActions.updateTextSettings({ fontSize: v })}
        />
      </div>

      <label
        title={t('Text Color ({color})', { color: ts.color || '#ffffff' })}
        className="w-[22px] h-[22px] rounded-ui-xs border border-ui-subtle hover:border-ui-strong bg-ui-input flex items-center justify-center cursor-pointer shrink-0 overflow-hidden"
      >
        <input
          type="color"
          aria-label={t('Text Color')}
          value={ts.color || '#ffffff'}
          onChange={(e) => toolStoreActions.updateTextSettings({ color: e.target.value })}
          className="w-6 h-6 p-0 border-0 bg-transparent cursor-pointer"
        />
      </label>

      <div className="w-[92px] shrink-0">
        <ScrubSlider
          label={t('Lead')}
          size="xs"
          min={0.7}
          max={3.0}
          step={0.05}
          defaultValue={1.25}
          value={ts.lineSpacing ?? 1.25}
          onChange={(v) => toolStoreActions.updateTextSettings({ lineSpacing: v })}
        />
      </div>

      <div className="w-[92px] shrink-0">
        <ScrubSlider
          label={t('Track')}
          size="xs"
          min={-10}
          max={40}
          step={0.5}
          defaultValue={0}
          unit="px"
          value={ts.letterSpacing ?? 0}
          onChange={(v) => toolStoreActions.updateTextSettings({ letterSpacing: v })}
        />
      </div>

      <BarDivider />

      <ToggleChip
        active={ts.bold}
        label=""
        title={t('Bold (Ctrl+B)')}
        icon={<Bold className="w-3 h-3" />}
        onClick={() => toolStoreActions.updateTextSettings({ bold: !ts.bold })}
      />
      <ToggleChip
        active={ts.italic}
        label=""
        title={t('Italic (Ctrl+I)')}
        icon={<Italic className="w-3 h-3" />}
        onClick={() => toolStoreActions.updateTextSettings({ italic: !ts.italic })}
      />
      <ToggleChip
        active={Boolean(ts.underline)}
        label=""
        title={t('Underline (Ctrl+U)')}
        icon={<Underline className="w-3 h-3" />}
        onClick={() => toolStoreActions.updateTextSettings({ underline: !ts.underline })}
      />

      <div className="flex items-center gap-0.5 bg-ui-input border border-ui-subtle rounded-ui-xs p-0.5 shrink-0">
        {(
          [
            { 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-5 h-[18px] rounded-[2px] flex items-center justify-center cursor-pointer transition-colors ${
              ts.align === a.id
                ? 'bg-ui-control-active text-ui-accent'
                : 'text-ui-muted hover:text-ui-primary'
            }`}
          >
            {a.icon}
          </button>
        ))}
      </div>

      <ToggleChip
        active={ts.writingMode === 'vertical-rl'}
        label={ts.writingMode === 'vertical-rl' ? t('Vert') : t('Horiz')}
        title={t('Toggle Horizontal / Vertical Writing Mode')}
        onClick={() =>
          toolStoreActions.updateTextSettings({
            writingMode: ts.writingMode === 'vertical-rl' ? 'horizontal-tb' : 'vertical-rl',
          })
        }
      />

      <BarDivider />

      <ToggleChip
        active={ts.outline}
        label={t('Outline')}
        onClick={() => toolStoreActions.updateTextSettings({ outline: !ts.outline })}
      />
      {ts.outline && (
        <>
          <div className="w-[88px] shrink-0">
            <ScrubSlider
              label={t('Width')}
              size="xs"
              min={1}
              max={24}
              step={1}
              defaultValue={3}
              unit="px"
              value={ts.outlineWidth}
              onChange={(v) => toolStoreActions.updateTextSettings({ outlineWidth: v })}
            />
          </div>
          <label
            title={t('Outline Color ({color})', { color: ts.outlineColor || '#000000' })}
            className="w-[22px] h-[22px] rounded-ui-xs border border-ui-subtle hover:border-ui-strong bg-ui-input flex items-center justify-center cursor-pointer shrink-0 overflow-hidden"
          >
            <input
              type="color"
              aria-label={t('Outline Color')}
              value={ts.outlineColor || '#000000'}
              onChange={(e) => toolStoreActions.updateTextSettings({ outlineColor: e.target.value })}
              className="w-6 h-6 p-0 border-0 bg-transparent cursor-pointer"
            />
          </label>
        </>
      )}

      <ActionChip
        label={t('Reset')}
        title={t('Reset to plain white text without outline')}
        icon={<RotateCcw className="w-3 h-3" />}
        onClick={() => toolStoreActions.resetTextSettings()}
      />
    </>
  );
});
TextOptionsSegment.displayName = 'TextOptionsSegment';

const Scene3DOptionsSegment: React.FC = React.memo(() => {
  const { t } = useI18n();
  const activeMode = use3DStore((s) => s.activeMode);
  const gizmoMode = use3DStore((s) => s.gizmoMode);
  const gizmoSpace = use3DStore((s) => s.gizmoSpace);
  const shadingMode = use3DStore((s) => s.shadingMode);
  const opacity = use3DStore((s) => s.opacity);
  const fov = use3DStore((s) => s.fov);
  const snapEnabled = use3DStore((s) => s.snapEnabled);
  const showGrid = use3DStore((s) => s.showGrid);
  const toonOutline = use3DStore((s) => s.toonOutline);
  const isReferenceVisible = use3DStore((s) => s.isReferenceVisible);

  return (
    <>
      <ToolLabelBadge icon={<Box className="w-3 h-3" />} label={t('3D Stage')} />
      <select
        aria-label={t('3D Tool Mode')}
        value={activeMode}
        onChange={(e) => store3DActions.setActiveMode(e.target.value as Tool3DMode)}
        className={compactSelectClass}
      >
        <option value="smart">{t('Smart')}</option>
        <option value="camera-orbit">{t('Camera Orbit')}</option>
        <option value="camera-pan">{t('Camera Pan')}</option>
        <option value="model-rotate">{t('Model Rotate')}</option>
        <option value="model-move">{t('Model Move')}</option>
        <option value="model-scale">{t('Model Scale')}</option>
      </select>

      <div className="flex items-center gap-0.5 bg-ui-input border border-ui-subtle rounded-ui-xs p-0.5 shrink-0">
        {(
          [
            { id: 'translate', label: 'Move' },
            { id: 'rotate', label: 'Rotate' },
            { id: 'scale', label: 'Scale' },
          ] as ReadonlyArray<{ id: Gizmo3DMode; label: string }>
        ).map((g) => (
          <button
            key={g.id}
            type="button"
            onClick={() => store3DActions.setGizmoMode(g.id)}
            className={`h-[18px] px-1.5 rounded-[2px] text-[10px] cursor-pointer transition-colors ${
              gizmoMode === g.id
                ? 'bg-ui-control-active text-ui-primary font-medium'
                : 'text-ui-muted hover:text-ui-primary'
            }`}
          >
            {t(g.label)}
          </button>
        ))}
      </div>

      <ToggleChip
        active={gizmoSpace === 'world'}
        label={gizmoSpace === 'world' ? t('World') : t('Local')}
        title={t('Toggle Gizmo Coordinate Space')}
        onClick={() => store3DActions.setGizmoSpace(gizmoSpace === 'world' ? 'local' : 'world')}
      />

      <BarDivider />

      <select
        aria-label={t('3D Shading')}
        value={shadingMode}
        onChange={(e) => store3DActions.setShadingMode(e.target.value as Shading3DMode)}
        className={compactSelectClass}
      >
        <option value="shaded">{t('Shaded')}</option>
        <option value="smooth">{t('Smooth')}</option>
        <option value="toon">{t('Toon')}</option>
        <option value="wireframe">{t('Wireframe')}</option>
        <option value="silhouette">{t('Silhouette')}</option>
      </select>

      <div className="w-[96px] shrink-0">
        <ScrubSlider
          label={t('Opacity')}
          size="xs"
          variant="opacity"
          min={10}
          max={100}
          step={1}
          defaultValue={92}
          unit="%"
          value={Math.round(opacity * 100)}
          onChange={(v) => store3DActions.setOpacity(v / 100)}
        />
      </div>

      <div className="w-[86px] shrink-0">
        <ScrubSlider
          label={t('FOV')}
          size="xs"
          min={18}
          max={95}
          step={1}
          defaultValue={45}
          unit="°"
          value={Math.round(fov)}
          onChange={(v) => store3DActions.setFov(v)}
        />
      </div>

      <BarDivider />

      <ToggleChip
        active={snapEnabled}
        icon={<Magnet className="w-3 h-3" />}
        label={t('Snap')}
        onClick={() => store3DActions.setSnapEnabled(!snapEnabled)}
      />
      <ToggleChip
        active={showGrid}
        icon={<Grid3x3 className="w-3 h-3" />}
        label={t('Grid')}
        onClick={() => store3DActions.setShowGrid(!showGrid)}
      />
      <ToggleChip
        active={toonOutline}
        label={t('Outline')}
        onClick={() => store3DActions.setToonOutline(!toonOutline)}
      />
      <ToggleChip
        active={isReferenceVisible}
        label={t('Visible')}
        onClick={() => store3DActions.toggleReferenceVisible()}
      />
    </>
  );
});
Scene3DOptionsSegment.displayName = 'Scene3DOptionsSegment';

const ShapeOptionsSegment: React.FC = React.memo(() => {
  const { t, tc } = useI18n();
  const ss = useToolStore((s) => s.shapeSettings);
  return (
    <>
      <ToolLabelBadge icon={<Shapes className="w-3 h-3" />} label={t('Shape')} />
      <select
        aria-label={t('Shape Type')}
        value={ss.shape}
        onChange={(e) => toolStoreActions.updateShapeSettings({ shape: e.target.value as ShapeKind })}
        className={compactSelectClass}
      >
        {SHAPE_KIND_OPTIONS.map((opt) => (
          <option key={opt.value} value={opt.value}>
            {t(opt.label)}
          </option>
        ))}
      </select>
      <div className="flex items-center gap-0.5 bg-ui-input border border-ui-subtle rounded-ui-xs p-0.5 shrink-0">
        {(['stroke', 'fill', 'both'] as ShapeDrawMode[]).map((m) => (
          <button
            key={m}
            type="button"
            onClick={() => toolStoreActions.updateShapeSettings({ mode: m })}
            className={`h-[18px] px-1.5 rounded-[2px] text-[10px] capitalize cursor-pointer transition-colors ${
              ss.mode === m
                ? 'bg-ui-control-active text-ui-primary font-medium'
                : 'text-ui-muted hover:text-ui-primary'
            }`}
          >
            {tc('shapeDrawMode', m)}
          </button>
        ))}
      </div>
      <BarDivider />
      <div className="w-[100px] shrink-0">
        <ScrubSlider
          label={tc('layerStyle', 'Stroke')}
          size="xs"
          min={1}
          max={100}
          step={1}
          defaultValue={4}
          unit="px"
          value={ss.strokeWidth}
          onChange={(v) => toolStoreActions.updateShapeSettings({ strokeWidth: v })}
        />
      </div>
      <div className="w-[100px] shrink-0">
        <ScrubSlider
          label={t('Opacity')}
          size="xs"
          variant="opacity"
          min={1}
          max={100}
          step={1}
          defaultValue={100}
          unit="%"
          value={Math.round(ss.opacity * 100)}
          onChange={(v) => toolStoreActions.updateShapeSettings({ opacity: v / 100 })}
        />
      </div>
      <ToggleChip
        active={ss.antiAlias}
        label={t('Anti-Alias')}
        onClick={() => toolStoreActions.updateShapeSettings({ antiAlias: !ss.antiAlias })}
      />
    </>
  );
});
ShapeOptionsSegment.displayName = 'ShapeOptionsSegment';

const PenOptionsSegment: React.FC = React.memo(() => {
  const { t, tc } = useI18n();
  const ps = useToolStore((s) => s.penSettings);
  return (
    <>
      <ToolLabelBadge icon={<PenTool className="w-3 h-3" />} label={t('Pen')} />
      <div className="flex items-center gap-0.5 bg-ui-input border border-ui-subtle rounded-ui-xs p-0.5 shrink-0">
        {(['draw', 'edit'] as PenToolMode[]).map((m) => (
          <button
            key={m}
            type="button"
            onClick={() => toolStoreActions.updatePenSettings({ mode: m })}
            className={`h-[18px] px-1.5 rounded-[2px] text-[10px] capitalize cursor-pointer transition-colors ${
              ps.mode === m
                ? 'bg-ui-control-active text-ui-primary font-medium'
                : 'text-ui-muted hover:text-ui-primary'
            }`}
          >
            {tc('penMode', m)}
          </button>
        ))}
      </div>
      <BarDivider />
      <div className="w-[100px] shrink-0">
        <ScrubSlider
          label={t('Width')}
          size="xs"
          min={1}
          max={80}
          step={1}
          defaultValue={4}
          unit="px"
          value={ps.strokeWidth}
          onChange={(v) => toolStoreActions.updatePenSettings({ strokeWidth: v })}
        />
      </div>
      <div className="w-[100px] shrink-0">
        <ScrubSlider
          label={t('Opacity')}
          size="xs"
          variant="opacity"
          min={1}
          max={100}
          step={1}
          defaultValue={100}
          unit="%"
          value={Math.round(ps.opacity * 100)}
          onChange={(v) => toolStoreActions.updatePenSettings({ opacity: v / 100 })}
        />
      </div>
      <ToggleChip
        active={ps.strokeEnabled}
        label={tc('layerStyle', 'Stroke')}
        onClick={() => toolStoreActions.updatePenSettings({ strokeEnabled: !ps.strokeEnabled })}
      />
      <ToggleChip
        active={ps.fillEnabled}
        label={t('Fill')}
        onClick={() => toolStoreActions.updatePenSettings({ fillEnabled: !ps.fillEnabled })}
      />
    </>
  );
});
PenOptionsSegment.displayName = 'PenOptionsSegment';

const LiquifyOptionsSegment: React.FC = React.memo(() => {
  const { t } = useI18n();
  const ls = useToolStore((s) => s.liquifySettings);
  return (
    <>
      <ToolLabelBadge icon={<Waves className="w-3 h-3" />} label={t('Liquify')} />
      <select
        aria-label={t('Liquify Mode')}
        value={ls.mode}
        onChange={(e) => toolStoreActions.updateLiquifySettings({ mode: e.target.value as LiquifyMode })}
        className={compactSelectClass}
      >
        {LIQUIFY_MODE_OPTIONS.map((opt) => (
          <option key={opt.value} value={opt.value}>
            {t(opt.label)}
          </option>
        ))}
      </select>
      <BarDivider />
      <div className="w-[108px] shrink-0">
        <ScrubSlider
          label={t('Size')}
          size="xs"
          variant="size"
          logarithmic
          min={5}
          max={500}
          step={1}
          defaultValue={80}
          unit="px"
          value={ls.size}
          onChange={(v) => toolStoreActions.updateLiquifySettings({ size: Math.round(v) })}
        />
      </div>
      <div className="w-[104px] shrink-0">
        <ScrubSlider
          label={t('Strength')}
          size="xs"
          min={1}
          max={100}
          step={1}
          defaultValue={50}
          unit="%"
          value={ls.strength}
          onChange={(v) => toolStoreActions.updateLiquifySettings({ strength: v })}
        />
      </div>
      <div className="w-[100px] shrink-0">
        <ScrubSlider
          label={t('Hardness')}
          size="xs"
          min={0}
          max={100}
          step={1}
          defaultValue={50}
          unit="%"
          value={ls.hardness}
          onChange={(v) => toolStoreActions.updateLiquifySettings({ hardness: v })}
        />
      </div>
      <ToggleChip
        active={Boolean(ls.multiLayer)}
        label={t('Multi-Layer')}
        onClick={() => toolStoreActions.updateLiquifySettings({ multiLayer: !ls.multiLayer })}
      />
    </>
  );
});
LiquifyOptionsSegment.displayName = 'LiquifyOptionsSegment';

const RetouchOptionsSegment: React.FC = React.memo(() => {
  const { t } = useI18n();
  const rs = useToolStore((s) => s.retouchSettings);
  return (
    <>
      <ToolLabelBadge icon={<Sparkles className="w-3 h-3" />} label={t('Retouch')} />
      <select
        aria-label={t('Retouch Mode')}
        value={rs.mode}
        onChange={(e) => toolStoreActions.updateRetouchSettings({ mode: e.target.value as RetouchMode })}
        className={compactSelectClass}
      >
        {RETOUCH_MODE_OPTIONS.map((opt) => (
          <option key={opt.value} value={opt.value}>
            {t(opt.label)}
          </option>
        ))}
      </select>
      <BarDivider />
      <div className="w-[106px] shrink-0">
        <ScrubSlider
          label={t('Size')}
          size="xs"
          variant="size"
          logarithmic
          min={2}
          max={300}
          step={1}
          defaultValue={40}
          unit="px"
          value={rs.size}
          onChange={(v) => toolStoreActions.updateRetouchSettings({ size: Math.round(v) })}
        />
      </div>
      <div className="w-[104px] shrink-0">
        <ScrubSlider
          label={t('Strength')}
          size="xs"
          min={1}
          max={100}
          step={1}
          defaultValue={50}
          unit="%"
          value={rs.strength}
          onChange={(v) => toolStoreActions.updateRetouchSettings({ strength: v })}
        />
      </div>
      <div className="w-[100px] shrink-0">
        <ScrubSlider
          label={t('Hardness')}
          size="xs"
          min={0}
          max={100}
          step={1}
          defaultValue={50}
          unit="%"
          value={rs.hardness}
          onChange={(v) => toolStoreActions.updateRetouchSettings({ hardness: v })}
        />
      </div>
      <ToggleChip
        active={rs.usePressure}
        label={t('Pressure')}
        onClick={() => toolStoreActions.updateRetouchSettings({ usePressure: !rs.usePressure })}
      />
    </>
  );
});
RetouchOptionsSegment.displayName = 'RetouchOptionsSegment';

const MiscToolOptionsSegment: React.FC<{ tool: ToolType }> = React.memo(({ tool }) => {
  const { t, tc } = useI18n();
  const frameSettings = useToolStore((s) => s.frameSettings);
  const balloonSettings = useToolStore((s) => s.balloonSettings);
  const vectorEditSettings = useToolStore((s) => s.vectorEditSettings);

  if (tool === 'frame') {
    return (
      <>
        <ToolLabelBadge icon={<Shapes className="w-3 h-3" />} label={t('Frame')} />
        <div className="w-[104px] shrink-0">
          <ScrubSlider
            label={t('Border')}
            size="xs"
            min={1}
            max={30}
            step={1}
            defaultValue={4}
            unit="px"
            value={frameSettings.thickness}
            onChange={(v) => toolStoreActions.updateFrameSettings({ thickness: v })}
          />
        </div>
        <ToggleChip
          active={frameSettings.fillBackground}
          label={t('Fill Paper')}
          onClick={() =>
            toolStoreActions.updateFrameSettings({ fillBackground: !frameSettings.fillBackground })
          }
        />
      </>
    );
  }

  if (tool === 'balloon') {
    return (
      <>
        <ToolLabelBadge icon={<Type className="w-3 h-3" />} label={t('Balloon')} />
        <div className="w-[104px] shrink-0">
          <ScrubSlider
            label={tc('layerStyle', 'Stroke')}
            size="xs"
            min={1}
            max={20}
            step={1}
            defaultValue={3}
            unit="px"
            value={balloonSettings.strokeWidth}
            onChange={(v) => toolStoreActions.updateBalloonSettings({ strokeWidth: v })}
          />
        </div>
        <div className="w-[98px] shrink-0">
          <ScrubSlider
            label={t('Font')}
            size="xs"
            min={10}
            max={96}
            step={1}
            defaultValue={22}
            unit="px"
            value={balloonSettings.fontSize}
            onChange={(v) => toolStoreActions.updateBalloonSettings({ fontSize: v })}
          />
        </div>
        <ToggleChip
          active={balloonSettings.vertical}
          label={t('Vertical')}
          onClick={() =>
            toolStoreActions.updateBalloonSettings({ vertical: !balloonSettings.vertical })
          }
        />
      </>
    );
  }

  if (tool === 'vector-edit') {
    return (
      <>
        <ToolLabelBadge icon={<Spline className="w-3 h-3" />} label={t('Correct Line')} />
        <div className="w-[106px] shrink-0">
          <ScrubSlider
            label={t('Radius')}
            size="xs"
            min={5}
            max={160}
            step={1}
            defaultValue={35}
            unit="px"
            value={vectorEditSettings.radius}
            onChange={(v) => toolStoreActions.updateVectorEditSettings({ radius: v })}
          />
        </div>
      </>
    );
  }

  return (
    <>
      <ToolLabelBadge icon={<Pipette className="w-3 h-3" />} label={t('Eyedropper')} />
      <span className="text-[10.5px] text-ui-muted">
        {t(
          'Click or drag on canvas to sample color · Hold Alt with any brush for temporary eyedropper'
        )}
      </span>
    </>
  );
});
MiscToolOptionsSegment.displayName = 'MiscToolOptionsSegment';

const ToolOptionsBarInner: React.FC<Omit<ToolOptionsBarProps, 'forceVisible'>> = React.memo(
  ({
    onDeselect,
    onTransformSelection,
    onInvertSelection,
    onExpandSelection,
    onFeatherSelection,
    onFlipHorizontal,
    onFlipVertical,
    onResetRotation,
  }) => {
    const { t } = useI18n();
    const tool = useToolStore((s) => s.tool);

    const renderToolSegment = () => {
      if (isBrushLikeTool(tool)) {
        return <BrushOptionsSegment tool={tool} />;
      }
      if (tool === 'fill') {
        return <FillOptionsSegment />;
      }
      if (
        tool === 'select-rect' ||
        tool === 'select-lasso' ||
        tool === 'select-wand' ||
        tool === 'select-pen' ||
        tool === 'select-eraser'
      ) {
        return (
          <SelectionOptionsSegment
            tool={tool}
            onDeselect={onDeselect}
            onTransformSelection={onTransformSelection}
            onInvertSelection={onInvertSelection}
            onExpandSelection={onExpandSelection}
            onFeatherSelection={onFeatherSelection}
          />
        );
      }
      if (tool === 'gradient') {
        return <GradientOptionsSegment />;
      }
      if (tool === 'transform' || tool === 'object') {
        return (
          <TransformOptionsSegment
            tool={tool}
            onTransformSelection={onTransformSelection}
            onFlipHorizontal={onFlipHorizontal}
            onFlipVertical={onFlipVertical}
            onResetRotation={onResetRotation}
          />
        );
      }
      if (tool === 'text') {
        return <TextOptionsSegment />;
      }
      if (tool === '3d') {
        return <Scene3DOptionsSegment />;
      }
      if (tool === 'shape') {
        return <ShapeOptionsSegment />;
      }
      if (tool === 'pen') {
        return <PenOptionsSegment />;
      }
      if (tool === 'liquify') {
        return <LiquifyOptionsSegment />;
      }
      if (tool === 'retouch') {
        return <RetouchOptionsSegment />;
      }
      return <MiscToolOptionsSegment tool={tool} />;
    };

    return (
      <div
        role="toolbar"
        aria-label={t('Contextual Tool Options')}
        data-testid="tool-options-bar"
        data-chrome-bar="options"
        data-active-tool={tool}
        className="h-[var(--ui-options-bar-height,32px)] px-2 flex items-center gap-1.5 overflow-x-auto no-scrollbar whitespace-nowrap shrink-0 select-none bg-ui-header border-b border-ui-subtle text-ui-primary tabular-nums z-30 ui-icon-stroke"
      >
        <div className="flex items-center gap-1.5 min-w-0 flex-1">{renderToolSegment()}</div>

        <button
          type="button"
          data-testid="tool-options-bar-close"
          onClick={() => workspaceStoreActions.setShowToolOptionsBar(false)}
          title={t('Hide Tool Options Bar (Window → Tool Options Bar)')}
          aria-label={t('Hide Tool Options Bar')}
          className="w-5 h-5 rounded-ui-xs flex items-center justify-center text-ui-muted hover:text-ui-primary hover:bg-ui-control-hover transition-colors shrink-0 cursor-pointer"
        >
          <X className="w-3 h-3" />
        </button>
      </div>
    );
  }
);
ToolOptionsBarInner.displayName = 'ToolOptionsBarInner';

export const ToolOptionsBar: React.FC<ToolOptionsBarProps> = React.memo(
  ({ forceVisible = false, ...rest }) => {
    const showToolOptionsBar = useWorkspaceStore((s) => s.showToolOptionsBar);
    if (!forceVisible && !showToolOptionsBar) return null;
    return <ToolOptionsBarInner {...rest} />;
  }
);
ToolOptionsBar.displayName = 'ToolOptionsBar';