Skip to content

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

34.9 KB
Raw Blame
import React, { useCallback, useEffect, useId, useMemo, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
import {
  ArrowDown,
  ArrowLeft,
  ArrowRight,
  ArrowUp,
  Eye,
  EyeOff,
  Lock,
  Plus,
  Sliders,
  SlidersHorizontal,
  Trash2,
  Unlock,
  X,
} from 'lucide-react';
import { BrushPresetId, CspBrush, isPaintTool } from '../types/editor';
import { QuickBrushTileSize } from '../types/workspace';
import { migrateLegacyPresetId } from '../utils/brushPresetManager';
import {
  uiStoreActions,
  useToolStore,
  useUiStore,
  useWorkspaceStore,
  workspaceStoreActions,
} from '../stores';
import { resolveAppearanceTokens } from '../utils/themeEngine';
import {
  DND_BRUSH_MIME,
  DND_QUICK_BRUSH_REORDER_MIME,
  ResolvedQuickBrush,
  activateQuickBrush,
  clampQuickBrushPosition,
  getCategoryAccentStyle,
  resolveQuickBrush,
} from '../utils/quickBrushUtils';
import { BrushPreview } from './BrushPreview';
import { QuickBrushPanelSettings } from './QuickBrushPanelSettings';
import { isImeComposing, useI18n } from '../i18n';

export interface QuickBrushPanelProps {
  customBrushes: CspBrush[];
}

interface TileDimensions {
  width: number;
  height: number;
  iconSize: number;
  strokeWidth: number;
  strokeHeight: number;
}

function getTileDimensions(tileSize: QuickBrushTileSize, showNames: boolean): TileDimensions {
  if (tileSize === 'compact') {
    return showNames
      ? { width: 56, height: 50, iconSize: 24, strokeWidth: 46, strokeHeight: 24 }
      : { width: 40, height: 40, iconSize: 24, strokeWidth: 32, strokeHeight: 26 };
  }
  if (tileSize === 'large') {
    return showNames
      ? { width: 84, height: 74, iconSize: 42, strokeWidth: 70, strokeHeight: 38 }
      : { width: 58, height: 58, iconSize: 38, strokeWidth: 48, strokeHeight: 38 };
  }
  // medium (default — closely matches the sleek reference proportions)
  return showNames
    ? { width: 68, height: 60, iconSize: 32, strokeWidth: 56, strokeHeight: 30 }
    : { width: 48, height: 48, iconSize: 30, strokeWidth: 38, strokeHeight: 30 };
}

/** 6-dot drag grip icon matching the subtle tactile grip in vertical & horizontal floating bars */
const GripDotsIcon: React.FC<{ orientation: 'vertical' | 'horizontal'; locked: boolean }> = ({
  orientation,
  locked,
}) => {
  const dots =
    orientation === 'vertical'
      ? [
          [2, 2],
          [6, 2],
          [10, 2],
          [2, 6],
          [6, 6],
          [10, 6],
        ]
      : [
          [2, 2],
          [6, 2],
          [2, 6],
          [6, 6],
          [2, 10],
          [6, 10],
        ];
  const vb = orientation === 'vertical' ? '0 0 12 8' : '0 0 8 12';
  const w = orientation === 'vertical' ? 12 : 8;
  const h = orientation === 'vertical' ? 8 : 12;

  return (
    <svg
      width={w}
      height={h}
      viewBox={vb}
      aria-hidden="true"
      className={locked ? 'opacity-30' : 'opacity-65 group-hover:opacity-100 transition-opacity'}
    >
      {dots.map(([cx, cy], i) => (
        <circle key={i} cx={cx} cy={cy} r="1.05" fill="currentColor" />
      ))}
    </svg>
  );
};

/** Crisp theme-adaptive brush tip dab thumbnail matching the quick-brush aesthetic */
const BrushTipThumbnail: React.FC<{
  brush: ResolvedQuickBrush;
  size: number;
  isLightScheme: boolean;
}> = React.memo(({ brush, size, isLightScheme }) => {
  const gradId = useId();

  if (brush.tipDataUrl) {
    const scaleX = brush.thicknessVertical ? Math.max(0.28, Math.min(1, brush.thickness)) : 1;
    const scaleY = !brush.thicknessVertical ? Math.max(0.28, Math.min(1, brush.thickness)) : 1;
    const transformParts: string[] = [];
    if (brush.angle) transformParts.push(`rotate(${brush.angle}deg)`);
    if (scaleX !== 1 || scaleY !== 1) transformParts.push(`scale(${scaleX}, ${scaleY})`);

    return (
      <img
        src={brush.tipDataUrl}
        alt=""
        draggable={false}
        style={{
          width: size,
          height: size,
          transform: transformParts.length > 0 ? transformParts.join(' ') : undefined,
        }}
        className={`object-contain pointer-events-none select-none ${
          brush.isColorTip
            ? ''
            : isLightScheme
              ? 'invert'
              : 'drop-shadow-[0_1px_2px_rgba(0,0,0,0.45)]'
        }`}
      />
    );
  }

  // Analytical SVG dab for brushes without a bitmap tip (e.g. G-Pen, Dot Pen, Soft Glaze Airbrush, Velvet Blend, Eraser)
  const clampedHardness = Math.max(0, Math.min(1, brush.hardness));
  const rx = brush.thicknessVertical ? Math.max(12, Math.round(42 * Math.min(1, brush.thickness))) : 42;
  const ry = !brush.thicknessVertical ? Math.max(12, Math.round(42 * Math.min(1, brush.thickness))) : 42;
  const isSoft = clampedHardness < 0.9;
  const coreStop = Math.round(clampedHardness * 78);

  return (
    <svg
      width={size}
      height={size}
      viewBox="0 0 100 100"
      aria-hidden="true"
      className="pointer-events-none select-none overflow-visible text-ui-primary"
    >
      {isSoft && (
        <defs>
          <radialGradient id={gradId} cx="50%" cy="50%" r="50%">
            <stop offset="0%" stopColor="currentColor" stopOpacity="1" />
            <stop offset={`${coreStop}%`} stopColor="currentColor" stopOpacity="0.92" />
            <stop
              offset={`${Math.min(98, coreStop + Math.round((100 - coreStop) * 0.52))}%`}
              stopColor="currentColor"
              stopOpacity="0.34"
            />
            <stop offset="100%" stopColor="currentColor" stopOpacity="0" />
          </radialGradient>
        </defs>
      )}
      <g transform={brush.angle ? `rotate(${brush.angle} 50 50)` : undefined}>
        <ellipse
          cx="50"
          cy="50"
          rx={rx}
          ry={ry}
          fill={isSoft ? `url(#${gradId})` : 'currentColor'}
          stroke={brush.isEraser ? 'var(--ui-danger)' : undefined}
          strokeWidth={brush.isEraser ? 5 : undefined}
          strokeDasharray={brush.isEraser ? '9 6' : undefined}
        />
      </g>
    </svg>
  );
});
BrushTipThumbnail.displayName = 'BrushTipThumbnail';

export const QuickBrushPanel: React.FC<QuickBrushPanelProps> = React.memo(({ customBrushes }) => {
  const { t, td } = useI18n();
  const config = useWorkspaceStore((s) => s.quickBrushPanel);
  const palettesHidden = useWorkspaceStore((s) => s.palettesHidden);
  const autoFadeInFocus = useWorkspaceStore(
    (s) => s.palettesHidden && s.focusHud.autoFadeWhileDrawing
  );
  const showStatusBar = useWorkspaceStore((s) => s.showStatusBar);
  const leftHandedMode = useWorkspaceStore((s) => s.leftHandedMode);
  const activeTool = useToolStore((s) => s.tool);
  const activePresetId = useToolStore((s) => s.activePresetId);
  const appearance = useUiStore((s) => s.appSettings.appearance);
  const isDrawingInFocus = useUiStore((s) => (autoFadeInFocus ? s.isDrawing : false));

  const resolvedTheme = useMemo(() => resolveAppearanceTokens(appearance), [appearance]);
  const isLightScheme = resolvedTheme.colorScheme === 'light';
  const previewInkColor = resolvedTheme.tokens['--ui-text-primary'];

  const panelRef = useRef<HTMLDivElement>(null);
  const scrollRef = useRef<HTMLDivElement>(null);
  const settingsBtnRef = useRef<HTMLButtonElement>(null);
  const contextMenuRef = useRef<HTMLDivElement>(null);

  const [isDraggingPanel, setIsDraggingPanel] = useState(false);
  const [settingsOpen, setSettingsOpen] = useState(false);
  const [settingsInitialTab, setSettingsInitialTab] = useState<'settings' | 'brushes'>('settings');
  const [isDropTargetOver, setIsDropTargetOver] = useState(false);
  const [draggedTileId, setDraggedTileId] = useState<BrushPresetId | null>(null);
  const [dragOverTileId, setDragOverTileId] = useState<BrushPresetId | null>(null);
  const [tileContextMenu, setTileContextMenu] = useState<{
    brush: ResolvedQuickBrush;
    index: number;
    x: number;
    y: number;
  } | null>(null);

  const isShouldRender =
    config.visible && (!palettesHidden || config.keepVisibleWhenPalettesHidden);

  const resolvedBrushes = useMemo(
    () =>
      config.brushIds
        .map((id) => resolveQuickBrush(id, customBrushes))
        .filter((b): b is ResolvedQuickBrush => b !== null),
    [config.brushIds, customBrushes]
  );

  const tileDim = useMemo(
    () => getTileDimensions(config.tileSize, config.showNames),
    [config.tileSize, config.showNames]
  );

  // Close settings or tile context menu if panel hides
  useEffect(() => {
    if (!isShouldRender) {
      setSettingsOpen(false);
      setTileContextMenu(null);
    }
  }, [isShouldRender]);

  // Keep custom-positioned floating bar clamped inside viewport on window resize or orientation change
  useEffect(() => {
    if (!isShouldRender || !config.position) return;
    const clampNow = () => {
      const el = panelRef.current;
      const curPos = useWorkspaceStore.getState().quickBrushPanel.position;
      if (!el || !curPos) return;
      const rect = el.getBoundingClientRect();
      const clamped = clampQuickBrushPosition(curPos.x, curPos.y, rect.width, rect.height);
      if (clamped.x !== curPos.x || clamped.y !== curPos.y) {
        workspaceStoreActions.setQuickBrushPanelPosition(clamped, false);
      }
    };
    const raf = requestAnimationFrame(clampNow);
    window.addEventListener('resize', clampNow);
    return () => {
      cancelAnimationFrame(raf);
      window.removeEventListener('resize', clampNow);
    };
  }, [
    isShouldRender,
    config.position,
    config.orientation,
    config.columns,
    config.tileSize,
    resolvedBrushes.length,
  ]);

  // Close tile context menu on outside click / Escape
  useEffect(() => {
    if (!tileContextMenu) return;
    const handleOutside = (e: MouseEvent) => {
      if (contextMenuRef.current?.contains(e.target as Node)) return;
      setTileContextMenu(null);
    };
    const handleKey = (e: KeyboardEvent) => {
      if (isImeComposing(e)) return;
      if (e.key === 'Escape') setTileContextMenu(null);
    };
    window.addEventListener('mousedown', handleOutside);
    window.addEventListener('keydown', handleKey);
    return () => {
      window.removeEventListener('mousedown', handleOutside);
      window.removeEventListener('keydown', handleKey);
    };
  }, [tileContextMenu]);

  const handleStartPanelDrag = useCallback(
    (e: React.PointerEvent<HTMLDivElement>) => {
      if (e.button !== 0 || config.locked) return;
      const el = panelRef.current;
      if (!el) return;

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

      const rect = el.getBoundingClientRect();
      const startX = e.clientX;
      const startY = e.clientY;
      const origX = rect.left;
      const origY = rect.top;
      const panelW = rect.width;
      const panelH = rect.height;
      let moved = false;

      const onMove = (ev: PointerEvent) => {
        const dx = ev.clientX - startX;
        const dy = ev.clientY - startY;
        if (!moved) {
          if (Math.hypot(dx, dy) < 4) return;
          moved = true;
          setIsDraggingPanel(true);
          setSettingsOpen(false);
          setTileContextMenu(null);
        }
        const nextPos = clampQuickBrushPosition(origX + dx, origY + dy, panelW, panelH);
        workspaceStoreActions.setQuickBrushPanelPosition(nextPos, false);
      };

      const cleanup = () => {
        window.removeEventListener('pointermove', onMove);
        window.removeEventListener('pointerup', onUp);
        window.removeEventListener('pointercancel', onCancel);
        setIsDraggingPanel(false);
      };

      const onUp = (ev: PointerEvent) => {
        const wasMoved = moved;
        cleanup();
        if (wasMoved) {
          const finalPos = clampQuickBrushPosition(
            origX + (ev.clientX - startX),
            origY + (ev.clientY - startY),
            panelW,
            panelH
          );
          workspaceStoreActions.setQuickBrushPanelPosition(finalPos, true);
        }
      };

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

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

  const handleDropOnPanel = useCallback(
    (e: React.DragEvent) => {
      e.preventDefault();
      e.stopPropagation();
      setIsDropTargetOver(false);
      setDragOverTileId(null);
      if (config.locked) return;

      const incomingBrushId = e.dataTransfer.getData(DND_BRUSH_MIME);
      if (incomingBrushId) {
        const resolved = resolveQuickBrush(incomingBrushId, customBrushes);
        const brushLabel = resolved ? td(resolved.name, 'brushName') : t('Brush');
        const added = workspaceStoreActions.addQuickBrush(incomingBrushId);
        if (added) {
          uiStoreActions.showToast(t('Added "{name}" to Quick Brushes', { name: brushLabel }));
        } else {
          uiStoreActions.showToast(t('"{name}" is already in Quick Brushes', { name: brushLabel }));
        }
      }
      setDraggedTileId(null);
    },
    [config.locked, customBrushes, t, td]
  );

  const handleOpenSettings = (tab: 'settings' | 'brushes' = 'settings') => {
    setTileContextMenu(null);
    if (settingsOpen && settingsInitialTab === tab) {
      setSettingsOpen(false);
    } else {
      setSettingsInitialTab(tab);
      setSettingsOpen(true);
    }
  };

  if (!isShouldRender) return null;

  const isHorizontal = config.orientation === 'horizontal';
  const isFixed = config.position !== null;
  const activeNormalizedPreset = migrateLegacyPresetId(activePresetId);

  const containerPositionStyle: React.CSSProperties = isFixed
    ? {
        position: 'fixed',
        left: config.position!.x,
        top: config.position!.y,
        zIndex: isDraggingPanel ? 49 : 44,
      }
    : {
        zIndex: 36,
      };

  const autoAnchorClass = isFixed
    ? ''
    : isHorizontal
      ? `${showStatusBar ? 'bottom-9' : 'bottom-3'} absolute left-1/2 -translate-x-1/2`
      : leftHandedMode
        ? 'absolute left-3 top-1/2 -translate-y-1/2'
        : 'absolute right-3 top-1/2 -translate-y-1/2';

  const gridStyle: React.CSSProperties = isHorizontal
    ? {
        display: 'grid',
        gridAutoFlow: 'column',
        gridTemplateRows: `repeat(${config.columns}, ${tileDim.height}px)`,
        gridAutoColumns: `${tileDim.width}px`,
        gap: '5px',
      }
    : {
        display: 'grid',
        gridTemplateColumns: `repeat(${config.columns}, ${tileDim.width}px)`,
        gap: '5px',
      };

  const controlButtons = (
    <>
      <button
        type="button"
        data-testid="quick-brush-lock-btn"
        onClick={() => {
          const locked = workspaceStoreActions.toggleQuickBrushPanelLocked();
          uiStoreActions.showToast(
            locked ? t('Quick Brush Panel locked') : t('Quick Brush Panel unlocked')
          );
        }}
        title={config.locked ? t('Unlock Quick Brush Panel') : t('Lock Panel Position & Brushes')}
        aria-label={config.locked ? t('Unlock Quick Brush Panel') : t('Lock Quick Brush Panel')}
        aria-pressed={config.locked}
        className={`w-6 h-6 rounded-ui-xs flex items-center justify-center transition-colors cursor-pointer ${
          config.locked
            ? 'text-ui-accent bg-ui-control-active'
            : 'text-ui-muted hover:text-ui-primary hover:bg-ui-control-hover'
        }`}
      >
        {config.locked ? <Lock className="w-3.5 h-3.5" /> : <Unlock className="w-3.5 h-3.5" />}
      </button>

      <button
        ref={settingsBtnRef}
        type="button"
        data-testid="quick-brush-settings-btn"
        onClick={() => handleOpenSettings('settings')}
        title={t('Quick Brush Panel Settings')}
        aria-label={t('Quick Brush Panel Settings')}
        aria-expanded={settingsOpen}
        className={`w-6 h-6 rounded-ui-xs flex items-center justify-center transition-colors cursor-pointer ${
          settingsOpen
            ? 'text-ui-accent bg-ui-control-active'
            : 'text-ui-muted hover:text-ui-primary hover:bg-ui-control-hover'
        }`}
      >
        <SlidersHorizontal className="w-3.5 h-3.5" />
      </button>

      <button
        type="button"
        data-testid="quick-brush-close-btn"
        onClick={() => {
          setSettingsOpen(false);
          workspaceStoreActions.setQuickBrushPanelVisible(false);
          uiStoreActions.showToast(t('Quick Brush Panel hidden (Shift+B to reopen)'));
        }}
        title={t('Hide Quick Brush Panel (Shift+B)')}
        aria-label={t('Hide Quick Brush Panel')}
        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 transition-colors cursor-pointer"
      >
        <X className="w-3.5 h-3.5" />
      </button>

      {config.showHideUiButton && (
        <button
          type="button"
          data-testid="quick-brush-hide-ui-btn"
          onClick={() => workspaceStoreActions.togglePalettesHidden()}
          title={palettesHidden ? t('Show All Palettes (Tab)') : t('Hide All Other Palettes (Tab)')}
          aria-label={palettesHidden ? t('Show All Palettes') : t('Hide All Other Palettes')}
          aria-pressed={palettesHidden}
          className={`w-6 h-6 rounded-ui-xs flex items-center justify-center transition-colors cursor-pointer ${
            palettesHidden
              ? 'text-ui-accent bg-ui-control-active'
              : 'text-ui-muted hover:text-ui-primary hover:bg-ui-control-hover'
          }`}
        >
          {palettesHidden ? <Eye className="w-3.5 h-3.5" /> : <EyeOff className="w-3.5 h-3.5" />}
        </button>
      )}
    </>
  );

  const isAutoFaded = Boolean(
    isDrawingInFocus && !isDraggingPanel && !settingsOpen && !tileContextMenu
  );
  const useBlur = config.opacity < 0.98 || appearance.floatingOpacity < 0.98;

  const panelElement = (
    <div
      ref={panelRef}
      data-testid="quick-brush-panel"
      data-orientation={config.orientation}
      data-locked={String(config.locked)}
      data-auto-faded={String(isAutoFaded)}
      data-anchor-side={isFixed ? 'custom' : isHorizontal ? 'bottom' : leftHandedMode ? 'left' : 'right'}
      role="toolbar"
      aria-label={t('Quick-Access Brush Panel')}
      onPointerDown={(e) => e.stopPropagation()}
      onWheel={(e) => e.stopPropagation()}
      onDragOver={(e) => {
        if (config.locked) return;
        if (
          e.dataTransfer.types.includes(DND_BRUSH_MIME) ||
          e.dataTransfer.types.includes(DND_QUICK_BRUSH_REORDER_MIME)
        ) {
          e.preventDefault();
          e.dataTransfer.dropEffect = e.dataTransfer.types.includes(DND_BRUSH_MIME) ? 'copy' : 'move';
          if (e.dataTransfer.types.includes(DND_BRUSH_MIME)) {
            setIsDropTargetOver(true);
          }
        }
      }}
      onDragLeave={(e) => {
        if (!panelRef.current?.contains(e.relatedTarget as Node)) {
          setIsDropTargetOver(false);
          setDragOverTileId(null);
        }
      }}
      onDrop={handleDropOnPanel}
      style={{
        ...containerPositionStyle,
        backgroundColor: `color-mix(in srgb, var(--ui-bg-elevated) ${Math.round(config.opacity * 100)}%, transparent)`,
        backdropFilter: useBlur ? 'blur(8px)' : 'none',
        WebkitBackdropFilter: useBlur ? 'blur(8px)' : 'none',
        opacity: isAutoFaded ? 0.22 : 1,
        pointerEvents: isAutoFaded ? 'none' : 'auto',
      }}
      className={`${autoAnchorClass} flex ${
        isHorizontal ? 'flex-row items-center px-1.5 py-1.5' : 'flex-col items-center px-1.5 py-1.5'
      } rounded-ui-lg border transition-[opacity,border-color,box-shadow] duration-150 select-none shadow-ui-floating ${
        isDropTargetOver
          ? 'border-ui-accent ring-1 ring-ui-accent-border'
          : isDraggingPanel
            ? 'border-ui-strong'
            : 'border-ui-default'
      }`}
    >
      {/* Drag Handle (+ rotated title in Horizontal mode matching reference layout) */}
      <div
        data-testid="quick-brush-drag-handle"
        onPointerDown={handleStartPanelDrag}
        onDoubleClick={() => {
          if (!config.locked) {
            workspaceStoreActions.toggleQuickBrushPanelOrientation();
          }
        }}
        title={
          config.locked
            ? t('Panel locked — unlock to drag or flip orientation')
            : t('Drag to move panel • Double-click to flip Vertical / Horizontal')
        }
        className={`group flex items-center justify-center shrink-0 text-ui-muted ${
          config.locked ? 'cursor-default' : 'cursor-grab active:cursor-grabbing hover:text-ui-primary'
        } ${
          isHorizontal
            ? 'flex-col gap-1 pr-1.5 py-0.5 self-stretch min-w-[20px]'
            : 'flex-row w-full pb-1.5 pt-0.5'
        }`}
      >
        <GripDotsIcon orientation={config.orientation} locked={config.locked} />
        {isHorizontal && config.showTitle && config.title.trim().length > 0 && (
          <span
            data-testid="quick-brush-title-label"
            style={{ writingMode: 'vertical-rl' }}
            className="text-[10px] font-medium tracking-wide text-ui-secondary max-h-[40px] overflow-hidden text-ellipsis whitespace-nowrap leading-none"
          >
            {td(config.title)}
          </span>
        )}
      </div>

      {/* Brush Tiles List / Grid */}
      <div
        ref={scrollRef}
        onWheel={(e) => {
          if (isHorizontal && scrollRef.current && Math.abs(e.deltaY) > Math.abs(e.deltaX)) {
            scrollRef.current.scrollLeft += e.deltaY;
          }
        }}
        className={
          isHorizontal
            ? 'overflow-x-auto overflow-y-hidden no-scrollbar max-w-[calc(100vw-160px)]'
            : 'overflow-y-auto overflow-x-hidden no-scrollbar max-h-[calc(100vh-160px)]'
        }
      >
        {resolvedBrushes.length === 0 ? (
          <button
            type="button"
            data-testid="quick-brush-empty-add-btn"
            onClick={() => handleOpenSettings('brushes')}
            style={{ width: Math.max(tileDim.width, 64), height: tileDim.height }}
            className="rounded-ui-md border border-dashed border-ui-default bg-ui-control hover:bg-ui-control-hover text-ui-muted hover:text-ui-primary flex flex-col items-center justify-center gap-1 text-[10px] cursor-pointer transition-colors"
            title={t('Add brushes to Quick-Access Brush Panel')}
          >
            <Plus className="w-4 h-4 text-ui-accent" />
            <span>{t('Add')}</span>
          </button>
        ) : (
          <div style={gridStyle}>
            {resolvedBrushes.map((brush, index) => {
              const displayName = td(brush.name, 'brushName');
              const displayDesc = brush.desc ? td(brush.desc) : '';
              const isSelected = brush.isEraser
                ? activeTool === 'eraser'
                : isPaintTool(activeTool) &&
                  migrateLegacyPresetId(brush.id) === activeNormalizedPreset;
              const accent = config.showCategoryColors
                ? getCategoryAccentStyle(brush.category)
                : { barColor: null, cardTint: null, label: '' };
              const isBeingDragged = draggedTileId === brush.id;
              const isDragTarget = dragOverTileId === brush.id && draggedTileId !== brush.id;

              const cardBg = isSelected
                ? 'var(--ui-bg-control-active)'
                : accent.cardTint
                  ? `linear-gradient(0deg, ${accent.cardTint}, ${accent.cardTint}), var(--ui-bg-control)`
                  : 'var(--ui-bg-control)';

              return (
                <div
                  key={brush.id}
                  data-testid={`quick-brush-tile-${brush.id}`}
                  data-selected={String(isSelected)}
                  draggable={!config.locked}
                  onDragStart={(e) => {
                    if (config.locked) return;
                    e.stopPropagation();
                    e.dataTransfer.setData(DND_QUICK_BRUSH_REORDER_MIME, brush.id);
                    e.dataTransfer.effectAllowed = 'move';
                    setDraggedTileId(brush.id);
                  }}
                  onDragOver={(e) => {
                    if (config.locked) return;
                    if (e.dataTransfer.types.includes(DND_QUICK_BRUSH_REORDER_MIME)) {
                      e.preventDefault();
                      e.stopPropagation();
                      e.dataTransfer.dropEffect = 'move';
                      setDragOverTileId(brush.id);
                    }
                  }}
                  onDrop={(e) => {
                    if (config.locked) return;
                    const reorderedId = e.dataTransfer.getData(DND_QUICK_BRUSH_REORDER_MIME);
                    if (reorderedId) {
                      e.preventDefault();
                      e.stopPropagation();
                      workspaceStoreActions.reorderQuickBrush(reorderedId, brush.id);
                      setDraggedTileId(null);
                      setDragOverTileId(null);
                    }
                  }}
                  onDragEnd={() => {
                    setDraggedTileId(null);
                    setDragOverTileId(null);
                  }}
                  onContextMenu={(e) => {
                    e.preventDefault();
                    e.stopPropagation();
                    setSettingsOpen(false);
                    const vw = typeof window !== 'undefined' ? window.innerWidth : 1280;
                    const vh = typeof window !== 'undefined' ? window.innerHeight : 800;
                    setTileContextMenu({
                      brush,
                      index,
                      x: Math.max(8, Math.min(vw - 176, e.clientX)),
                      y: Math.max(40, Math.min(vh - 150, e.clientY)),
                    });
                  }}
                  onClick={() => {
                    void activateQuickBrush(brush, customBrushes);
                  }}
                  role="button"
                  tabIndex={0}
                  onKeyDown={(e) => {
                    if (isImeComposing(e)) return;
                    if (e.key === 'Enter' || e.key === ' ') {
                      e.preventDefault();
                      void activateQuickBrush(brush, customBrushes);
                    }
                  }}
                  title={displayDesc ? `${displayName} — ${displayDesc}` : displayName}
                  style={{
                    width: tileDim.width,
                    height: tileDim.height,
                    background: cardBg,
                  }}
                  className={`group relative rounded-ui-md flex flex-col items-center justify-center overflow-hidden transition-all cursor-pointer border ${
                    isDragTarget
                      ? 'border-ui-accent ring-1 ring-ui-accent'
                      : isSelected
                        ? 'border-ui-accent ring-1 ring-ui-accent-border'
                        : 'border-ui-subtle hover:border-ui-strong'
                  } ${isBeingDragged ? 'opacity-45' : 'opacity-100'}`}
                >
                  {/* Subtle Category Left Accent Bar (like Blend purple / Natural Paint teal) */}
                  {accent.barColor && (
                    <span
                      aria-hidden="true"
                      style={{ backgroundColor: accent.barColor }}
                      className="absolute left-[3px] top-[5px] bottom-[5px] w-[2.5px] rounded-full opacity-90 pointer-events-none"
                    />
                  )}

                  {/* Brush Preview (Tip Dab or S-Curve Stroke) */}
                  <div
                    className={`flex items-center justify-center w-full ${
                      config.showNames ? 'flex-1 min-h-0 pt-1 px-1.5' : 'h-full p-1.5'
                    }`}
                  >
                    {config.previewStyle === 'stroke' ? (
                      <BrushPreview
                        preset={brush.id}
                        settings={brush.previewSettings}
                        tool={brush.isEraser ? 'eraser' : 'brush'}
                        strokeColor={previewInkColor}
                        width={tileDim.strokeWidth}
                        height={tileDim.strokeHeight}
                      />
                    ) : (
                      <BrushTipThumbnail
                        brush={brush}
                        size={tileDim.iconSize}
                        isLightScheme={isLightScheme}
                      />
                    )}
                  </div>

                  {/* Truncated Brush Name */}
                  {config.showNames && (
                    <span
                      className={`w-full px-1 pb-1 text-center text-[10px] leading-[1.15] truncate pointer-events-none ${
                        isSelected ? 'text-ui-primary font-medium' : 'text-ui-secondary'
                      }`}
                    >
                      {displayName}
                    </span>
                  )}

                  {/* Subtle hover remove badge when unlocked */}
                  {!config.locked && (
                    <button
                      type="button"
                      data-testid={`quick-brush-remove-${brush.id}`}
                      onClick={(e) => {
                        e.stopPropagation();
                        workspaceStoreActions.removeQuickBrush(brush.id);
                        uiStoreActions.showToast(
                          t('Removed "{name}" from Quick Brushes', { name: displayName })
                        );
                      }}
                      title={t('Remove {name}', { name: displayName })}
                      aria-label={t('Remove {name} from Quick Brushes', { name: displayName })}
                      className="opacity-0 group-hover:opacity-100 focus:opacity-100 absolute top-0.5 right-0.5 w-3.5 h-3.5 rounded-full bg-ui-elevated border border-ui-subtle hover:bg-ui-danger hover:border-ui-danger text-ui-muted hover:text-white flex items-center justify-center transition-opacity cursor-pointer"
                    >
                      <X className="w-2.5 h-2.5" />
                    </button>
                  )}
                </div>
              );
            })}
          </div>
        )}
      </div>

      {/* Control Buttons Cluster: Lock, Settings, Close (+ optional Hide UI) */}
      <div
        className={
          isHorizontal
            ? 'grid grid-cols-2 gap-0.5 pl-1.5 items-center justify-items-center shrink-0'
            : 'flex items-center justify-center gap-0.5 pt-1.5 shrink-0 flex-wrap'
        }
      >
        {controlButtons}
      </div>

      {/* Settings Popover (Portaled to document.body) */}
      {settingsOpen && (
        <QuickBrushPanelSettings
          anchorRef={settingsBtnRef}
          initialTab={settingsInitialTab}
          customBrushes={customBrushes}
          onClose={() => setSettingsOpen(false)}
        />
      )}

      {/* Right-Click Context Menu for Individual Brush Tiles */}
      {tileContextMenu &&
        typeof document !== 'undefined' &&
        createPortal(
          <div
            ref={contextMenuRef}
            data-testid="quick-brush-tile-context-menu"
            style={{
              position: 'fixed',
              left: tileContextMenu.x,
              top: tileContextMenu.y,
              zIndex: 1000,
            }}
            onPointerDown={(e) => e.stopPropagation()}
            className="w-44 rounded-ui-md bg-ui-elevated border border-ui-default shadow-ui-popover p-1 text-[11px] text-ui-primary select-none"
          >
            <div className="px-2 py-0.5 text-[10px] text-ui-muted truncate">
              {td(tileContextMenu.brush.name)}
            </div>
            <div className="my-0.5 border-t border-ui-subtle" />

            {!tileContextMenu.brush.isEraser && (
              <button
                type="button"
                onClick={async () => {
                  const target = tileContextMenu.brush;
                  setTileContextMenu(null);
                  await activateQuickBrush(target, customBrushes);
                  uiStoreActions.setBrushStudioModalOpen(true);
                }}
                className="w-full flex items-center gap-1.5 px-2 py-1 rounded-ui-sm hover:bg-ui-control-hover text-left cursor-pointer"
              >
                <Sliders className="w-3 h-3 text-ui-accent" />
                <span>{t('Edit in Brush Studio')}</span>
              </button>
            )}

            {!config.locked && (
              <>
                <button
                  type="button"
                  disabled={tileContextMenu.index === 0}
                  onClick={() => {
                    workspaceStoreActions.moveQuickBrush(tileContextMenu.brush.id, -1);
                    setTileContextMenu(null);
                  }}
                  className="w-full flex items-center gap-1.5 px-2 py-1 rounded-ui-sm hover:bg-ui-control-hover disabled:opacity-35 text-left cursor-pointer"
                >
                  {isHorizontal ? (
                    <ArrowLeft className="w-3 h-3 text-ui-muted" />
                  ) : (
                    <ArrowUp className="w-3 h-3 text-ui-muted" />
                  )}
                  <span>{isHorizontal ? t('Move Left') : t('Move Up')}</span>
                </button>

                <button
                  type="button"
                  disabled={tileContextMenu.index === resolvedBrushes.length - 1}
                  onClick={() => {
                    workspaceStoreActions.moveQuickBrush(tileContextMenu.brush.id, 1);
                    setTileContextMenu(null);
                  }}
                  className="w-full flex items-center gap-1.5 px-2 py-1 rounded-ui-sm hover:bg-ui-control-hover disabled:opacity-35 text-left cursor-pointer"
                >
                  {isHorizontal ? (
                    <ArrowRight className="w-3 h-3 text-ui-muted" />
                  ) : (
                    <ArrowDown className="w-3 h-3 text-ui-muted" />
                  )}
                  <span>{isHorizontal ? t('Move Right') : t('Move Down')}</span>
                </button>

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

                <button
                  type="button"
                  onClick={() => {
                    const target = tileContextMenu.brush;
                    workspaceStoreActions.removeQuickBrush(target.id);
                    uiStoreActions.showToast(
                      t('Removed "{name}" from Quick Brushes', { name: td(target.name) })
                    );
                    setTileContextMenu(null);
                  }}
                  className="w-full flex items-center gap-1.5 px-2 py-1 rounded-ui-sm hover:bg-ui-danger/15 text-ui-danger text-left cursor-pointer"
                >
                  <Trash2 className="w-3 h-3" />
                  <span>{t('Remove from Panel')}</span>
                </button>
              </>
            )}
          </div>,
          document.body
        )}
    </div>
  );

  // When dragged to custom fixed screen coordinates, portal to document.body so it floats freely
  // across the entire viewport without clipping; when auto-anchored, sit cleanly inside the center canvas area!
  return isFixed && typeof document !== 'undefined'
    ? createPortal(panelElement, document.body)
    : panelElement;
});

QuickBrushPanel.displayName = 'QuickBrushPanel';