Skip to content

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

41.6 KB
Raw Blame
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import {
  AlignCenter,
  AlignLeft,
  AlignRight,
  Bold,
  Check,
  GripVertical,
  Italic,
  Minus,
  Move,
  Pipette,
  Plus,
  RotateCcw,
  SlidersHorizontal,
  Trash2,
  Underline,
  X,
} from 'lucide-react';
import { TextSettings } from '../types/editor';
import { computeMangaTextLayout, renderMangaTextToCanvas } from '../utils/mangaTextEngine';
import {
  DEFAULT_TEXT_SETTINGS,
  getTextFontOptions,
  queryInstalledSystemFonts,
  TEXT_FONT_PRESETS,
  TEXT_QUICK_COLORS,
} from '../utils/textSettings';
import { isImeComposing, useI18n } from '../i18n';

interface TextEditorOverlayProps {
  x: number;
  y: number;
  settings: TextSettings;
  editingLayerId?: string | null;
  primaryColor?: string;
  zoom: number;
  rotation?: number;
  flipX?: boolean;
  flipY?: boolean;
  onUpdateSettings: (updater: (prev: TextSettings) => TextSettings) => void;
  onMove: (newX: number, newY: number) => void;
  onConfirm: () => void;
  onCancel: () => void;
  onDelete?: () => void;
}

export const MANGA_FONTS = TEXT_FONT_PRESETS.map((f) => ({ id: f.value, label: f.label }));

export const TextEditorOverlay: React.FC<TextEditorOverlayProps> = ({
  x,
  y,
  settings,
  editingLayerId = null,
  primaryColor,
  zoom,
  rotation = 0,
  flipX = false,
  flipY = false,
  onUpdateSettings,
  onMove,
  onConfirm,
  onCancel,
  onDelete,
}) => {
  const { t, tc, td } = useI18n();
  const textareaRef = useRef<HTMLTextAreaElement | null>(null);
  const previewCanvasRef = useRef<HTMLCanvasElement | null>(null);

  const [showMoreStyle, setShowMoreStyle] = useState(false);
  const [showColorPopover, setShowColorPopover] = useState(false);
  const [systemFonts, setSystemFonts] = useState<string[]>([]);
  const [fontSizeInput, setFontSizeInput] = useState<string>(String(settings.fontSize));

  const isVertical = settings.writingMode === 'vertical-rl';
  const safeZoom = zoom > 0.05 ? zoom : 1;
  const invScaleX = (flipX ? -1 : 1) / safeZoom;
  const invScaleY = (flipY ? -1 : 1) / safeZoom;

  useEffect(() => {
    setFontSizeInput(String(settings.fontSize));
  }, [settings.fontSize]);

  // Focus textarea when opening or switching writing modes
  useEffect(() => {
    const el = textareaRef.current;
    if (!el) return;
    el.focus();
    const len = el.value.length;
    try {
      el.setSelectionRange(len, len);
    } catch {
      // ignore in non-browser test environments
    }
  }, [editingLayerId, isVertical]);

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

  const fontOptions = useMemo(
    () => getTextFontOptions(settings.fontFamily, systemFonts),
    [settings.fontFamily, systemFonts]
  );

  // Compute exact layout matching committed canvas output 1:1
  const layout = useMemo(() => {
    const sampleText = settings.text || ' ';
    return computeMangaTextLayout(sampleText, {
      fontSize: settings.fontSize,
      fontFamily: settings.fontFamily,
      writingMode: settings.writingMode || 'horizontal-tb',
      bold: settings.bold,
      italic: settings.italic,
      underline: settings.underline,
      align: settings.align,
      lineHeightRatio: settings.lineSpacing,
      letterSpacing: settings.letterSpacing,
      maxWidth: settings.maxWidth,
      anchorTopLeft: true,
    });
  }, [
    settings.text,
    settings.fontSize,
    settings.fontFamily,
    settings.writingMode,
    settings.bold,
    settings.italic,
    settings.underline,
    settings.align,
    settings.lineSpacing,
    settings.letterSpacing,
    settings.maxWidth,
  ]);

  const boxWidth = Math.max(
    settings.maxWidth ?? 0,
    Math.ceil(layout.width),
    Math.ceil(settings.fontSize * 3.5),
    72
  );
  const boxHeight = Math.max(Math.ceil(layout.height), Math.ceil(settings.fontSize * 1.25), 28);

  const canvasPad = useMemo(() => {
    const outlinePad = settings.outline ? (settings.outlineWidth || 3) * 3 : 0;
    return Math.ceil(Math.max(16, outlinePad + settings.fontSize * 0.45));
  }, [settings.outline, settings.outlineWidth, settings.fontSize]);

  // Render live pixel-exact canvas preview using the exact same renderer as committed text layers
  useEffect(() => {
    const canvas = previewCanvasRef.current;
    if (!canvas) return;
    const ctx = canvas.getContext('2d');
    if (!ctx) return;

    const cssW = boxWidth + canvasPad * 2;
    const cssH = boxHeight + canvasPad * 2;
    const dpr = typeof window !== 'undefined' ? window.devicePixelRatio || 1 : 1;
    const renderScale = Math.max(1, Math.min(3, dpr * Math.min(2, safeZoom)));
    const pixelW = Math.max(1, Math.round(cssW * renderScale));
    const pixelH = Math.max(1, Math.round(cssH * renderScale));

    if (canvas.width !== pixelW || canvas.height !== pixelH) {
      canvas.width = pixelW;
      canvas.height = pixelH;
    }

    ctx.save();
    ctx.setTransform(renderScale, 0, 0, renderScale, 0, 0);
    ctx.clearRect(0, 0, cssW, cssH);

    if (settings.text && settings.text.trim()) {
      renderMangaTextToCanvas(ctx, settings.text, canvasPad, canvasPad, {
        fontSize: settings.fontSize,
        fontFamily: settings.fontFamily,
        writingMode: settings.writingMode || 'horizontal-tb',
        bold: settings.bold,
        italic: settings.italic,
        underline: settings.underline,
        align: settings.align,
        color: settings.color,
        outline: settings.outline,
        outlineColor: settings.outlineColor,
        outlineWidth: settings.outlineWidth,
        lineHeightRatio: settings.lineSpacing,
        letterSpacing: settings.letterSpacing,
        opacity: settings.opacity,
        maxWidth: settings.maxWidth ?? boxWidth,
        anchorTopLeft: true,
      });
    }
    ctx.restore();
  }, [
    boxWidth,
    boxHeight,
    canvasPad,
    safeZoom,
    settings.text,
    settings.fontSize,
    settings.fontFamily,
    settings.writingMode,
    settings.bold,
    settings.italic,
    settings.underline,
    settings.align,
    settings.color,
    settings.outline,
    settings.outlineColor,
    settings.outlineWidth,
    settings.lineSpacing,
    settings.letterSpacing,
    settings.opacity,
    settings.maxWidth,
  ]);

  // Convert screen pointer delta to canvas delta accounting for zoom, rotation, flipX/Y
  const screenDeltaToCanvas = useCallback(
    (dxScreen: number, dyScreen: number) => {
      const rad = (-rotation * Math.PI) / 180;
      const cos = Math.cos(rad);
      const sin = Math.sin(rad);
      return {
        dx: ((dxScreen * cos - dyScreen * sin) * (flipX ? -1 : 1)) / safeZoom,
        dy: ((dxScreen * sin + dyScreen * cos) * (flipY ? -1 : 1)) / safeZoom,
      };
    },
    [rotation, flipX, flipY, safeZoom]
  );

  // Move drag state
  const dragModeRef = useRef<'none' | 'move' | 'resize-width' | 'scale-font'>('none');
  const dragStartRef = useRef({
    clientX: 0,
    clientY: 0,
    initX: x,
    initY: y,
    initWidth: boxWidth,
    initFontSize: settings.fontSize,
  });

  const startDrag = useCallback(
    (mode: 'move' | 'resize-width' | 'scale-font', e: React.PointerEvent) => {
      e.stopPropagation();
      e.preventDefault();
      try {
        (e.currentTarget as HTMLElement).setPointerCapture(e.pointerId);
      } catch {
        // ignore synthetic events
      }
      dragModeRef.current = mode;
      dragStartRef.current = {
        clientX: e.clientX,
        clientY: e.clientY,
        initX: x,
        initY: y,
        initWidth: settings.maxWidth ?? boxWidth,
        initFontSize: settings.fontSize,
      };
    },
    [x, y, settings.maxWidth, boxWidth, settings.fontSize]
  );

  const handleDragMove = useCallback(
    (e: React.PointerEvent) => {
      const mode = dragModeRef.current;
      if (mode === 'none') return;
      e.stopPropagation();
      const { dx, dy } = screenDeltaToCanvas(
        e.clientX - dragStartRef.current.clientX,
        e.clientY - dragStartRef.current.clientY
      );

      if (mode === 'move') {
        onMove(
          Math.round(dragStartRef.current.initX + dx),
          Math.round(dragStartRef.current.initY + dy)
        );
      } else if (mode === 'resize-width') {
        const nextW = Math.max(48, Math.round(dragStartRef.current.initWidth + dx));
        onUpdateSettings((prev) => ({ ...prev, maxWidth: nextW }));
      } else if (mode === 'scale-font') {
        const delta = Math.abs(dy) > Math.abs(dx) ? dy : dx;
        const scaleFactor = Math.max(0.25, 1 + delta / Math.max(60, dragStartRef.current.initFontSize * 2));
        const nextSize = Math.max(
          6,
          Math.min(400, Math.round(dragStartRef.current.initFontSize * scaleFactor))
        );
        onUpdateSettings((prev) => ({ ...prev, fontSize: nextSize }));
      }
    },
    [screenDeltaToCanvas, onMove, onUpdateSettings]
  );

  const handleDragUp = useCallback((e: React.PointerEvent) => {
    if (dragModeRef.current === 'none') return;
    e.stopPropagation();
    try {
      (e.currentTarget as HTMLElement).releasePointerCapture(e.pointerId);
    } catch {
      // ignore
    }
    dragModeRef.current = 'none';
  }, []);

  const stepFontSize = useCallback(
    (delta: number) => {
      onUpdateSettings((prev) => ({
        ...prev,
        fontSize: Math.max(6, Math.min(400, Math.round((prev.fontSize || 36) + delta))),
      }));
    },
    [onUpdateSettings]
  );

  const handleEditorKeyDown = useCallback(
    (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
      // Stop propagation so global canvas shortcuts never fire while typing
      e.stopPropagation();

      // Never intercept keys during Japanese/CJK IME conversion (Enter/Escape confirm or cancel candidates)
      if (isImeComposing(e)) {
        return;
      }

      if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) {
        e.preventDefault();
        onConfirm();
        return;
      }
      if (e.key === 'Escape') {
        e.preventDefault();
        onCancel();
        return;
      }

      // Rich formatting shortcuts
      if (e.ctrlKey || e.metaKey) {
        const k = e.key.toLowerCase();
        if (k === 'b') {
          e.preventDefault();
          onUpdateSettings((prev) => ({ ...prev, bold: !prev.bold }));
          return;
        }
        if (k === 'i') {
          e.preventDefault();
          onUpdateSettings((prev) => ({ ...prev, italic: !prev.italic }));
          return;
        }
        if (k === 'u') {
          e.preventDefault();
          onUpdateSettings((prev) => ({ ...prev, underline: !prev.underline }));
          return;
        }
        if (e.key === ']' || (e.shiftKey && e.key === '>')) {
          e.preventDefault();
          stepFontSize(e.shiftKey ? 4 : 2);
          return;
        }
        if (e.key === '[' || (e.shiftKey && e.key === '<')) {
          e.preventDefault();
          stepFontSize(e.shiftKey ? -4 : -2);
          return;
        }
        if (e.shiftKey && k === 'l') {
          e.preventDefault();
          onUpdateSettings((prev) => ({ ...prev, align: 'left' }));
          return;
        }
        if (e.shiftKey && k === 'e') {
          e.preventDefault();
          onUpdateSettings((prev) => ({ ...prev, align: 'center' }));
          return;
        }
        if (e.shiftKey && k === 'r') {
          e.preventDefault();
          onUpdateSettings((prev) => ({ ...prev, align: 'right' }));
          return;
        }
      }

      // Alt + Arrow key nudging
      if (e.altKey && !e.ctrlKey && !e.metaKey) {
        const step = e.shiftKey ? 10 : 1;
        if (e.key === 'ArrowLeft') {
          e.preventDefault();
          onMove(x - step, y);
        } else if (e.key === 'ArrowRight') {
          e.preventDefault();
          onMove(x + step, y);
        } else if (e.key === 'ArrowUp') {
          e.preventDefault();
          onMove(x, y - step);
        } else if (e.key === 'ArrowDown') {
          e.preventDefault();
          onMove(x, y + step);
        }
      }
    },
    [onConfirm, onCancel, onUpdateSettings, stepFontSize, onMove, x, y]
  );

  const commitFontSizeInput = useCallback(() => {
    const parsed = parseInt(fontSizeInput, 10);
    if (Number.isFinite(parsed)) {
      const clamped = Math.max(6, Math.min(400, parsed));
      onUpdateSettings((prev) => ({ ...prev, fontSize: clamped }));
      setFontSizeInput(String(clamped));
    } else {
      setFontSizeInput(String(settings.fontSize));
    }
  }, [fontSizeInput, onUpdateSettings, settings.fontSize]);

  const handleResetToStandard = useCallback(() => {
    onUpdateSettings((prev) => ({
      ...DEFAULT_TEXT_SETTINGS,
      text: prev.text,
      maxWidth: prev.maxWidth ?? null,
    }));
  }, [onUpdateSettings]);

  const borderPx = Math.max(1, 1.25 / safeZoom);
  const handleSize = Math.max(7, 9 / safeZoom);

  return (
    <div
      data-testid="text-editor-overlay"
      className="absolute z-40 pointer-events-auto select-none"
      style={{
        left: `${x}px`,
        top: `${y}px`,
      }}
      onPointerDown={(e) => e.stopPropagation()}
    >
      {/* Direct On-Canvas WYSIWYG Text Bounding Box */}
      <div
        className="relative"
        style={{
          width: `${boxWidth}px`,
          height: `${boxHeight}px`,
        }}
      >
        {/* Pixel-exact Canvas Renderer (1:1 parity with committed layer) */}
        <canvas
          ref={previewCanvasRef}
          data-testid="text-live-preview-canvas"
          className="pointer-events-none absolute"
          style={{
            left: `${-canvasPad}px`,
            top: `${-canvasPad}px`,
            width: `${boxWidth + canvasPad * 2}px`,
            height: `${boxHeight + canvasPad * 2}px`,
          }}
        />

        {/* Crisp Zoom-Compensated Dashed Bounding Frame */}
        <div
          className="pointer-events-none absolute inset-0 rounded-[2px]"
          style={{
            outline: `${borderPx}px dashed rgba(56, 189, 248, 0.85)`,
            outlineOffset: `${Math.max(2, 3 / safeZoom)}px`,
            boxShadow: `0 0 0 ${borderPx}px rgba(0, 0, 0, 0.35)`,
          }}
        />

        {/* Subtle Placeholder when Empty */}
        {!settings.text && (
          <div
            className="pointer-events-none absolute inset-0 overflow-hidden"
            style={{
              fontFamily: settings.fontFamily,
              fontSize: `${settings.fontSize}px`,
              fontWeight: settings.bold ? 700 : 400,
              fontStyle: settings.italic ? 'italic' : 'normal',
              lineHeight: `${layout.lineHeight}px`,
              letterSpacing: settings.letterSpacing ? `${settings.letterSpacing}px` : undefined,
              textAlign: settings.align,
              color: settings.color || '#ffffff',
              opacity: 0.42,
              whiteSpace: 'nowrap',
            }}
          >
            {t('Type text...')}
          </div>
        )}

        {/* Direct Transparent On-Canvas Input for Horizontal Mode (Alt+Drag moves box) */}
        {!isVertical && (
          <textarea
            ref={textareaRef}
            data-testid="text-editor-textarea"
            aria-label={t('Canvas text input')}
            value={settings.text}
            onChange={(e) => onUpdateSettings((prev) => ({ ...prev, text: e.target.value }))}
            onKeyDown={handleEditorKeyDown}
            onPointerDown={(e) => {
              e.stopPropagation();
              if (e.altKey) {
                startDrag('move', e);
              }
            }}
            onPointerMove={handleDragMove}
            onPointerUp={handleDragUp}
            spellCheck={false}
            className="absolute inset-0 w-full h-full bg-transparent outline-none border-0 p-0 m-0 resize-none overflow-hidden select-text selection:bg-sky-400/35"
            style={{
              fontFamily: settings.fontFamily,
              fontSize: `${settings.fontSize}px`,
              fontWeight: settings.bold ? 700 : 400,
              fontStyle: settings.italic ? 'italic' : 'normal',
              lineHeight: `${layout.lineHeight}px`,
              letterSpacing: settings.letterSpacing ? `${settings.letterSpacing}px` : undefined,
              textAlign: settings.align,
              color: 'transparent',
              caretColor: '#38bdf8',
              whiteSpace: settings.maxWidth ? 'pre-wrap' : 'pre',
              overflowWrap: 'break-word',
              cursor: 'text',
            }}
          />
        )}

        {/* Direct Drag Surface for Vertical Mode */}
        {isVertical && (
          <div
            onPointerDown={(e) => startDrag('move', e)}
            onPointerMove={handleDragMove}
            onPointerUp={handleDragUp}
            className="absolute inset-0 cursor-move"
            title={t('Drag to reposition vertical text')}
          />
        )}

        {/* Top-Left Move Grip Pill (always easy to grab & reposition text) */}
        <div
          data-testid="text-move-handle"
          onPointerDown={(e) => startDrag('move', e)}
          onPointerMove={handleDragMove}
          onPointerUp={handleDragUp}
          title={t('Drag to move text (or Alt+Drag / Alt+Arrow keys)')}
          className="absolute flex items-center justify-center rounded-full bg-sky-500 text-white shadow cursor-move hover:bg-sky-400 transition-colors"
          style={{
            left: `${-handleSize * 1.1}px`,
            top: `${-handleSize * 1.1}px`,
            width: `${handleSize * 2.1}px`,
            height: `${handleSize * 2.1}px`,
          }}
        >
          <Move style={{ width: `${handleSize * 1.2}px`, height: `${handleSize * 1.2}px` }} />
        </div>

        {/* Right-Edge Wrap Width Handle (horizontal mode) */}
        {!isVertical && (
          <div
            data-testid="text-width-handle"
            onPointerDown={(e) => startDrag('resize-width', e)}
            onPointerMove={handleDragMove}
            onPointerUp={handleDragUp}
            onDoubleClick={(e) => {
              e.stopPropagation();
              onUpdateSettings((prev) => ({ ...prev, maxWidth: null }));
            }}
            title={
              settings.maxWidth
                ? t('Wrap width: {width}px (drag to resize, double-click for auto width)', {
                    width: settings.maxWidth,
                  })
                : t('Drag to set word-wrap box width')
            }
            className="absolute top-1/2 -translate-y-1/2 rounded-full bg-white border border-sky-500 shadow cursor-ew-resize hover:bg-sky-100"
            style={{
              right: `${-handleSize * 0.75}px`,
              width: `${handleSize * 0.85}px`,
              height: `${Math.max(handleSize * 2.2, Math.min(boxHeight * 0.5, handleSize * 3.5))}px`,
            }}
          />
        )}

        {/* Bottom-Right Corner Font Scale Handle */}
        <div
          data-testid="text-scale-handle"
          onPointerDown={(e) => startDrag('scale-font', e)}
          onPointerMove={handleDragMove}
          onPointerUp={handleDragUp}
          title={t('Drag diagonally to scale font size')}
          className="absolute rounded-[2px] bg-white border border-sky-500 shadow cursor-nwse-resize hover:bg-sky-100"
          style={{
            right: `${-handleSize * 0.75}px`,
            bottom: `${-handleSize * 0.75}px`,
            width: `${handleSize * 1.25}px`,
            height: `${handleSize * 1.25}px`,
          }}
        />
      </div>

      {/* Compact Zoom-Compensated Floating Quick Bar */}
      <div
        className="mt-2"
        style={{
          transform: `scale(${invScaleX}, ${invScaleY})`,
          transformOrigin: 'top left',
        }}
      >
        <div className="w-max max-w-[560px] bg-ui-floating/95 backdrop-blur-md border border-ui-default rounded-ui-lg shadow-ui-popover text-ui-primary overflow-visible">
          {/* Primary Compact Toolbar Row */}
          <div className="px-2 py-1.5 flex items-center gap-1.5 flex-wrap">
            {/* Drag Handle */}
            <div
              onPointerDown={(e) => startDrag('move', e)}
              onPointerMove={handleDragMove}
              onPointerUp={handleDragUp}
              title={t('Drag to move text')}
              className="p-0.5 text-ui-muted hover:text-ui-primary cursor-move shrink-0"
            >
              <GripVertical className="w-3.5 h-3.5" />
            </div>

            {/* Font Family */}
            <select
              aria-label={t('Font Family')}
              value={settings.fontFamily}
              onFocus={handleLoadSystemFonts}
              onChange={(e) => onUpdateSettings((prev) => ({ ...prev, fontFamily: e.target.value }))}
              className="h-6 max-w-[140px] bg-ui-input text-ui-primary text-[11px] border border-ui-subtle rounded-ui-xs px-1.5 focus:border-ui-focus focus:outline-none cursor-pointer"
              style={{ fontFamily: settings.fontFamily }}
            >
              {fontOptions.map((f) => (
                <option
                  key={f.value}
                  value={f.value}
                  className="bg-ui-elevated text-ui-primary"
                  style={{ fontFamily: f.value }}
                >
                  {td(f.label)}
                </option>
              ))}
            </select>

            {/* Font Size Stepper + Input */}
            <div className="inline-flex items-center bg-ui-input border border-ui-subtle rounded-ui-xs h-6 overflow-hidden shrink-0">
              <button
                type="button"
                onClick={() => stepFontSize(-2)}
                title={t('Decrease font size (Ctrl+[)')}
                className="w-5 h-full flex items-center justify-center text-ui-muted hover:text-ui-primary hover:bg-ui-control-hover cursor-pointer"
              >
                <Minus className="w-2.5 h-2.5" />
              </button>
              <input
                type="text"
                inputMode="numeric"
                aria-label={t('Font Size')}
                value={fontSizeInput}
                onChange={(e) => setFontSizeInput(e.target.value.replace(/[^0-9]/g, ''))}
                onBlur={commitFontSizeInput}
                onKeyDown={(e) => {
                  e.stopPropagation();
                  if (isImeComposing(e)) return;
                  if (e.key === 'Enter') {
                    commitFontSizeInput();
                    textareaRef.current?.focus();
                  } else if (e.key === 'ArrowUp') {
                    e.preventDefault();
                    stepFontSize(e.shiftKey ? 10 : 1);
                  } else if (e.key === 'ArrowDown') {
                    e.preventDefault();
                    stepFontSize(e.shiftKey ? -10 : -1);
                  }
                }}
                className="w-9 h-full bg-transparent text-center text-[11px] font-ui-mono tabular-nums text-ui-primary focus:outline-none"
              />
              <button
                type="button"
                onClick={() => stepFontSize(2)}
                title={t('Increase font size (Ctrl+])')}
                className="w-5 h-full flex items-center justify-center text-ui-muted hover:text-ui-primary hover:bg-ui-control-hover cursor-pointer"
              >
                <Plus className="w-2.5 h-2.5" />
              </button>
            </div>

            {/* Text Color Swatch + Quick Popover */}
            <div className="relative shrink-0">
              <button
                type="button"
                data-testid="text-color-trigger"
                onClick={() => setShowColorPopover((v) => !v)}
                title={t('Text Color ({color})', { color: settings.color || '#ffffff' })}
                className="w-6 h-6 rounded-ui-xs border border-ui-default hover:border-ui-strong flex items-center justify-center bg-ui-input cursor-pointer"
              >
                <span
                  className="w-4 h-4 rounded-[2px] border border-black/30"
                  style={{ backgroundColor: settings.color || '#ffffff' }}
                />
              </button>

              {showColorPopover && (
                <div className="absolute left-0 top-7 z-50 p-2 bg-ui-floating border border-ui-default rounded-ui-md shadow-ui-popover flex flex-col gap-2 w-44">
                  <div className="flex items-center justify-between text-[10px] text-ui-muted">
                    <span>{t('Text Color')}</span>
                    <span className="font-ui-mono uppercase">{settings.color || '#ffffff'}</span>
                  </div>
                  <div className="flex items-center gap-1.5 flex-wrap">
                    {TEXT_QUICK_COLORS.map((swatch) => (
                      <button
                        key={swatch.hex}
                        type="button"
                        title={td(swatch.label)}
                        onClick={() => {
                          onUpdateSettings((prev) => ({ ...prev, color: swatch.hex }));
                          setShowColorPopover(false);
                        }}
                        className={`w-5 h-5 rounded-ui-xs border cursor-pointer ${
                          (settings.color || '#ffffff').toLowerCase() === swatch.hex
                            ? 'border-ui-accent ring-1 ring-ui-accent-border'
                            : 'border-ui-default hover:border-ui-strong'
                        }`}
                        style={{ backgroundColor: swatch.hex }}
                      />
                    ))}
                  </div>
                  <div className="flex items-center justify-between gap-1.5 pt-1 border-t border-ui-subtle">
                    <label className="inline-flex items-center gap-1.5 text-[10px] text-ui-secondary cursor-pointer">
                      <input
                        type="color"
                        value={settings.color || '#ffffff'}
                        onChange={(e) =>
                          onUpdateSettings((prev) => ({ ...prev, color: e.target.value }))
                        }
                        className="w-5 h-5 bg-transparent cursor-pointer border border-ui-default rounded-ui-xs"
                      />
                      <span>{t('Custom')}</span>
                    </label>
                    {primaryColor && (
                      <button
                        type="button"
                        onClick={() => {
                          onUpdateSettings((prev) => ({ ...prev, color: primaryColor }));
                          setShowColorPopover(false);
                        }}
                        title={t('Use current brush color ({color})', { color: primaryColor })}
                        className="inline-flex items-center gap-1 px-1.5 py-0.5 rounded-ui-xs bg-ui-control hover:bg-ui-control-hover border border-ui-subtle text-[10px] text-ui-primary cursor-pointer"
                      >
                        <Pipette className="w-2.5 h-2.5" />
                        <span>{t('Brush')}</span>
                      </button>
                    )}
                  </div>
                </div>
              )}
            </div>

            <span className="h-4 w-px bg-ui-subtle shrink-0" />

            {/* Bold / Italic / Underline */}
            <div className="inline-flex items-center gap-0.5 shrink-0">
              <button
                type="button"
                aria-pressed={settings.bold}
                onClick={() => onUpdateSettings((prev) => ({ ...prev, bold: !prev.bold }))}
                title={t('Bold (Ctrl+B)')}
                className={`w-6 h-6 rounded-ui-xs flex items-center justify-center border transition-colors cursor-pointer ${
                  settings.bold
                    ? 'bg-ui-accent-subtle text-ui-accent border-ui-accent-border'
                    : 'border-transparent text-ui-icon-muted hover:text-ui-primary hover:bg-ui-control-hover'
                }`}
              >
                <Bold className="w-3.5 h-3.5" />
              </button>
              <button
                type="button"
                aria-pressed={settings.italic}
                onClick={() => onUpdateSettings((prev) => ({ ...prev, italic: !prev.italic }))}
                title={t('Italic (Ctrl+I)')}
                className={`w-6 h-6 rounded-ui-xs flex items-center justify-center border transition-colors cursor-pointer ${
                  settings.italic
                    ? 'bg-ui-accent-subtle text-ui-accent border-ui-accent-border'
                    : 'border-transparent text-ui-icon-muted hover:text-ui-primary hover:bg-ui-control-hover'
                }`}
              >
                <Italic className="w-3.5 h-3.5" />
              </button>
              <button
                type="button"
                aria-pressed={Boolean(settings.underline)}
                onClick={() =>
                  onUpdateSettings((prev) => ({ ...prev, underline: !prev.underline }))
                }
                title={t('Underline (Ctrl+U)')}
                className={`w-6 h-6 rounded-ui-xs flex items-center justify-center border transition-colors cursor-pointer ${
                  settings.underline
                    ? 'bg-ui-accent-subtle text-ui-accent border-ui-accent-border'
                    : 'border-transparent text-ui-icon-muted hover:text-ui-primary hover:bg-ui-control-hover'
                }`}
              >
                <Underline className="w-3.5 h-3.5" />
              </button>
            </div>

            {/* Alignment */}
            <div className="inline-flex items-center gap-0.5 bg-ui-input p-0.5 rounded-ui-xs border border-ui-subtle shrink-0">
              {(
                [
                  { id: 'left', icon: <AlignLeft className="w-3 h-3" />, label: 'Align Left (Ctrl+Shift+L)' },
                  { id: 'center', icon: <AlignCenter className="w-3 h-3" />, label: 'Align Center (Ctrl+Shift+E)' },
                  { id: 'right', icon: <AlignRight className="w-3 h-3" />, label: 'Align Right (Ctrl+Shift+R)' },
                ] as const
              ).map((a) => (
                <button
                  key={a.id}
                  type="button"
                  title={t(a.label)}
                  onClick={() => onUpdateSettings((prev) => ({ ...prev, align: a.id }))}
                  className={`w-5 h-5 rounded-[2px] flex items-center justify-center cursor-pointer transition-colors ${
                    settings.align === a.id
                      ? 'bg-ui-control-active text-ui-accent'
                      : 'text-ui-icon-muted hover:text-ui-primary'
                  }`}
                >
                  {a.icon}
                </button>
              ))}
            </div>

            {/* Horizontal / Vertical Toggle */}
            <div className="inline-flex items-center gap-0.5 bg-ui-input p-0.5 rounded-ui-xs border border-ui-subtle shrink-0">
              <button
                type="button"
                onClick={() => onUpdateSettings((prev) => ({ ...prev, writingMode: 'horizontal-tb' }))}
                title={t('Horizontal Text')}
                className={`px-1.5 h-5 rounded-[2px] text-[10px] font-medium cursor-pointer transition-colors ${
                  !isVertical
                    ? 'bg-ui-control-active text-ui-primary'
                    : 'text-ui-muted hover:text-ui-primary'
                }`}
              >
                {tc('writingMode', 'H')}
              </button>
              <button
                type="button"
                onClick={() => onUpdateSettings((prev) => ({ ...prev, writingMode: 'vertical-rl' }))}
                title={t('Vertical Text (Tate-gaki)')}
                className={`px-1.5 h-5 rounded-[2px] text-[10px] font-medium cursor-pointer transition-colors ${
                  isVertical
                    ? 'bg-ui-accent-subtle text-ui-accent'
                    : 'text-ui-muted hover:text-ui-primary'
                }`}
              >
                {tc('writingMode', 'V')}
              </button>
            </div>

            {/* Expand Typography / Outline Settings */}
            <button
              type="button"
              data-testid="text-more-style-btn"
              aria-expanded={showMoreStyle}
              onClick={() => setShowMoreStyle((v) => !v)}
              title={t('Spacing, opacity, and outline options')}
              className={`h-6 px-1.5 rounded-ui-xs border text-[10.5px] inline-flex items-center gap-1 cursor-pointer transition-colors shrink-0 ${
                showMoreStyle || settings.outline
                  ? 'bg-ui-control-active border-ui-accent-border text-ui-primary'
                  : 'bg-ui-input border-ui-subtle text-ui-secondary hover:text-ui-primary hover:bg-ui-control-hover'
              }`}
            >
              <SlidersHorizontal className="w-3 h-3" />
              <span>{t('Style')}</span>
            </button>

            <span className="h-4 w-px bg-ui-subtle shrink-0" />

            {/* Delete / Cancel / Apply */}
            {editingLayerId && onDelete && (
              <button
                type="button"
                data-testid="text-delete-btn"
                onClick={onDelete}
                title={t('Delete text layer')}
                className="w-6 h-6 rounded-ui-xs flex items-center justify-center text-ui-muted hover:text-ui-danger hover:bg-ui-danger/15 transition-colors cursor-pointer shrink-0"
              >
                <Trash2 className="w-3.5 h-3.5" />
              </button>
            )}
            <button
              type="button"
              data-testid="text-cancel-btn"
              onClick={onCancel}
              title={t('Cancel (Esc)')}
              className="w-6 h-6 rounded-ui-xs flex items-center justify-center bg-ui-control hover:bg-ui-control-hover border border-ui-subtle text-ui-secondary hover:text-ui-primary transition-colors cursor-pointer shrink-0"
            >
              <X className="w-3.5 h-3.5" />
            </button>
            <button
              type="button"
              data-testid="text-confirm-btn"
              onClick={onConfirm}
              title={t('Apply text (Ctrl+Enter or click outside)')}
              className="h-6 px-2 rounded-ui-xs inline-flex items-center gap-1 bg-ui-accent text-ui-accent-contrast hover:opacity-90 text-[11px] font-medium transition-opacity cursor-pointer shrink-0"
            >
              <Check className="w-3.5 h-3.5" />
              <span>{t('Done')}</span>
            </button>
          </div>

          {/* Dedicated Text Input Box for Vertical Mode */}
          {isVertical && (
            <div className="px-2.5 pb-2 pt-1 border-t border-ui-subtle">
              <textarea
                ref={textareaRef}
                data-testid="text-editor-textarea"
                aria-label={t('Vertical text input')}
                value={settings.text}
                onChange={(e) => onUpdateSettings((prev) => ({ ...prev, text: e.target.value }))}
                onKeyDown={handleEditorKeyDown}
                placeholder={t('Type vertical text (Enter starts next column)...')}
                rows={2}
                className="w-full bg-ui-input text-ui-primary placeholder:text-ui-muted text-xs border border-ui-subtle rounded-ui-sm p-1.5 focus:border-ui-focus focus:outline-none resize-none"
              />
            </div>
          )}

          {/* Expandable Advanced Typography & Optional Outline Drawer */}
          {showMoreStyle && (
            <div className="px-3 py-2.5 border-t border-ui-subtle bg-ui-header/70 space-y-2 text-[11px]">
              <div className="grid grid-cols-2 gap-x-4 gap-y-2">
                <label className="flex items-center gap-2">
                  <span className="text-ui-muted min-w-16 shrink-0 whitespace-nowrap tabular-nums">
                    {t('Line {value}', { value: (settings.lineSpacing ?? 1.25).toFixed(2) })}
                  </span>
                  <input
                    type="range"
                    min={0.8}
                    max={2.5}
                    step={0.05}
                    value={settings.lineSpacing ?? 1.25}
                    onChange={(e) =>
                      onUpdateSettings((prev) => ({ ...prev, lineSpacing: Number(e.target.value) }))
                    }
                    className="flex-1 min-w-0"
                  />
                </label>

                <label className="flex items-center gap-2">
                  <span className="text-ui-muted min-w-16 shrink-0 whitespace-nowrap tabular-nums">
                    {t('Track {value}px', { value: (settings.letterSpacing ?? 0).toFixed(0) })}
                  </span>
                  <input
                    type="range"
                    min={-6}
                    max={30}
                    step={0.5}
                    value={settings.letterSpacing ?? 0}
                    onChange={(e) =>
                      onUpdateSettings((prev) => ({
                        ...prev,
                        letterSpacing: Number(e.target.value),
                      }))
                    }
                    className="flex-1 min-w-0"
                  />
                </label>

                <label className="flex items-center gap-2">
                  <span className="text-ui-muted min-w-16 shrink-0 whitespace-nowrap tabular-nums">
                    {t('Opacity {value}%', { value: Math.round((settings.opacity ?? 1) * 100) })}
                  </span>
                  <input
                    type="range"
                    min={0.1}
                    max={1}
                    step={0.05}
                    value={settings.opacity ?? 1}
                    onChange={(e) =>
                      onUpdateSettings((prev) => ({ ...prev, opacity: Number(e.target.value) }))
                    }
                    className="flex-1 min-w-0"
                  />
                </label>

                <div className="flex items-center justify-between gap-2">
                  <label className="inline-flex items-center gap-1.5 cursor-pointer text-ui-primary">
                    <input
                      type="checkbox"
                      checked={Boolean(settings.outline)}
                      onChange={(e) =>
                        onUpdateSettings((prev) => ({ ...prev, outline: e.target.checked }))
                      }
                      className="cursor-pointer"
                    />
                    <span>{t('Outline')}</span>
                  </label>
                  <button
                    type="button"
                    onClick={handleResetToStandard}
                    title={t('Reset to plain white text without outline')}
                    className="inline-flex items-center gap-1 px-1.5 py-0.5 rounded-ui-xs bg-ui-control hover:bg-ui-control-hover border border-ui-subtle text-[10px] text-ui-secondary hover:text-ui-primary cursor-pointer"
                  >
                    <RotateCcw className="w-2.5 h-2.5" />
                    <span>{t('Plain White')}</span>
                  </button>
                </div>
              </div>

              {settings.outline && (
                <div className="flex items-center gap-3 pt-1.5 border-t border-ui-subtle">
                  <label className="flex items-center gap-2 flex-1">
                    <span className="text-ui-muted tabular-nums shrink-0">
                      {tc('outline', 'Width {value}px', { value: settings.outlineWidth })}
                    </span>
                    <input
                      type="range"
                      min={1}
                      max={16}
                      value={settings.outlineWidth}
                      onChange={(e) =>
                        onUpdateSettings((prev) => ({
                          ...prev,
                          outlineWidth: Number(e.target.value),
                        }))
                      }
                      className="flex-1 min-w-0"
                    />
                  </label>

                  <div className="flex items-center gap-1 shrink-0">
                    <span className="text-ui-muted">{t('Color:')}</span>
                    <button
                      type="button"
                      onClick={() =>
                        onUpdateSettings((prev) => ({ ...prev, outlineColor: '#000000' }))
                      }
                      className={`w-4 h-4 rounded-ui-xs border cursor-pointer ${
                        settings.outlineColor === '#000000'
                          ? 'border-ui-accent ring-1 ring-ui-accent-border'
                          : 'border-ui-default'
                      }`}
                      style={{ backgroundColor: '#000000' }}
                      title={t('Black outline')}
                    />
                    <button
                      type="button"
                      onClick={() =>
                        onUpdateSettings((prev) => ({ ...prev, outlineColor: '#ffffff' }))
                      }
                      className={`w-4 h-4 rounded-ui-xs border cursor-pointer ${
                        settings.outlineColor === '#ffffff'
                          ? 'border-ui-accent ring-1 ring-ui-accent-border'
                          : 'border-ui-default'
                      }`}
                      style={{ backgroundColor: '#ffffff' }}
                      title={t('White outline')}
                    />
                    <input
                      type="color"
                      aria-label={t('Outline Color')}
                      value={settings.outlineColor || '#000000'}
                      onChange={(e) =>
                        onUpdateSettings((prev) => ({ ...prev, outlineColor: e.target.value }))
                      }
                      className="w-5 h-4 bg-transparent cursor-pointer border border-ui-default rounded-ui-xs"
                    />
                  </div>
                </div>
              )}

              <div className="flex items-center justify-between text-[10px] text-ui-muted pt-1 border-t border-ui-subtle">
                <span>{t('Click outside or Ctrl+Enter to apply')}</span>
                <span>{t('Alt+Arrows to nudge • Drag edge to wrap')}</span>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
};