Skip to content

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

76.7 KB
Raw Blame
import React, { useState, useEffect, useMemo, useRef } from 'react';
import { version as APP_VERSION } from '../../package.json';
import { safeLocalStorageSetItem } from '../utils/safeStorage';
import {
  DEFAULT_INTERFACE_SCALE,
  INTERFACE_SCALE_PRESETS,
  INTERFACE_SCALE_STEP,
  MAX_INTERFACE_SCALE,
  MIN_INTERFACE_SCALE,
  clampInterfaceScale,
} from '../utils/interfaceScale';
import {
  X,
  Palette,
  Layers,
  Paintbrush,
  Keyboard,
  SlidersHorizontal,
  Gauge,
  Users,
  Shield,
  Info,
  RotateCcw,
  Search,
  AlertTriangle,
  ArrowDownToLine,
  Loader2,
  RefreshCw,
  Minus,
  Plus,
  Globe,
} from 'lucide-react';
import { AppLanguage, detectSystemLanguage, isImeComposing, useI18n } from '../i18n';
import { isTauriEnvironment } from '../hooks/useMultiplayer';
import { updaterService } from '../services/updaterService';
import { useUpdaterStore } from '../stores/useUpdaterStore';
import { getChangelogForVersion } from '../utils/changelog';
import { ChangelogBox } from './ChangelogBox';
import {
  AppSettings,
  DEFAULT_APP_SETTINGS,
  DEFAULT_MODIFIER_KEY_SETTINGS,
  ModifierAction,
  ModifierKeySlot,
  MouseWheelAction,
  NICKNAME_CUSTOMIZED_STORAGE_KEY,
  NICKNAME_STORAGE_KEY,
  ShortcutCategory,
} from '../types/settings';
import {
  BUILT_IN_LOOK_PRESET_IDS,
  BuiltInLookPresetId,
  DEFAULT_APPEARANCE_CONFIG,
  createAppearanceFromPreset,
} from '../types/appearance';
import { uiStoreActions } from '../stores';
import { LookPresetCard } from './AppearanceStudioDrawer';
import { CanvasColorMode, CspBrush } from '../types/editor';
import { DPI_PRESETS } from './NewCanvasModal';
import { PressureCurveEditor } from './PressureCurveEditor';
import { PerformanceSettingsTab } from './PerformanceSettingsTab';
import {
  CommandDefinition,
  DEFAULT_COMMANDS,
  SHORTCUT_CATEGORIES,
  buildSubToolShortcutCommands,
  findShortcutConflicts,
  formatShortcutFromEvent,
  formatShortcutLabel,
  getOsModifierDisplayName,
  resolveCommandShortcut,
} from '../utils/shortcutManager';
import {
  CUSTOM_BRUSHES_CHANGED_EVENT,
  getCachedCustomBrushes,
  loadCustomBrushes,
} from '../utils/brushStorage';
import { useSubToolGroupStore } from '../stores/useSubToolGroupStore';
import {
  acquireNativeOsHotkeyRecording,
  subscribeNativeOsHotkeys,
} from '../utils/nativeOsHotkeys';

interface SettingsModalProps {
  isOpen: boolean;
  onClose: () => void;
  onOpenAppearanceStudio?: () => void;
  settings: AppSettings;
  onUpdateSettings: (newSettings: AppSettings) => void;
  onShowToast: (message: string) => void;
}

type SettingsTab =
  | 'appearance'
  | 'canvas'
  | 'brush'
  | 'performance'
  | 'collaboration'
  | 'shortcuts'
  | 'modifiers'
  | 'about';

const MODIFIER_ACTION_OPTIONS: Array<{ value: ModifierAction; label: string }> = [
  { value: 'none', label: 'None' },
  { value: 'pan', label: 'Pan / Hand Tool' },
  { value: 'rotate', label: 'Rotate Canvas' },
  { value: 'zoom-drag', label: 'Scrubby Zoom Drag' },
  { value: 'eyedropper', label: 'Eyedropper (Sample Color)' },
  { value: 'brush-size', label: 'Brush Size & Hardness Drag' },
  { value: 'straight-line', label: 'Straight Line / Angle Snap' },
  { value: 'temp-eraser', label: 'Temporary Eraser' },
  { value: 'quick-palette', label: 'Quick Palette Popover' },
  { value: 'swap-colors', label: 'Swap Primary / Secondary Color' },
  { value: 'undo', label: 'Undo' },
];

const MOUSE_WHEEL_OPTIONS: Array<{ value: MouseWheelAction; label: string }> = [
  { value: 'zoom', label: 'Zoom In / Out' },
  { value: 'scroll', label: 'Scroll / Pan Canvas' },
  { value: 'brush-size', label: 'Adjust Brush Size' },
];

const MODIFIER_SLOTS: Array<{
  slot: ModifierKeySlot;
  label: string;
  desc: string;
}> = [
  { slot: 'space', label: 'Space + Drag', desc: 'Hold Space while dragging on canvas' },
  { slot: 'shift', label: 'Shift', desc: 'Hold Shift while clicking or dragging' },
  { slot: 'ctrl', label: 'Ctrl', desc: 'Hold Ctrl / Cmd while clicking or dragging' },
  { slot: 'alt', label: 'Alt', desc: 'Hold Alt while clicking or hovering' },
  { slot: 'ctrlSpace', label: 'Ctrl + Space + Drag', desc: 'Hold Ctrl + Space and drag' },
  { slot: 'shiftSpace', label: 'Shift + Space + Drag', desc: 'Hold Shift + Space and drag' },
  {
    slot: 'ctrlAlt',
    label: 'Ctrl + Alt + Drag',
    desc: 'Interactive brush size (horizontal) & hardness (vertical)',
  },
  {
    slot: 'shiftAlt',
    label: 'Shift + Alt + Drag',
    desc: 'Alternate brush size / modifier drag combo',
  },
  { slot: 'rightClick', label: 'Right Click', desc: 'Secondary mouse button on canvas' },
  { slot: 'middleClick', label: 'Middle Click', desc: 'Middle mouse button / wheel press' },
  {
    slot: 'stylusButton1',
    label: 'Stylus Barrel Button 1',
    desc: 'Lower stylus side button (or mouse side btn 1)',
  },
  {
    slot: 'stylusButton2',
    label: 'Stylus Barrel Button 2',
    desc: 'Upper stylus side button (or mouse side btn 2)',
  },
];

export const SettingsModal: React.FC<SettingsModalProps> = ({
  isOpen,
  onClose,
  onOpenAppearanceStudio,
  settings,
  onUpdateSettings,
  onShowToast,
}) => {
  const { t, tc, td, lang } = useI18n();
  const [activeTab, setActiveTab] = useState<SettingsTab>('appearance');
  const [localSettings, setLocalSettings] = useState<AppSettings>(() => ({
    ...DEFAULT_APP_SETTINGS,
    ...settings,
  }));
  const [draftInterfaceScale, setDraftInterfaceScale] = useState<number>(() =>
    clampInterfaceScale(settings.interfaceScale)
  );
  const [interfaceScaleInput, setInterfaceScaleInput] = useState<string>(() =>
    String(clampInterfaceScale(settings.interfaceScale))
  );
  const isDraggingScaleSliderRef = useRef(false);
  const draftInterfaceScaleRef = useRef(draftInterfaceScale);
  draftInterfaceScaleRef.current = draftInterfaceScale;
  const [searchQuery, setSearchQuery] = useState<string>('');
  const [selectedCategory, setSelectedCategory] = useState<'All' | ShortcutCategory>('All');
  const [recordingCommandId, setRecordingCommandId] = useState<string | null>(null);
  const [recordWithOsModifier, setRecordWithOsModifier] = useState<boolean>(false);
  const [customBrushes, setCustomBrushes] = useState<CspBrush[]>(() => getCachedCustomBrushes());
  const customSubToolGroups = useSubToolGroupStore((s) => s.groups);
  const [pendingConflict, setPendingConflict] = useState<{
    commandId: string;
    shortcut: string;
    conflicts: CommandDefinition[];
  } | null>(null);

  const osKeyLabel = getOsModifierDisplayName();

  const allCommands = useMemo(
    () => [...DEFAULT_COMMANDS, ...buildSubToolShortcutCommands(customBrushes, customSubToolGroups)],
    [customBrushes, customSubToolGroups, lang]
  );

  useEffect(() => {
    if (!isOpen) return;
    let active = true;
    setCustomBrushes([...getCachedCustomBrushes()]);
    void loadCustomBrushes().then((loaded) => {
      if (active) setCustomBrushes(loaded);
    });
    const handleChanged = () => {
      if (active) setCustomBrushes([...getCachedCustomBrushes()]);
    };
    window.addEventListener(CUSTOM_BRUSHES_CHANGED_EVENT, handleChanged);
    return () => {
      active = false;
      window.removeEventListener(CUSTOM_BRUSHES_CHANGED_EVENT, handleChanged);
    };
  }, [isOpen]);

  const isDesktopTauri = isTauriEnvironment();
  const updaterStatus = useUpdaterStore((s) => s.status);
  const runtimeAppVersion = useUpdaterStore((s) => s.currentVersion);
  const availableUpdateVersion = useUpdaterStore((s) => s.availableVersion);
  const updateProgressPercent = useUpdaterStore((s) => s.progressPercent);
  const updateErrorMessage = useUpdaterStore((s) => s.errorMessage);

  useEffect(() => {
    const merged = {
      ...DEFAULT_APP_SETTINGS,
      ...settings,
    };
    setLocalSettings(merged);
    if (!isDraggingScaleSliderRef.current) {
      const clampedScale = clampInterfaceScale(merged.interfaceScale);
      setDraftInterfaceScale(clampedScale);
      setInterfaceScaleInput(String(clampedScale));
    }
  }, [settings]);

  useEffect(() => {
    if (isOpen && isDesktopTauri) {
      void updaterService.resolveCurrentVersion();
    }
  }, [isOpen, isDesktopTauri]);

  useEffect(() => {
    if (!isOpen) {
      setRecordingCommandId(null);
      setRecordWithOsModifier(false);
      setPendingConflict(null);
    }
  }, [isOpen]);

  // Global capture listener (DOM + native Windows OS-key hook) while recording a shortcut keybinding
  useEffect(() => {
    if (!isOpen || !recordingCommandId) return;

    const releaseNativeRecording = acquireNativeOsHotkeyRecording();

    const applyCapturedEvent = (ev: {
      key: string;
      code?: string;
      ctrlKey?: boolean;
      metaKey?: boolean;
      shiftKey?: boolean;
      altKey?: boolean;
    }) => {
      if (ev.key === 'Escape' && !ev.ctrlKey && !ev.metaKey && !ev.altKey && !ev.shiftKey) {
        setRecordingCommandId(null);
        setRecordWithOsModifier(false);
        setPendingConflict(null);
        return;
      }

      const captured = formatShortcutFromEvent({
        ...ev,
        metaKey: Boolean(ev.metaKey || recordWithOsModifier),
      });
      if (!captured) return;

      const conflicts = findShortcutConflicts(
        recordingCommandId,
        captured,
        localSettings.shortcuts,
        allCommands
      );
      if (conflicts.length > 0) {
        setPendingConflict({
          commandId: recordingCommandId,
          shortcut: captured,
          conflicts,
        });
        setRecordingCommandId(null);
        setRecordWithOsModifier(false);
        return;
      }

      const nextShortcuts = {
        ...localSettings.shortcuts,
        [recordingCommandId]: captured,
      };
      const updated: AppSettings = { ...localSettings, shortcuts: nextShortcuts };
      setLocalSettings(updated);
      onUpdateSettings(updated);
      setRecordingCommandId(null);
      setRecordWithOsModifier(false);
      setPendingConflict(null);
    };

    const handleRecordKeyDown = (e: KeyboardEvent) => {
      e.preventDefault();
      e.stopPropagation();
      applyCapturedEvent(e);
    };

    const unsubNative = subscribeNativeOsHotkeys((ev) => {
      if (ev.phase !== 'keydown' || ev.repeat) return;
      applyCapturedEvent(ev);
    });

    window.addEventListener('keydown', handleRecordKeyDown, true);
    return () => {
      window.removeEventListener('keydown', handleRecordKeyDown, true);
      unsubNative();
      releaseNativeRecording();
    };
  }, [isOpen, recordingCommandId, recordWithOsModifier, localSettings, onUpdateSettings, allCommands]);

  const filteredCommands = useMemo(() => {
    const q = searchQuery.trim().toLowerCase();
    return allCommands.filter((cmd) => {
      if (selectedCategory !== 'All' && cmd.category !== selectedCategory) return false;
      if (!q) return true;
      const bound = formatShortcutLabel(resolveCommandShortcut(cmd, localSettings.shortcuts));
      const trLabel = td(cmd.label);
      const trDesc = td(cmd.description);
      const trCat = td(cmd.category);
      const trGroup = cmd.groupBadge ? td(cmd.groupBadge) : '';
      return (
        cmd.label.toLowerCase().includes(q) ||
        trLabel.toLowerCase().includes(q) ||
        cmd.description.toLowerCase().includes(q) ||
        trDesc.toLowerCase().includes(q) ||
        cmd.category.toLowerCase().includes(q) ||
        trCat.toLowerCase().includes(q) ||
        (cmd.groupBadge && cmd.groupBadge.toLowerCase().includes(q)) ||
        (trGroup && trGroup.toLowerCase().includes(q)) ||
        bound.toLowerCase().includes(q)
      );
    });
  }, [allCommands, searchQuery, selectedCategory, localSettings.shortcuts, td]);

  if (!isOpen) return null;

  const handleChange = <K extends keyof AppSettings>(key: K, value: AppSettings[K]) => {
    const updated = { ...localSettings, [key]: value };
    setLocalSettings(updated);
    onUpdateSettings(updated);
  };

  const commitInterfaceScale = (rawScale: number) => {
    const clamped = clampInterfaceScale(rawScale);
    setDraftInterfaceScale(clamped);
    setInterfaceScaleInput(String(clamped));
    handleChange('interfaceScale', clamped);
  };

  const handleResetDefaults = () => {
    setRecordingCommandId(null);
    setPendingConflict(null);
    isDraggingScaleSliderRef.current = false;
    const fresh: AppSettings = {
      ...DEFAULT_APP_SETTINGS,
      appearance: { ...DEFAULT_APPEARANCE_CONFIG },
      shortcuts: {},
      modifierKeys: { ...DEFAULT_MODIFIER_KEY_SETTINGS },
      pressureCurve: {
        ...DEFAULT_APP_SETTINGS.pressureCurve,
        points: DEFAULT_APP_SETTINGS.pressureCurve.points.map(([x, y]) => [x, y]),
      },
    };
    setLocalSettings(fresh);
    setDraftInterfaceScale(DEFAULT_INTERFACE_SCALE);
    setInterfaceScaleInput(String(DEFAULT_INTERFACE_SCALE));
    onUpdateSettings(fresh);
    onShowToast(t('Preferences reset to defaults'));
  };

  const handleConfirmConflictReplace = () => {
    if (!pendingConflict) return;
    const nextShortcuts = { ...localSettings.shortcuts };
    for (const c of pendingConflict.conflicts) {
      if (c.defaultShortcut) {
        nextShortcuts[c.id] = '';
      } else {
        delete nextShortcuts[c.id];
      }
    }
    nextShortcuts[pendingConflict.commandId] = pendingConflict.shortcut;
    const updated: AppSettings = { ...localSettings, shortcuts: nextShortcuts };
    setLocalSettings(updated);
    onUpdateSettings(updated);
    setPendingConflict(null);
    onShowToast(
      t('Assigned {shortcut}', { shortcut: formatShortcutLabel(pendingConflict.shortcut) })
    );
  };

  const handleResetSingleShortcut = (commandId: string) => {
    const nextShortcuts = { ...localSettings.shortcuts };
    delete nextShortcuts[commandId];
    handleChange('shortcuts', nextShortcuts);
  };

  const handleClearSingleShortcut = (commandId: string) => {
    const cmd = allCommands.find((c) => c.id === commandId);
    const nextShortcuts = { ...localSettings.shortcuts };
    if (cmd && !cmd.defaultShortcut) {
      delete nextShortcuts[commandId];
    } else {
      nextShortcuts[commandId] = '';
    }
    handleChange('shortcuts', nextShortcuts);
  };

  const handleResetAllShortcuts = () => {
    setRecordingCommandId(null);
    setPendingConflict(null);
    handleChange('shortcuts', {});
    onShowToast(t('Shortcuts reset to defaults'));
  };

  const handleModifierSlotChange = (slot: ModifierKeySlot, action: ModifierAction) => {
    handleChange('modifierKeys', {
      ...localSettings.modifierKeys,
      [slot]: action,
    });
  };

  const handleMouseWheelChange = (action: MouseWheelAction) => {
    handleChange('modifierKeys', {
      ...localSettings.modifierKeys,
      mouseWheel: action,
    });
  };

  const handleResetModifiers = () => {
    handleChange('modifierKeys', { ...DEFAULT_MODIFIER_KEY_SETTINGS });
    onShowToast(t('Modifier keys reset to defaults'));
  };

  const handleResetCollaboration = () => {
    const updated: AppSettings = {
      ...localSettings,
      collabSignalingUrl: '',
      collabTurnUrl: '',
      collabTurnUsername: '',
      collabTurnCredential: '',
    };
    setLocalSettings(updated);
    onUpdateSettings(updated);
    onShowToast(t('Collaboration network settings reset to defaults'));
  };

  const handleSelectLookPreset = (presetId: BuiltInLookPresetId) => {
    const cur = localSettings.appearance ?? DEFAULT_APPEARANCE_CONFIG;
    const nextAppearance = createAppearanceFromPreset(presetId, {
      accent: cur.accent,
      customAccentHex: cur.customAccentHex,
      cornerRadius: cur.cornerRadius,
      chromeStyle: cur.chromeStyle,
      floatingOpacity: cur.floatingOpacity,
      density: cur.density,
      fontProfile: cur.fontProfile,
      iconStrokeWidth: cur.iconStrokeWidth,
      sliderStyle: cur.sliderStyle,
      brushListStyle: cur.brushListStyle,
      layerThumbSize: cur.layerThumbSize,
    });
    handleChange('appearance', nextAppearance);
  };

  const handleOpenLiveAppearanceStudio = () => {
    onClose();
    if (onOpenAppearanceStudio) {
      onOpenAppearanceStudio();
    } else {
      uiStoreActions.setAppearanceStudioOpen(true);
    }
  };

  const tabs: Array<{ id: SettingsTab; label: string; icon: React.ReactNode }> = [
    { id: 'appearance', label: t('Appearance'), icon: <Palette className="w-3.5 h-3.5" /> },
    { id: 'canvas', label: t('Canvas'), icon: <Layers className="w-3.5 h-3.5" /> },
    { id: 'brush', label: t('Brush & Stylus'), icon: <Paintbrush className="w-3.5 h-3.5" /> },
    { id: 'performance', label: t('Performance'), icon: <Gauge className="w-3.5 h-3.5" /> },
    { id: 'collaboration', label: t('Collaboration'), icon: <Users className="w-3.5 h-3.5" /> },
    { id: 'shortcuts', label: t('Shortcuts'), icon: <Keyboard className="w-3.5 h-3.5" /> },
    {
      id: 'modifiers',
      label: t('Modifier Keys'),
      icon: <SlidersHorizontal className="w-3.5 h-3.5" />,
    },
    { id: 'about', label: t('About'), icon: <Info className="w-3.5 h-3.5" /> },
  ];

  return (
    <div
      role="dialog"
      aria-modal="true"
      className="fixed inset-0 z-50 flex items-center justify-center bg-ui-overlay p-4 select-none"
      onClick={onClose}
      onKeyDown={(e) => {
        if (isImeComposing(e)) return;
        if (e.key === 'Escape' && !recordingCommandId) onClose();
      }}
    >
      <div
        onClick={(e) => e.stopPropagation()}
        className="bg-ui-panel border border-ui-default rounded-ui-lg shadow-ui-popover w-full max-w-3xl flex flex-col overflow-hidden text-xs text-ui-primary h-[600px] max-h-full"
      >
        {/* Header */}
        <div className="h-10 px-4 flex items-center justify-between bg-ui-header border-b border-ui-subtle shrink-0">
          <span className="text-xs font-medium text-ui-primary">{t('Preferences')}</span>
          <button
            type="button"
            onClick={onClose}
            className="w-6 h-6 rounded-ui-sm flex items-center justify-center text-ui-muted hover:text-ui-primary hover:bg-ui-control-hover transition-colors cursor-pointer"
            title={t('Close (Esc)')}
          >
            <X className="w-3.5 h-3.5" />
          </button>
        </div>

        {/* Body */}
        <div className="flex flex-1 min-h-0 overflow-hidden">
          {/* Left Navigation */}
          <div className="w-44 bg-ui-header border-r border-ui-subtle p-2 flex flex-col justify-between gap-2 shrink-0 min-h-0">
            <div className="space-y-0.5 overflow-y-auto min-h-0">
              {tabs.map((tab) => {
                const active = activeTab === tab.id;
                return (
                  <button
                    key={tab.id}
                    type="button"
                    onClick={() => {
                      setActiveTab(tab.id);
                      setRecordingCommandId(null);
                      setPendingConflict(null);
                    }}
                    className={`w-full flex items-center gap-2 px-2.5 py-1.5 rounded-ui-sm text-left transition-colors cursor-pointer border ${
                      active
                        ? 'bg-ui-control text-ui-primary border-ui-default font-medium'
                        : 'text-ui-muted hover:text-ui-primary hover:bg-ui-control-hover border-transparent'
                    }`}
                  >
                    <span className={active ? 'text-ui-accent' : ''}>{tab.icon}</span>
                    <span>{tab.label}</span>
                  </button>
                );
              })}
            </div>

            <button
              type="button"
              onClick={handleResetDefaults}
              className="w-full flex items-center justify-center gap-1.5 px-2 py-1.5 rounded-ui-sm text-[11px] text-ui-muted hover:text-ui-primary hover:bg-ui-control-hover transition-colors cursor-pointer"
            >
              <RotateCcw className="w-3 h-3" />
              <span>{t('Reset All Defaults')}</span>
            </button>
          </div>

          {/* Content */}
          <div className="flex-1 p-5 overflow-y-auto bg-ui-panel space-y-5">
            {activeTab === 'appearance' && (
              <>
                <section
                  className="p-3 rounded-ui-md bg-ui-header border border-ui-default flex flex-wrap items-center justify-between gap-3"
                  data-testid="settings-language-section"
                >
                  <div className="min-w-0">
                    <div className="flex items-center gap-1.5">
                      <Globe className="w-3.5 h-3.5 text-ui-accent shrink-0" />
                      <h3 className="text-xs font-medium text-ui-primary">
                        {lang === 'ja' ? '言語 (Language)' : 'Language / 言語'}
                      </h3>
                    </div>
                    <p className="text-[11px] text-ui-muted mt-0.5">
                      {t('Choose the display language for menus, panels, tools, and dialogs')}
                    </p>
                  </div>
                  <div className="flex items-center gap-1 bg-ui-input p-0.5 rounded-ui-sm border border-ui-subtle shrink-0">
                    {(
                      [
                        {
                          value: 'auto' as AppLanguage,
                          label: t('System Default ({lang})', {
                            lang: detectSystemLanguage() === 'ja' ? '日本語' : 'English',
                          }),
                        },
                        { value: 'en' as AppLanguage, label: 'English' },
                        { value: 'ja' as AppLanguage, label: '日本語' },
                      ] as const
                    ).map((opt) => {
                      const active = (localSettings.language ?? 'auto') === opt.value;
                      return (
                        <button
                          key={opt.value}
                          type="button"
                          data-testid={`settings-lang-${opt.value}`}
                          onClick={() => {
                            handleChange('language', opt.value);
                            const nextResolved =
                              opt.value === 'auto' ? detectSystemLanguage() : opt.value;
                            const langLabel = nextResolved === 'ja' ? '日本語' : 'English';
                            onShowToast(
                              nextResolved === 'ja'
                                ? `表示言語を${langLabel}に変更しました`
                                : `Language changed to ${langLabel}`
                            );
                          }}
                          className={`h-6 px-2.5 rounded-ui-xs text-[11px] transition-colors cursor-pointer ${
                            active
                              ? 'bg-ui-control-active text-ui-primary font-medium border border-ui-accent-border'
                              : 'text-ui-muted hover:text-ui-primary hover:bg-ui-control-hover border border-transparent'
                          }`}
                        >
                          {opt.label}
                        </button>
                      );
                    })}
                  </div>
                </section>

                <section className="p-3 rounded-ui-md bg-ui-header border border-ui-default flex items-center justify-between gap-3">
                  <div className="min-w-0">
                    <h3 className="text-xs font-medium text-ui-primary">
                      {t('Live Appearance Studio')}
                    </h3>
                    <p className="text-[11px] text-ui-muted">
                      {t('Fine-tune brightness, warmth, accent, chrome, density, and custom tokens live over your canvas')}
                    </p>
                  </div>
                  <button
                    type="button"
                    data-testid="settings-open-appearance-studio-btn"
                    onClick={handleOpenLiveAppearanceStudio}
                    className="h-7 px-3 rounded-ui-sm bg-ui-control-active hover:bg-ui-control-hover border border-ui-accent-border text-xs font-medium text-ui-primary flex items-center gap-1.5 shrink-0 transition-colors cursor-pointer"
                  >
                    <Palette className="w-3.5 h-3.5 text-ui-accent shrink-0" />
                    <span>{t('Open Live Appearance Studio')}</span>
                  </button>
                </section>

                <section className="space-y-2.5" data-testid="settings-look-presets-section">
                  <div className="flex items-center justify-between">
                    <div>
                      <h3 className="text-xs font-medium text-ui-primary">{t('Look Presets')}</h3>
                      <p className="text-[11px] text-ui-muted">
                        {t('Calibrated studio palettes for color-accurate dark, neutral 18%, and daylight work')}
                      </p>
                    </div>
                  </div>

                  <div className="grid grid-cols-3 gap-2">
                    {BUILT_IN_LOOK_PRESET_IDS.map((presetId) => {
                      const activeAppearance = localSettings.appearance ?? DEFAULT_APPEARANCE_CONFIG;
                      const isActive =
                        activeAppearance.lookPreset === presetId &&
                        !activeAppearance.tokenOverrides;
                      return (
                        <LookPresetCard
                          key={presetId}
                          presetId={presetId}
                          data-testid={`settings-look-preset-${presetId}`}
                          active={isActive}
                          accent={activeAppearance.accent}
                          customAccentHex={activeAppearance.customAccentHex}
                          onSelect={handleSelectLookPreset}
                        />
                      );
                    })}
                  </div>
                </section>

                <section className="space-y-2.5" data-testid="settings-interface-size-section">
                  <div className="flex items-center justify-between gap-2">
                    <div>
                      <h3 className="text-xs font-medium text-ui-primary">{t('Interface Size')}</h3>
                      <p className="text-[11px] text-ui-muted tabular-nums">
                        {t('Adjust UI scale for menus, panels, and controls ({min}%–{max}%)', {
                          min: MIN_INTERFACE_SCALE,
                          max: MAX_INTERFACE_SCALE,
                        })}
                      </p>
                    </div>
                    <div className="flex items-center gap-1 shrink-0">
                      <button
                        type="button"
                        data-testid="settings-interface-scale-dec"
                        aria-label={t('Decrease Interface Size')}
                        disabled={draftInterfaceScale <= MIN_INTERFACE_SCALE}
                        onClick={() =>
                          commitInterfaceScale(draftInterfaceScale - INTERFACE_SCALE_STEP)
                        }
                        className="w-6 h-6 rounded-ui-sm bg-ui-control hover:bg-ui-control-hover border border-ui-subtle text-ui-muted hover:text-ui-primary flex items-center justify-center transition-colors cursor-pointer disabled:opacity-35 disabled:cursor-not-allowed"
                        title={t('Decrease (-{step}%)', { step: INTERFACE_SCALE_STEP })}
                      >
                        <Minus className="w-3 h-3" />
                      </button>
                      <div className="flex items-center bg-ui-input border border-ui-default rounded-ui-sm px-1.5 h-6">
                        <input
                          type="number"
                          data-testid="settings-interface-scale-input"
                          aria-label={t('Interface Size Percentage')}
                          min={MIN_INTERFACE_SCALE}
                          max={MAX_INTERFACE_SCALE}
                          step={INTERFACE_SCALE_STEP}
                          value={interfaceScaleInput}
                          onChange={(e) => setInterfaceScaleInput(e.target.value)}
                          onBlur={() => {
                            const parsed = Number(interfaceScaleInput);
                            if (Number.isFinite(parsed)) {
                              commitInterfaceScale(parsed);
                            } else {
                              setInterfaceScaleInput(String(draftInterfaceScale));
                            }
                          }}
                          onKeyDown={(e) => {
                            if (isImeComposing(e)) return;
                            if (e.key === 'Enter') {
                              const parsed = Number(interfaceScaleInput);
                              if (Number.isFinite(parsed)) {
                                commitInterfaceScale(parsed);
                              } else {
                                setInterfaceScaleInput(String(draftInterfaceScale));
                              }
                              (e.currentTarget as HTMLInputElement).blur();
                            }
                          }}
                          className="w-10 bg-transparent text-right font-ui-mono tabular-nums text-xs text-ui-primary focus:shadow-none"
                        />
                        <span className="font-ui-mono text-[11px] text-ui-muted ml-0.5">%</span>
                      </div>
                      <button
                        type="button"
                        data-testid="settings-interface-scale-inc"
                        aria-label={t('Increase Interface Size')}
                        disabled={draftInterfaceScale >= MAX_INTERFACE_SCALE}
                        onClick={() =>
                          commitInterfaceScale(draftInterfaceScale + INTERFACE_SCALE_STEP)
                        }
                        className="w-6 h-6 rounded-ui-sm bg-ui-control hover:bg-ui-control-hover border border-ui-subtle text-ui-muted hover:text-ui-primary flex items-center justify-center transition-colors cursor-pointer disabled:opacity-35 disabled:cursor-not-allowed"
                        title={t('Increase (+{step}%)', { step: INTERFACE_SCALE_STEP })}
                      >
                        <Plus className="w-3 h-3" />
                      </button>
                      <button
                        type="button"
                        data-testid="settings-interface-scale-reset"
                        disabled={draftInterfaceScale === DEFAULT_INTERFACE_SCALE}
                        onClick={() => commitInterfaceScale(DEFAULT_INTERFACE_SCALE)}
                        className="h-6 px-2 rounded-ui-sm bg-ui-control hover:bg-ui-control-hover border border-ui-subtle text-[11px] text-ui-secondary hover:text-ui-primary transition-colors cursor-pointer disabled:opacity-35 disabled:cursor-not-allowed"
                        title={t('Reset Interface Size to 100%')}
                      >
                        {t('Reset')}
                      </button>
                    </div>
                  </div>

                  <div className="bg-ui-header border border-ui-subtle rounded-ui-md p-3 space-y-2.5">
                    <div className="space-y-1">
                      <input
                        type="range"
                        data-testid="settings-interface-scale-slider"
                        aria-label={t('Interface Size')}
                        min={MIN_INTERFACE_SCALE}
                        max={MAX_INTERFACE_SCALE}
                        step={INTERFACE_SCALE_STEP}
                        value={draftInterfaceScale}
                        onPointerDown={() => {
                          isDraggingScaleSliderRef.current = true;
                          const handleWindowPointerEnd = () => {
                            window.removeEventListener('pointerup', handleWindowPointerEnd);
                            window.removeEventListener('pointercancel', handleWindowPointerEnd);
                            if (!isDraggingScaleSliderRef.current) return;
                            isDraggingScaleSliderRef.current = false;
                            commitInterfaceScale(draftInterfaceScaleRef.current);
                          };
                          window.addEventListener('pointerup', handleWindowPointerEnd);
                          window.addEventListener('pointercancel', handleWindowPointerEnd);
                        }}
                        onChange={(e) => {
                          const next = clampInterfaceScale(Number(e.target.value));
                          setDraftInterfaceScale(next);
                          setInterfaceScaleInput(String(next));
                          if (!isDraggingScaleSliderRef.current) {
                            handleChange('interfaceScale', next);
                          }
                        }}
                        onPointerUp={(e) => {
                          if (!isDraggingScaleSliderRef.current) return;
                          isDraggingScaleSliderRef.current = false;
                          commitInterfaceScale(Number((e.currentTarget as HTMLInputElement).value));
                        }}
                        onPointerCancel={() => {
                          isDraggingScaleSliderRef.current = false;
                          commitInterfaceScale(draftInterfaceScale);
                        }}
                        className="w-full"
                      />
                      <div className="flex items-center justify-between text-[10px] font-ui-mono tabular-nums text-ui-muted">
                        <span>{MIN_INTERFACE_SCALE}%</span>
                        <span>{DEFAULT_INTERFACE_SCALE}%</span>
                        <span>{MAX_INTERFACE_SCALE}%</span>
                      </div>
                    </div>

                    <div className="grid grid-cols-6 gap-1.5">
                      {INTERFACE_SCALE_PRESETS.map((preset) => {
                        const isSelected = draftInterfaceScale === preset;
                        return (
                          <button
                            key={preset}
                            type="button"
                            data-testid={`settings-interface-scale-preset-${preset}`}
                            onClick={() => commitInterfaceScale(preset)}
                            className={`py-1 rounded-ui-sm font-ui-mono tabular-nums text-[11px] transition-colors cursor-pointer border ${
                              isSelected
                                ? 'bg-ui-control-active text-ui-primary font-medium border-ui-accent-border'
                                : 'bg-ui-input text-ui-secondary border-ui-subtle hover:text-ui-primary hover:bg-ui-control-hover'
                            }`}
                          >
                            {preset}%
                          </button>
                        );
                      })}
                    </div>
                  </div>
                </section>

                <section className="space-y-2">
                  <h3 className="text-xs font-medium text-ui-primary">{t('Artist Name')}</h3>
                  <input
                    type="text"
                    value={localSettings.userName || ''}
                    onChange={(e) => {
                      const val = e.target.value;
                      handleChange('userName', val);
                      safeLocalStorageSetItem(NICKNAME_STORAGE_KEY, val, 'artist name');
                      safeLocalStorageSetItem(NICKNAME_CUSTOMIZED_STORAGE_KEY, val.trim() ? '1' : '0', 'artist name flag');
                    }}
                    placeholder={t('Artist')}
                    className="w-full bg-ui-input border border-ui-default px-3 py-1.5 rounded-ui-sm text-xs text-ui-primary placeholder:text-ui-muted/60"
                  />
                </section>

                <section className="space-y-2">
                  <h3 className="text-xs font-medium text-ui-primary">{t('Viewport Overlays')}</h3>
                  <div className="space-y-1 bg-ui-header border border-ui-subtle rounded-ui-md p-2.5">
                    <label className="flex items-center justify-between py-1 cursor-pointer">
                      <span className="text-xs text-ui-primary">{t('Transparency Checkerboard')}</span>
                      <input
                        type="checkbox"
                        checked={localSettings.showCheckerboard}
                        onChange={(e) => handleChange('showCheckerboard', e.target.checked)}
                      />
                    </label>
                    <label className="flex items-center justify-between py-1 cursor-pointer">
                      <span className="text-xs text-ui-primary">{t('Cursor Coordinates')}</span>
                      <input
                        type="checkbox"
                        checked={localSettings.showCursorCoordinates}
                        onChange={(e) => handleChange('showCursorCoordinates', e.target.checked)}
                      />
                    </label>
                    <label className="flex items-center justify-between py-1 cursor-pointer">
                      <span className="text-xs text-ui-primary">{t('Stylus Pressure Readout')}</span>
                      <input
                        type="checkbox"
                        checked={localSettings.showPressureInStatusBar}
                        onChange={(e) => handleChange('showPressureInStatusBar', e.target.checked)}
                      />
                    </label>
                  </div>
                </section>
              </>
            )}

            {activeTab === 'canvas' && (
              <>
                <section className="space-y-2">
                  <h3 className="text-xs font-medium text-ui-primary">{t('Default Dimensions')}</h3>
                  <div className="grid grid-cols-2 gap-2.5">
                    <div className="space-y-1">
                      <label className="text-[11px] text-ui-muted">{t('Width (px)')}</label>
                      <input
                        type="number"
                        min="64"
                        max="16384"
                        value={localSettings.defaultWidth}
                        onChange={(e) => handleChange('defaultWidth', Number(e.target.value))}
                        className="w-full bg-ui-input border border-ui-default px-2.5 py-1.5 rounded-ui-sm font-ui-mono tabular-nums text-xs text-ui-primary"
                      />
                    </div>
                    <div className="space-y-1">
                      <label className="text-[11px] text-ui-muted">{t('Height (px)')}</label>
                      <input
                        type="number"
                        min="64"
                        max="16384"
                        value={localSettings.defaultHeight}
                        onChange={(e) => handleChange('defaultHeight', Number(e.target.value))}
                        className="w-full bg-ui-input border border-ui-default px-2.5 py-1.5 rounded-ui-sm font-ui-mono tabular-nums text-xs text-ui-primary"
                      />
                    </div>
                  </div>
                </section>

                <section className="space-y-2">
                  <h3 className="text-xs font-medium text-ui-primary">{t('Resolution (DPI)')}</h3>
                  <div className="grid grid-cols-6 gap-1.5">
                    {DPI_PRESETS.map((p) => {
                      const selected = localSettings.defaultDpi === p.dpi;
                      return (
                        <button
                          key={p.dpi}
                          type="button"
                          onClick={() => handleChange('defaultDpi', p.dpi)}
                          className={`py-1.5 rounded-ui-sm font-ui-mono tabular-nums text-xs cursor-pointer transition-colors border ${
                            selected
                              ? 'bg-ui-control-active text-ui-primary border-ui-accent-border font-medium'
                              : 'bg-ui-header text-ui-secondary border-ui-subtle hover:text-ui-primary hover:bg-ui-control-hover'
                          }`}
                        >
                          {p.dpi}
                        </button>
                      );
                    })}
                  </div>
                </section>

                <section className="space-y-2">
                  <h3 className="text-xs font-medium text-ui-primary">{t('Color Mode')}</h3>
                  <div className="grid grid-cols-3 gap-1.5">
                    {(['color', 'grayscale', 'monochrome'] as CanvasColorMode[]).map((mode) => {
                      const selected = localSettings.defaultColorMode === mode;
                      return (
                        <button
                          key={mode}
                          type="button"
                          onClick={() => handleChange('defaultColorMode', mode)}
                          className={`p-2 rounded-ui-sm text-left capitalize cursor-pointer transition-colors border ${
                            selected
                              ? 'bg-ui-control-active text-ui-primary border-ui-accent-border font-medium'
                              : 'bg-ui-header text-ui-secondary border-ui-subtle hover:text-ui-primary hover:bg-ui-control-hover'
                          }`}
                        >
                          {tc('colorMode', mode)}
                        </button>
                      );
                    })}
                  </div>
                </section>

                <section className="p-3 rounded-ui-md bg-ui-header border border-ui-subtle flex items-center justify-between gap-3">
                  <div>
                    <h3 className="text-xs font-medium text-ui-primary">{t('RAM, GPU & Scratch Disk')}</h3>
                    <p className="text-[11px] text-ui-muted tabular-nums">
                      {t('Configure RAM allocation ({mb} MB), GPU adapter, and rendering optimization', {
                        mb: localSettings.tileMemoryBudgetMb || 1024,
                      })}
                    </p>
                  </div>
                  <button
                    type="button"
                    onClick={() => setActiveTab('performance')}
                    className="px-2.5 py-1.5 rounded-ui-sm bg-ui-control hover:bg-ui-control-hover border border-ui-default text-[11px] text-ui-primary font-medium shrink-0 cursor-pointer transition-colors"
                  >
                    {t('Open Performance')}
                  </button>
                </section>
              </>
            )}

            {activeTab === 'performance' && (
              <PerformanceSettingsTab
                settings={localSettings}
                isDesktopTauri={isDesktopTauri}
                onUpdateSettings={(updated) => {
                  setLocalSettings(updated);
                  onUpdateSettings(updated);
                }}
                onShowToast={onShowToast}
              />
            )}

            {activeTab === 'collaboration' && (
              <div className="space-y-5">
                <div className="flex items-center justify-between gap-3">
                  <div>
                    <h3 className="text-xs font-medium text-ui-primary">
                      {t('Collaborative Drawing (WebRTC P2P)')}
                    </h3>
                    <p className="text-[11px] text-ui-muted">
                      {t('Configure your display nickname and optional custom signaling or TURN relay servers for P2P rooms')}
                    </p>
                  </div>
                  <button
                    type="button"
                    data-testid="settings-collab-reset-btn"
                    onClick={handleResetCollaboration}
                    className="flex items-center gap-1 px-2.5 py-1 rounded-ui-sm bg-ui-control hover:bg-ui-control-hover border border-ui-subtle text-[11px] text-ui-secondary hover:text-ui-primary cursor-pointer shrink-0 transition-colors"
                  >
                    <RotateCcw className="w-3 h-3" />
                    <span>{t('Reset')}</span>
                  </button>
                </div>

                <section className="space-y-2">
                  <h4 className="text-xs font-medium text-ui-primary">{t('Artist Nickname')}</h4>
                  <input
                    type="text"
                    data-testid="settings-collab-nickname"
                    value={localSettings.userName || ''}
                    onChange={(e) => {
                      const val = e.target.value;
                      handleChange('userName', val);
                      safeLocalStorageSetItem(NICKNAME_STORAGE_KEY, val, 'artist name');
                      safeLocalStorageSetItem(
                        NICKNAME_CUSTOMIZED_STORAGE_KEY,
                        val.trim() ? '1' : '0',
                        'artist name flag'
                      );
                    }}
                    maxLength={40}
                    placeholder={t('Artist')}
                    className="w-full bg-ui-input border border-ui-default px-3 py-1.5 rounded-ui-sm text-xs text-ui-primary placeholder:text-ui-muted/60"
                  />
                  <p className="text-[10px] text-ui-muted">
                    {t('Shown to other artists on live cursors, participant lists, and owned layers.')}
                  </p>
                </section>

                <section className="space-y-2">
                  <h4 className="text-xs font-medium text-ui-primary">
                    {t('Custom Signaling Server URL (Optional)')}
                  </h4>
                  <input
                    type="text"
                    data-testid="settings-collab-signaling-url"
                    value={localSettings.collabSignalingUrl || ''}
                    onChange={(e) => handleChange('collabSignalingUrl', e.target.value)}
                    placeholder={t('wss://your-worker.workers.dev/signal (leave blank for built-in free relays)')}
                    className="w-full bg-ui-input border border-ui-default px-3 py-1.5 rounded-ui-sm font-ui-mono text-xs text-ui-primary placeholder:text-ui-muted/60"
                  />
                  {localSettings.collabSignalingUrl.trim() &&
                    !/^(wss?|https?):\/\//i.test(localSettings.collabSignalingUrl.trim()) && (
                      <p className="text-[10px] text-ui-warning">
                        {t('Signaling URL should start with {proto1} or {proto2}.', {
                          proto1: 'wss://',
                          proto2: 'https://',
                        })}
                      </p>
                    )}
                  <p className="text-[10px] text-ui-muted leading-relaxed">
                    {t("Leave blank to use Ink Studio's built-in free multi-relay signaling. Only tiny SDP/ICE handshakes pass through signaling — all brush strokes and tiles travel directly peer-to-peer.")}
                  </p>
                </section>

                <section className="space-y-2.5">
                  <div>
                    <h4 className="text-xs font-medium text-ui-primary">
                      {t('Optional TURN Server (Strict NAT / Firewall)')}
                    </h4>
                    <p className="text-[10px] text-ui-muted mt-0.5">
                      {t('Only required when direct P2P hole-punching is blocked by symmetric NAT or corporate firewalls.')}
                    </p>
                  </div>

                  <div className="space-y-2 bg-ui-header border border-ui-subtle rounded-ui-md p-3">
                    <div className="space-y-1">
                      <label className="text-[11px] text-ui-muted block">{t('TURN Server URL')}</label>
                      <input
                        type="text"
                        data-testid="settings-collab-turn-url"
                        value={localSettings.collabTurnUrl || ''}
                        onChange={(e) => handleChange('collabTurnUrl', e.target.value)}
                        placeholder="turns:turn.example.com:5349"
                        className="w-full bg-ui-input border border-ui-default px-2.5 py-1.5 rounded-ui-sm font-ui-mono text-xs text-ui-primary placeholder:text-ui-muted/60"
                      />
                      {localSettings.collabTurnUrl.trim() &&
                        !/^turns?:/i.test(localSettings.collabTurnUrl.trim()) && (
                          <p className="text-[10px] text-ui-warning">
                            {t('TURN URL must start with {proto1} or {proto2}.', {
                              proto1: 'turn:',
                              proto2: 'turns:',
                            })}
                          </p>
                        )}
                    </div>

                    <div className="grid grid-cols-2 gap-2.5">
                      <div className="space-y-1">
                        <label className="text-[11px] text-ui-muted block">{t('TURN Username')}</label>
                        <input
                          type="text"
                          data-testid="settings-collab-turn-username"
                          value={localSettings.collabTurnUsername || ''}
                          onChange={(e) => handleChange('collabTurnUsername', e.target.value)}
                          placeholder={t('Optional username')}
                          className="w-full bg-ui-input border border-ui-default px-2.5 py-1.5 rounded-ui-sm text-xs text-ui-primary placeholder:text-ui-muted/60"
                        />
                      </div>
                      <div className="space-y-1">
                        <label className="text-[11px] text-ui-muted block">{t('TURN Credential')}</label>
                        <input
                          type="password"
                          data-testid="settings-collab-turn-credential"
                          value={localSettings.collabTurnCredential || ''}
                          onChange={(e) => handleChange('collabTurnCredential', e.target.value)}
                          placeholder={t('Optional password / token')}
                          className="w-full bg-ui-input border border-ui-default px-2.5 py-1.5 rounded-ui-sm text-xs text-ui-primary placeholder:text-ui-muted/60"
                        />
                      </div>
                    </div>
                  </div>
                </section>

                <div className="rounded-ui-md bg-ui-header border border-ui-subtle p-3 flex items-start gap-2.5 text-[11px] text-ui-muted">
                  <Shield className="w-3.5 h-3.5 text-ui-icon-muted shrink-0 mt-0.5" />
                  <p className="leading-relaxed">
                    {t('Free public Google and Cloudflare STUN servers are included automatically for direct WebRTC P2P connections across PC and Android tablets.')}
                  </p>
                </div>
              </div>
            )}

            {activeTab === 'brush' && (
              <>
                <PressureCurveEditor
                  value={localSettings.pressureCurve}
                  onChange={(nextCurve) => handleChange('pressureCurve', nextCurve)}
                />

                <section className="space-y-2">
                  <div className="flex items-center justify-between">
                    <h3 className="text-xs font-medium text-ui-primary">{t('Default Stabilization')}</h3>
                    <span className="font-ui-mono tabular-nums text-xs text-ui-primary">
                      {localSettings.defaultStabilization}
                    </span>
                  </div>
                  <input
                    type="range"
                    min="0"
                    max="50"
                    value={localSettings.defaultStabilization}
                    onChange={(e) => handleChange('defaultStabilization', Number(e.target.value))}
                    className="w-full"
                  />
                </section>

                <section className="space-y-1 bg-ui-header border border-ui-subtle rounded-ui-md p-2.5">
                  <label className="flex items-center justify-between py-1 cursor-pointer">
                    <span className="text-xs text-ui-primary">{t('Stylus Pressure Sensitivity')}</span>
                    <input
                      type="checkbox"
                      checked={localSettings.usePressureByDefault}
                      onChange={(e) => handleChange('usePressureByDefault', e.target.checked)}
                    />
                  </label>
                  <label className="flex items-center justify-between py-1 cursor-pointer">
                    <span className="text-xs text-ui-primary">{t('Bezier Curve Smoothing')}</span>
                    <input
                      type="checkbox"
                      checked={localSettings.smoothingEnabled}
                      onChange={(e) => handleChange('smoothingEnabled', e.target.checked)}
                    />
                  </label>
                  <label className="flex items-start justify-between gap-3 py-1.5 pt-2 mt-1 border-t border-ui-subtle cursor-pointer">
                    <div className="min-w-0">
                      <div className="text-xs text-ui-primary">
                        {t('QuickShape (Hold Pen to Snap Shape)')}
                      </div>
                      <p className="text-[10px] text-ui-muted leading-relaxed mt-0.5">
                        {t('Hold the stylus still (~350 ms) at the end of a freehand stroke to snap it into a smooth line, arc, circle, ellipse, triangle, or rectangle, then drag handles or corners before lifting.')}
                      </p>
                    </div>
                    <input
                      type="checkbox"
                      data-testid="settings-quick-shape-toggle"
                      className="mt-0.5 shrink-0"
                      checked={Boolean(localSettings.quickShapeEnabled)}
                      onChange={(e) => handleChange('quickShapeEnabled', e.target.checked)}
                    />
                  </label>
                </section>

                <section className="space-y-2">
                  <h3 className="text-xs font-medium text-ui-primary">{t('Undo History Limit')}</h3>
                  <div className="grid grid-cols-4 gap-1.5">
                    {[25, 50, 75, 100].map((steps) => {
                      const selected = localSettings.maxHistorySteps === steps;
                      return (
                        <button
                          key={steps}
                          type="button"
                          onClick={() => handleChange('maxHistorySteps', steps)}
                          className={`py-1.5 rounded-ui-sm font-ui-mono tabular-nums text-xs cursor-pointer transition-colors border ${
                            selected
                              ? 'bg-ui-control-active text-ui-primary border-ui-accent-border font-medium'
                              : 'bg-ui-header text-ui-secondary border-ui-subtle hover:text-ui-primary hover:bg-ui-control-hover'
                          }`}
                        >
                          {steps}
                        </button>
                      );
                    })}
                  </div>
                </section>
              </>
            )}

            {activeTab === 'shortcuts' && (
              <div className="space-y-3">
                <div className="flex items-center gap-2">
                  <div className="relative flex-1">
                    <Search className="w-3.5 h-3.5 text-ui-icon-muted absolute left-2.5 top-1/2 -translate-y-1/2" />
                    <input
                      type="text"
                      placeholder={t('Search commands or keys...')}
                      value={searchQuery}
                      onChange={(e) => setSearchQuery(e.target.value)}
                      onKeyDown={(e) => {
                        if (isImeComposing(e)) e.stopPropagation();
                      }}
                      className="w-full bg-ui-input border border-ui-default rounded-ui-sm pl-8 pr-3 py-1.5 text-xs text-ui-primary placeholder:text-ui-muted"
                    />
                  </div>
                  <button
                    type="button"
                    onClick={handleResetAllShortcuts}
                    className="flex items-center gap-1 px-2.5 py-1.5 rounded-ui-sm bg-ui-control hover:bg-ui-control-hover border border-ui-subtle text-[11px] text-ui-secondary hover:text-ui-primary cursor-pointer shrink-0 transition-colors"
                    title={t('Reset all keybindings to defaults')}
                  >
                    <RotateCcw className="w-3 h-3" />
                    <span>{t('Reset')}</span>
                  </button>
                </div>

                {/* Category Filter Pills */}
                <div className="flex flex-wrap gap-1">
                  {(['All', ...SHORTCUT_CATEGORIES] as const).map((cat) => {
                    const active = selectedCategory === cat;
                    return (
                      <button
                        key={cat}
                        type="button"
                        data-testid={`settings-shortcut-cat-${cat}`}
                        onClick={() => setSelectedCategory(cat)}
                        className={`px-2.5 py-1 rounded-ui-sm text-[11px] transition-colors cursor-pointer border ${
                          active
                            ? 'bg-ui-control-active text-ui-primary font-medium border-ui-accent-border'
                            : 'bg-ui-header text-ui-secondary border-ui-subtle hover:text-ui-primary hover:bg-ui-control-hover'
                        }`}
                      >
                        {cat === 'All' ? t('All') : td(cat)}
                      </button>
                    );
                  })}
                </div>

                {/* OS/Win Key Support & Active Recording Helper Bar */}
                {recordingCommandId ? (
                  <div
                    data-testid="settings-shortcut-recording-bar"
                    className="px-2.5 py-2 rounded-ui-sm bg-ui-accent-subtle border border-ui-accent-border flex items-center justify-between gap-2 text-[11px]"
                  >
                    <div className="text-ui-primary min-w-0 truncate">
                      {t(
                        'Recording shortcut — press any key combo with Ctrl, {osKey}, Shift, or Alt (Esc to cancel)',
                        { osKey: osKeyLabel }
                      )}
                    </div>
                    <button
                      type="button"
                      data-testid="shortcut-record-os-toggle"
                      aria-pressed={recordWithOsModifier}
                      onClick={() => setRecordWithOsModifier((v) => !v)}
                      className={`px-2 py-0.5 rounded-ui-xs font-ui-mono text-[10px] shrink-0 cursor-pointer border transition-colors ${
                        recordWithOsModifier
                          ? 'bg-ui-accent text-ui-accent-contrast border-transparent font-semibold'
                          : 'bg-ui-input text-ui-secondary border-ui-default hover:bg-ui-control-hover hover:text-ui-primary'
                      }`}
                      title={t('Combine the next key press with the {osKey} (OS) modifier key', {
                        osKey: osKeyLabel,
                      })}
                    >
                      + {osKeyLabel} {recordWithOsModifier ? 'ON' : ''}
                    </button>
                  </div>
                ) : (
                  <div className="text-[10px] text-ui-muted px-0.5">
                    {t(
                      'Click any key badge to rebind. Supports Ctrl, {osKey} (OS), Shift, and Alt — including direct shortcuts for custom sub tools & groups.',
                      { osKey: osKeyLabel }
                    )}
                  </div>
                )}

                {/* Conflict Resolution Banner */}
                {pendingConflict && (
                  <div className="p-2.5 rounded-ui-sm bg-ui-warning/15 border border-ui-warning/40 flex items-center justify-between gap-2 text-[11px]">
                    <div className="flex items-center gap-2 text-ui-warning">
                      <AlertTriangle className="w-4 h-4 shrink-0 text-ui-warning" />
                      <span>
                        {t('{shortcut} conflicts with {commands}. Reassign anyway?', {
                          shortcut: formatShortcutLabel(pendingConflict.shortcut),
                          commands: pendingConflict.conflicts.map((c) => td(c.label)).join(', '),
                        })}
                      </span>
                    </div>
                    <div className="flex items-center gap-1.5 shrink-0">
                      <button
                        type="button"
                        onClick={handleConfirmConflictReplace}
                        className="px-2 py-1 rounded-ui-xs bg-ui-accent text-ui-accent-contrast hover:opacity-90 font-medium cursor-pointer"
                      >
                        {tc('shortcut', 'Replace')}
                      </button>
                      <button
                        type="button"
                        onClick={() => setPendingConflict(null)}
                        className="px-2 py-1 rounded-ui-xs bg-ui-control text-ui-primary hover:bg-ui-control-hover border border-ui-default cursor-pointer"
                      >
                        {t('Cancel')}
                      </button>
                    </div>
                  </div>
                )}

                <div className="space-y-0.5">
                  {filteredCommands.map((cmd) => {
                    const activeKey = resolveCommandShortcut(cmd, localSettings.shortcuts);
                    const isRecording = recordingCommandId === cmd.id;
                    const isOverridden = Object.prototype.hasOwnProperty.call(
                      localSettings.shortcuts,
                      cmd.id
                    );
                    return (
                      <div
                        key={cmd.id}
                        className="flex items-center justify-between gap-2 px-2.5 py-1.5 rounded-ui-sm hover:bg-ui-control-hover/60"
                      >
                        <div className="min-w-0">
                          <div className="flex items-center gap-1.5">
                            <span className="text-xs text-ui-primary truncate">{td(cmd.label)}</span>
                            <span className="text-[9px] px-1.5 py-0.5 rounded-ui-xs bg-ui-header border border-ui-subtle text-ui-muted">
                              {td(cmd.category)}
                            </span>
                            {cmd.groupBadge && (
                              <span className="text-[9px] px-1.5 py-0.5 rounded-ui-xs bg-ui-control text-ui-secondary shrink-0">
                                {td(cmd.groupBadge)}
                              </span>
                            )}
                            {cmd.springLoaded && (
                              <span
                                className="text-[9px] px-1.5 py-0.5 rounded-ui-xs bg-ui-accent-subtle text-ui-accent"
                                title={t('Hold key > 250ms to temporarily activate and revert on release')}
                              >
                                {t('Hold')}
                              </span>
                            )}
                          </div>
                          <div className="text-[10px] text-ui-muted truncate">
                            {td(cmd.description)}
                          </div>
                        </div>

                        <div className="flex items-center gap-1 shrink-0">
                          <button
                            type="button"
                            data-testid={`settings-shortcut-record-${cmd.id}`}
                            onClick={() => {
                              setPendingConflict(null);
                              setRecordWithOsModifier(false);
                              setRecordingCommandId(isRecording ? null : cmd.id);
                            }}
                            className={`px-2 py-1 rounded-ui-xs font-ui-mono text-[10px] min-w-[84px] text-center transition-colors cursor-pointer border ${
                              isRecording
                                ? 'bg-ui-accent text-ui-accent-contrast border-transparent font-semibold'
                                : activeKey
                                ? 'bg-ui-input text-ui-primary border-ui-default hover:bg-ui-control-hover'
                                : 'bg-ui-input text-ui-muted border-ui-subtle italic hover:bg-ui-control-hover'
                            }`}
                            title={t('Click and press a key combination to rebind')}
                          >
                            {isRecording ? t('Press keys...') : formatShortcutLabel(activeKey)}
                          </button>
                          {activeKey && (
                            <button
                              type="button"
                              onClick={() => handleClearSingleShortcut(cmd.id)}
                              className="w-6 h-6 rounded-ui-xs flex items-center justify-center text-ui-muted hover:text-ui-primary hover:bg-ui-control-hover cursor-pointer"
                              title={t('Unbind shortcut')}
                            >
                              <X className="w-3 h-3" />
                            </button>
                          )}
                          {isOverridden && (
                            <button
                              type="button"
                              onClick={() => handleResetSingleShortcut(cmd.id)}
                              className="w-6 h-6 rounded-ui-xs flex items-center justify-center text-ui-muted hover:text-ui-primary hover:bg-ui-control-hover cursor-pointer"
                              title={t('Reset to default ({shortcut})', {
                                shortcut: formatShortcutLabel(cmd.defaultShortcut),
                              })}
                            >
                              <RotateCcw className="w-3 h-3" />
                            </button>
                          )}
                        </div>
                      </div>
                    );
                  })}
                </div>
              </div>
            )}

            {activeTab === 'modifiers' && (
              <div className="space-y-4">
                <div className="flex items-center justify-between">
                  <div>
                    <h3 className="text-xs font-medium text-ui-primary">{t('Modifier Key Settings')}</h3>
                    <p className="text-[11px] text-ui-muted">
                      {t('Configure hold-to-act keys, mouse buttons, stylus barrel buttons, and scroll wheel')}
                    </p>
                  </div>
                  <button
                    type="button"
                    onClick={handleResetModifiers}
                    className="flex items-center gap-1 px-2.5 py-1 rounded-ui-sm bg-ui-control hover:bg-ui-control-hover border border-ui-subtle text-[11px] text-ui-secondary hover:text-ui-primary cursor-pointer transition-colors"
                  >
                    <RotateCcw className="w-3 h-3" />
                    <span>{t('Reset')}</span>
                  </button>
                </div>

                {/* Mouse Wheel */}
                <div className="flex items-center justify-between gap-3 px-3 py-2 rounded-ui-md bg-ui-header border border-ui-subtle">
                  <div>
                    <div className="text-xs text-ui-primary font-medium">{t('Mouse Wheel')}</div>
                    <div className="text-[10px] text-ui-muted">
                      {t('Action when scrolling wheel over the canvas viewport')}
                    </div>
                  </div>
                  <select
                    value={localSettings.modifierKeys.mouseWheel}
                    onChange={(e) => handleMouseWheelChange(e.target.value as MouseWheelAction)}
                    className="bg-ui-input text-ui-primary text-xs px-2.5 py-1.5 rounded-ui-sm border border-ui-default cursor-pointer"
                  >
                    {MOUSE_WHEEL_OPTIONS.map((opt) => (
                      <option key={opt.value} value={opt.value}>
                        {t(opt.label)}
                      </option>
                    ))}
                  </select>
                </div>

                {/* Keyboard, Mouse & Stylus Modifier Slots */}
                <div className="space-y-1">
                  {MODIFIER_SLOTS.map(({ slot, label, desc }) => (
                    <div
                      key={slot}
                      className="flex items-center justify-between gap-3 px-3 py-2 rounded-ui-md bg-ui-header border border-ui-subtle"
                    >
                      <div className="min-w-0">
                        <div className="text-xs text-ui-primary font-ui-mono">{t(label)}</div>
                        <div className="text-[10px] text-ui-muted truncate">{t(desc)}</div>
                      </div>
                      <select
                        value={localSettings.modifierKeys[slot]}
                        onChange={(e) =>
                          handleModifierSlotChange(slot, e.target.value as ModifierAction)
                        }
                        className="bg-ui-input text-ui-primary text-xs px-2.5 py-1.5 rounded-ui-sm border border-ui-default cursor-pointer shrink-0"
                      >
                        {MODIFIER_ACTION_OPTIONS.map((opt) => (
                          <option key={opt.value} value={opt.value}>
                            {t(opt.label)}
                          </option>
                        ))}
                      </select>
                    </div>
                  ))}
                </div>
              </div>
            )}

            {activeTab === 'about' && (
              <div className="space-y-4">
                <div className="p-4 rounded-ui-md bg-ui-header border border-ui-subtle flex items-center gap-3.5">
                  <img
                    src="/app-icon.png"
                    alt="Ink Studio"
                    className="w-10 h-10 object-contain shrink-0"
                  />
                  <div>
                    <h2 className="text-sm font-semibold text-ui-primary">Ink Studio</h2>
                    <p className="text-[11px] font-ui-mono tabular-nums text-ui-muted">
                      {t('v{version} · Collaborative Drawing Studio · by Sora', {
                        version: runtimeAppVersion || APP_VERSION,
                      })}
                    </p>
                  </div>
                </div>
                <p className="text-xs text-ui-muted leading-relaxed">
                  {t('Collaborative Drawing Studio supporting layered PSD/CSP workflows, GPU tile compositing, stylus pressure dynamics, vector inking, and real-time multiplayer drawing.')}
                </p>

                {(() => {
                  const activeVer = runtimeAppVersion || APP_VERSION;
                  const changelogEntry =
                    getChangelogForVersion(activeVer) ?? getChangelogForVersion();
                  if (!changelogEntry) return null;
                  return (
                    <section className="space-y-2 pt-2 border-t border-ui-subtle">
                      <div className="flex items-center justify-between">
                        <h3 className="text-xs font-medium text-ui-primary tabular-nums">
                          {t("What's New in v{version}", { version: changelogEntry.version })}
                        </h3>
                      </div>
                      <ChangelogBox entry={changelogEntry} maxHeightClass="max-h-48" />
                    </section>
                  );
                })()}

                {isDesktopTauri && (
                  <section className="space-y-2.5 pt-2 border-t border-ui-subtle">
                    <div>
                      <h3 className="text-xs font-medium text-ui-primary">{t('Updates')}</h3>
                      <p className="text-[11px] text-ui-muted">
                        {t('Keep Ink Studio up to date with the latest desktop releases')}
                      </p>
                    </div>

                    <div className="bg-ui-header border border-ui-subtle rounded-ui-md p-3 space-y-3">
                      <label className="flex items-center justify-between py-0.5 cursor-pointer">
                        <span className="text-xs text-ui-primary">
                          {t('Automatically check for updates on startup')}
                        </span>
                        <input
                          type="checkbox"
                          checked={localSettings.autoCheckUpdates}
                          onChange={(e) => handleChange('autoCheckUpdates', e.target.checked)}
                        />
                      </label>

                      <div className="pt-2.5 border-t border-ui-subtle flex items-center justify-between gap-3">
                        <div className="min-w-0 text-[11px]">
                          {updaterStatus === 'checking' && (
                            <span className="text-ui-muted">{t('Checking for updates...')}</span>
                          )}
                          {updaterStatus === 'up-to-date' && (
                            <span className="text-ui-success">{t('Up to date')}</span>
                          )}
                          {updaterStatus === 'available' && availableUpdateVersion && (
                            <span className="text-ui-accent font-medium tabular-nums">
                              {t('Update v{version} available', { version: availableUpdateVersion })}
                            </span>
                          )}
                          {updaterStatus === 'downloading' && (
                            <span className="text-ui-accent font-ui-mono tabular-nums">
                              {t('Downloading update... {percent}%', {
                                percent: updateProgressPercent,
                              })}
                            </span>
                          )}
                          {updaterStatus === 'ready' && (
                            <span className="text-ui-success">
                              {t('Update ready — restarting...')}
                            </span>
                          )}
                          {updaterStatus === 'error' && (
                            <span className="text-ui-danger break-words">
                              {updateErrorMessage || t('Failed to check for updates')}
                            </span>
                          )}
                          {updaterStatus === 'idle' && (
                            <span className="text-ui-muted">
                              {t('Current version: v{version}', {
                                version: runtimeAppVersion || APP_VERSION,
                              })}
                            </span>
                          )}
                        </div>

                        <div className="flex items-center gap-2 shrink-0">
                          {(updaterStatus === 'available' || updaterStatus === 'downloading') && (
                            <button
                              type="button"
                              onClick={() => {
                                onClose();
                                updaterService.openUpdateModal();
                              }}
                              className="flex items-center gap-1.5 px-2.5 py-1.5 rounded-ui-sm bg-ui-accent text-ui-accent-contrast hover:opacity-90 text-[11px] font-medium transition-opacity cursor-pointer"
                            >
                              <ArrowDownToLine className="w-3 h-3" />
                              <span>
                                {updaterStatus === 'downloading'
                                  ? t('View Progress')
                                  : t('View Update')}
                              </span>
                            </button>
                          )}

                          <button
                            type="button"
                            disabled={
                              updaterStatus === 'checking' ||
                              updaterStatus === 'downloading' ||
                              updaterStatus === 'ready'
                            }
                            onClick={() => void updaterService.checkForUpdates({ silent: false })}
                            className="flex items-center gap-1.5 px-2.5 py-1.5 rounded-ui-sm bg-ui-control hover:bg-ui-control-hover border border-ui-default disabled:opacity-50 disabled:cursor-not-allowed text-ui-primary text-[11px] font-medium transition-colors cursor-pointer"
                          >
                            {updaterStatus === 'checking' ? (
                              <Loader2 className="w-3 h-3 animate-spin text-ui-accent" />
                            ) : (
                              <RefreshCw className="w-3 h-3" />
                            )}
                            <span>{t('Check for Updates')}</span>
                          </button>
                        </div>
                      </div>
                    </div>
                  </section>
                )}
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
};