Skip to content

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

36.7 KB
Raw Blame
import React, { useState, useId, useMemo, useEffect, useCallback, useRef } from 'react';
import {
  X,
  Lock,
  Unlock,
  ArrowLeftRight,
  Printer,
  Maximize2,
  Check,
  Crop,
  RotateCcw,
  GripHorizontal,
  Grid3X3,
  PanelRightClose,
  SquareDashed,
  ArrowUpLeft,
  ArrowUp,
  ArrowUpRight,
  ArrowLeft,
  Circle,
  ArrowRight,
  ArrowDownLeft,
  ArrowDown,
  ArrowDownRight,
} from 'lucide-react';
import { CanvasDimensions } from '../types/editor';
import { AnchorPosition, ResizeCanvasOptions } from '../types/settings';
import { uiStoreActions, useUiStore } from '../stores';
import {
  CanvasResizeDraft,
  CropGridMode,
  MAX_CANVAS_DIM,
  MIN_CANVAS_DIM,
  RATIO_PRESETS,
  applyAnchorToDraft,
  applyCropXToDraft,
  applyCropYToDraft,
  applyFitBoundsToDraft,
  applyHeightToDraft,
  applyLockRatioToggleToDraft,
  applyRatioPresetToDraft,
  applyResetCropToDraft,
  applyScaleContentToggleToDraft,
  applySwapDimensionsToDraft,
  applyWidthToDraft,
  createInitialCanvasResizeDraft,
  cycleCropGridMode,
  draftToResizeCanvasOptions,
  isCropModified,
  nudgeCropDraft,
} from '../utils/canvasResizeCrop';
import { DPI_PRESETS } from './NewCanvasModal';
import { isImeComposing, useI18n } from '../i18n';

function gcd(a: number, b: number): number {
  a = Math.round(Math.abs(a));
  b = Math.round(Math.abs(b));
  return b ? gcd(b, a % b) : a;
}

const ANCHOR_GRID: { id: AnchorPosition; label: string; icon: React.ReactNode }[] = [
  { id: 'top-left', label: 'Top Left', icon: <ArrowUpLeft className="w-3.5 h-3.5" /> },
  { id: 'top', label: 'Top Center', icon: <ArrowUp className="w-3.5 h-3.5" /> },
  { id: 'top-right', label: 'Top Right', icon: <ArrowUpRight className="w-3.5 h-3.5" /> },
  { id: 'left', label: 'Middle Left', icon: <ArrowLeft className="w-3.5 h-3.5" /> },
  { id: 'center', label: 'Center', icon: <Circle className="w-2.5 h-2.5 fill-current" /> },
  { id: 'right', label: 'Middle Right', icon: <ArrowRight className="w-3.5 h-3.5" /> },
  { id: 'bottom-left', label: 'Bottom Left', icon: <ArrowDownLeft className="w-3.5 h-3.5" /> },
  { id: 'bottom', label: 'Bottom Center', icon: <ArrowDown className="w-3.5 h-3.5" /> },
  { id: 'bottom-right', label: 'Bottom Right', icon: <ArrowDownRight className="w-3.5 h-3.5" /> },
];

const ANCHOR_LABELS: Record<AnchorPosition, string> = {
  'top-left': 'Top Left',
  top: 'Top Center',
  'top-right': 'Top Right',
  left: 'Middle Left',
  center: 'Center',
  right: 'Middle Right',
  'bottom-left': 'Bottom Left',
  bottom: 'Bottom Center',
  'bottom-right': 'Bottom Right',
};

function formatGridMode(mode: CropGridMode): string {
  if (mode === 'thirds') return 'Thirds';
  if (mode === 'golden') return 'Golden';
  return 'Off';
}

function areResizeDraftsEqual(a: CanvasResizeDraft | undefined, b: CanvasResizeDraft | undefined): boolean {
  if (!a || !b) return a === b;
  return (
    a.originWidth === b.originWidth &&
    a.originHeight === b.originHeight &&
    a.cropX === b.cropX &&
    a.cropY === b.cropY &&
    a.width === b.width &&
    a.height === b.height &&
    a.dpi === b.dpi &&
    a.scaleContent === b.scaleContent &&
    a.anchor === b.anchor &&
    a.lockRatio === b.lockRatio &&
    a.ratioX === b.ratioX &&
    a.ratioY === b.ratioY &&
    a.gridMode === b.gridMode
  );
}

interface NumericDraftInputProps {
  id: string;
  value: number;
  min: number;
  max: number;
  onCommit: (val: number) => void;
  className?: string;
}

const NumericDraftInput: React.FC<NumericDraftInputProps> = ({
  id,
  value,
  min,
  max,
  onCommit,
  className,
}) => {
  const [editingText, setEditingText] = useState<string | null>(null);
  const isFocusedRef = useRef(false);

  const displayed = editingText !== null ? editingText : String(value);

  return (
    <input
      id={id}
      type="number"
      min={min}
      max={max}
      value={displayed}
      onFocus={() => {
        isFocusedRef.current = true;
        setEditingText(String(value));
      }}
      onChange={(e) => {
        const raw = e.target.value;
        if (isFocusedRef.current) {
          setEditingText(raw);
        }
        const trimmed = raw.trim();
        if (trimmed === '' || trimmed === '-') return;
        const parsed = Number(trimmed);
        if (Number.isFinite(parsed)) {
          // For positive-only dimensions, wait for blur if typed value is < min (e.g. typing "800" starting with "0")
          if (min >= 1 && parsed < min) return;
          onCommit(parsed);
        }
      }}
      onBlur={() => {
        isFocusedRef.current = false;
        if (editingText !== null) {
          const parsed = Number(editingText.trim());
          if (editingText.trim() !== '' && Number.isFinite(parsed)) {
            onCommit(parsed);
          }
          setEditingText(null);
        }
      }}
      className={className}
    />
  );
};

interface ResizeCanvasModalProps {
  isOpen: boolean;
  onClose: () => void;
  currentDimensions: CanvasDimensions;
  onResize: (options: ResizeCanvasOptions) => void;
  selectionBounds?: { x: number; y: number; width: number; height: number } | null;
}

export const ResizeCanvasModal: React.FC<ResizeCanvasModalProps> = ({
  isOpen,
  onClose,
  currentDimensions,
  onResize,
  selectionBounds = null,
}) => {
  const { t, tc, td } = useI18n();
  const widthInputId = useId();
  const heightInputId = useId();
  const cropXInputId = useId();
  const cropYInputId = useId();
  const dpiInputId = useId();

  const storeDraft = useUiStore((s) => s.canvasResizeDraft);
  const isInspectorCollapsed = useUiStore((s) => s.isResizeInspectorCollapsed);

  const userToggledLockRef = useRef(false);
  const [pos, setPos] = useState<{ x: number; y: number }>({ x: 0, y: 0 });
  const isDraggingWindowRef = useRef(false);
  const dragStartRef = useRef({ startX: 0, startY: 0, initX: 0, initY: 0 });
  const draftHistoryRef = useRef<CanvasResizeDraft[]>([]);
  const draftHistoryIndexRef = useRef<number>(-1);
  const isApplyingDraftHistoryRef = useRef<boolean>(false);
  const isPointerDownRef = useRef<boolean>(false);
  const pendingPointerDraftPushRef = useRef<boolean>(false);

  const pushDraftHistorySnapshot = useCallback((snapshot: CanvasResizeDraft) => {
    const stack = draftHistoryRef.current;
    const idx = draftHistoryIndexRef.current;
    if (idx >= 0 && areResizeDraftsEqual(stack[idx], snapshot)) return;
    const truncated = idx >= 0 ? stack.slice(0, idx + 1) : [];
    truncated.push({ ...snapshot });
    if (truncated.length > 100) {
      truncated.shift();
    }
    draftHistoryRef.current = truncated;
    draftHistoryIndexRef.current = truncated.length - 1;
  }, []);

  // Ensure draft and live crop draft undo stack are initialized whenever opened
  useEffect(() => {
    if (!isOpen) {
      draftHistoryRef.current = [];
      draftHistoryIndexRef.current = -1;
      isPointerDownRef.current = false;
      pendingPointerDraftPushRef.current = false;
      isApplyingDraftHistoryRef.current = false;
      return;
    }
    userToggledLockRef.current = false;
    setPos({ x: 0, y: 0 });
    const existing = useUiStore.getState().canvasResizeDraft;
    const initialDraft =
      existing &&
      existing.originWidth === currentDimensions.width &&
      existing.originHeight === currentDimensions.height
        ? existing
        : createInitialCanvasResizeDraft(currentDimensions);
    if (initialDraft !== existing) {
      uiStoreActions.updateCanvasResizeDraft(initialDraft);
    }
    draftHistoryRef.current = [{ ...initialDraft }];
    draftHistoryIndexRef.current = 0;
  }, [isOpen, currentDimensions]);

  // Coalesce continuous pointer drags on the crop overlay into a single draft undo step on pointerup
  useEffect(() => {
    if (!isOpen) return;
    const onPointerDown = () => {
      isPointerDownRef.current = true;
    };
    const onPointerEnd = () => {
      isPointerDownRef.current = false;
      if (pendingPointerDraftPushRef.current) {
        pendingPointerDraftPushRef.current = false;
        const latest = useUiStore.getState().canvasResizeDraft;
        if (latest) {
          pushDraftHistorySnapshot(latest);
        }
      }
    };
    window.addEventListener('pointerdown', onPointerDown, true);
    window.addEventListener('pointerup', onPointerEnd, true);
    window.addEventListener('pointercancel', onPointerEnd, true);
    return () => {
      window.removeEventListener('pointerdown', onPointerDown, true);
      window.removeEventListener('pointerup', onPointerEnd, true);
      window.removeEventListener('pointercancel', onPointerEnd, true);
    };
  }, [isOpen, pushDraftHistorySnapshot]);

  // Record discrete draft changes (inputs, anchor buttons, presets, arrow nudges) into crop draft history
  useEffect(() => {
    if (!isOpen || !storeDraft) return;
    if (isApplyingDraftHistoryRef.current) {
      isApplyingDraftHistoryRef.current = false;
      return;
    }
    if (isPointerDownRef.current) {
      pendingPointerDraftPushRef.current = true;
      return;
    }
    pushDraftHistorySnapshot(storeDraft);
  }, [isOpen, storeDraft, pushDraftHistorySnapshot]);

  const handleUndoDraft = useCallback(() => {
    if (draftHistoryIndexRef.current <= 0) return;
    draftHistoryIndexRef.current -= 1;
    const target = draftHistoryRef.current[draftHistoryIndexRef.current];
    if (!target) return;
    isApplyingDraftHistoryRef.current = true;
    uiStoreActions.updateCanvasResizeDraft({ ...target });
  }, []);

  const handleRedoDraft = useCallback(() => {
    if (draftHistoryIndexRef.current >= draftHistoryRef.current.length - 1) return;
    draftHistoryIndexRef.current += 1;
    const target = draftHistoryRef.current[draftHistoryIndexRef.current];
    if (!target) return;
    isApplyingDraftHistoryRef.current = true;
    uiStoreActions.updateCanvasResizeDraft({ ...target });
  }, []);

  const draft: CanvasResizeDraft = useMemo(
    () => storeDraft ?? createInitialCanvasResizeDraft(currentDimensions),
    [storeDraft, currentDimensions]
  );

  const updateDraft = useCallback(
    (updater: (prev: CanvasResizeDraft) => CanvasResizeDraft) => {
      const current =
        useUiStore.getState().canvasResizeDraft ??
        createInitialCanvasResizeDraft(currentDimensions);
      uiStoreActions.updateCanvasResizeDraft(updater(current));
    },
    [currentDimensions]
  );

  const handleApplyResize = useCallback(() => {
    const latest =
      useUiStore.getState().canvasResizeDraft ??
      createInitialCanvasResizeDraft(currentDimensions);
    onResize(draftToResizeCanvasOptions(latest));
    onClose();
  }, [currentDimensions, onResize, onClose]);

  useEffect(() => {
    if (!isOpen) return;
    const handleKeyDown = (e: KeyboardEvent) => {
      if (isImeComposing(e)) return;
      const target = e.target as HTMLElement | null;
      const tag = target?.tagName;
      const isTextLike =
        tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT' || Boolean(target?.isContentEditable);

      if (e.key === 'Escape') {
        e.preventDefault();
        e.stopPropagation();
        onClose();
        return;
      }

      if (!isTextLike && (e.ctrlKey || e.metaKey) && !e.altKey) {
        const lowerKey = e.key.toLowerCase();
        if (lowerKey === 'z' && !e.shiftKey) {
          e.preventDefault();
          e.stopPropagation();
          handleUndoDraft();
          return;
        }
        if ((lowerKey === 'z' && e.shiftKey) || (lowerKey === 'y' && !e.shiftKey)) {
          e.preventDefault();
          e.stopPropagation();
          handleRedoDraft();
          return;
        }
      }

      if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) {
        e.preventDefault();
        e.stopPropagation();
        if (target && tag === 'INPUT') {
          target.blur();
        }
        handleApplyResize();
        return;
      }

      if (e.key === 'Enter' && tag !== 'BUTTON' && tag !== 'SELECT' && tag !== 'TEXTAREA') {
        e.preventDefault();
        e.stopPropagation();
        if (target && tag === 'INPUT') {
          target.blur();
        }
        handleApplyResize();
        return;
      }

      if (!isTextLike && !e.ctrlKey && !e.metaKey && !e.altKey) {
        const step = e.shiftKey ? 10 : 1;
        if (e.key === 'ArrowLeft') {
          e.preventDefault();
          e.stopPropagation();
          updateDraft((prev) => nudgeCropDraft(prev, -step, 0));
        } else if (e.key === 'ArrowRight') {
          e.preventDefault();
          e.stopPropagation();
          updateDraft((prev) => nudgeCropDraft(prev, step, 0));
        } else if (e.key === 'ArrowUp') {
          e.preventDefault();
          e.stopPropagation();
          updateDraft((prev) => nudgeCropDraft(prev, 0, -step));
        } else if (e.key === 'ArrowDown') {
          e.preventDefault();
          e.stopPropagation();
          updateDraft((prev) => nudgeCropDraft(prev, 0, step));
        }
      }
    };
    window.addEventListener('keydown', handleKeyDown, true);
    return () => window.removeEventListener('keydown', handleKeyDown, true);
  }, [isOpen, onClose, handleApplyResize, handleUndoDraft, handleRedoDraft, updateDraft]);

  // Floating window drag handlers
  const handleWindowDragStart = (e: React.PointerEvent<HTMLDivElement>) => {
    if (e.button !== 0) return;
    if ((e.target as HTMLElement).closest('button')) return;
    isDraggingWindowRef.current = true;
    dragStartRef.current = {
      startX: e.clientX,
      startY: e.clientY,
      initX: pos.x,
      initY: pos.y,
    };
    try {
      e.currentTarget.setPointerCapture(e.pointerId);
    } catch {
      // Ignore synthetic capture error
    }
  };

  const handleWindowDragMove = (e: React.PointerEvent<HTMLDivElement>) => {
    if (!isDraggingWindowRef.current) return;
    const dx = e.clientX - dragStartRef.current.startX;
    const dy = e.clientY - dragStartRef.current.startY;
    setPos({
      x: dragStartRef.current.initX + dx,
      y: dragStartRef.current.initY + dy,
    });
  };

  const handleWindowDragEnd = (e: React.PointerEvent<HTMLDivElement>) => {
    if (!isDraggingWindowRef.current) return;
    isDraggingWindowRef.current = false;
    try {
      e.currentTarget.releasePointerCapture(e.pointerId);
    } catch {
      // Ignore
    }
  };

  const { width, height, dpi, lockRatio, scaleContent, anchor, cropX, cropY, gridMode } = draft;

  const simplifiedRatio = useMemo(() => {
    if (width <= 0 || height <= 0) return '1:1';
    const divisor = gcd(width, height);
    const simpleX = width / divisor;
    const simpleY = height / divisor;
    if (simpleX < 50 && simpleY < 50) {
      return `${simpleX}:${simpleY}`;
    }
    const dec = (width / height).toFixed(2);
    return `${dec}:1`;
  }, [width, height]);

  const percentW = useMemo(
    () => Math.round((width / (currentDimensions.width || 1)) * 100),
    [width, currentDimensions.width]
  );

  const percentH = useMemo(
    () => Math.round((height / (currentDimensions.height || 1)) * 100),
    [height, currentDimensions.height]
  );

  const megapixels = useMemo(() => ((width * height) / 1000000).toFixed(2), [width, height]);

  const printDimensionsCm = useMemo(() => {
    const safeDpi = Math.max(1, dpi);
    return {
      w: ((width / safeDpi) * 2.54).toFixed(1),
      h: ((height / safeDpi) * 2.54).toFixed(1),
    };
  }, [width, height, dpi]);

  const modified = isCropModified(draft);

  const handleToggleLockRatio = () => {
    userToggledLockRef.current = true;
    updateDraft((prev) => applyLockRatioToggleToDraft(prev, !prev.lockRatio));
  };

  const handleSetScaleContent = (nextScale: boolean) => {
    const shouldAutoLock = nextScale && !userToggledLockRef.current;
    updateDraft((prev) => applyScaleContentToggleToDraft(prev, nextScale, shouldAutoLock));
  };

  if (!isOpen || isInspectorCollapsed) return null;

  const isCropping = !scaleContent;
  const applyButtonLabel = isCropping && modified ? t('Apply Crop & Resize') : t('Resize Canvas');

  return (
    <div
      className="fixed inset-0 z-[49] pointer-events-none flex items-start justify-end p-3 sm:p-4 pt-12 sm:pt-14 select-none"
    >
      <div
        role="dialog"
        aria-modal="false"
        aria-labelledby="resize-canvas-modal-title"
        data-allow-canvas-nav="true"
        onPointerDown={(e) => e.stopPropagation()}
        style={{
          transform: `translate3d(${pos.x}px, ${pos.y}px, 0)`,
        }}
        className="pointer-events-auto bg-ui-panel/98 backdrop-blur-sm border border-ui-default rounded-ui-lg shadow-ui-popover w-[360px] max-w-[92vw] flex flex-col overflow-hidden text-xs text-ui-primary"
      >
        {/* Draggable Header */}
        <div
          onPointerDown={handleWindowDragStart}
          onPointerMove={handleWindowDragMove}
          onPointerUp={handleWindowDragEnd}
          onPointerCancel={handleWindowDragEnd}
          onDoubleClick={() => setPos({ x: 0, y: 0 })}
          className="h-9 px-3 bg-ui-header border-b border-ui-subtle flex items-center justify-between shrink-0 cursor-move"
          title={t('Drag to move panel · Double-click to reset position')}
        >
          <div className="flex items-center gap-2 min-w-0">
            {isCropping ? (
              <Crop className="w-3.5 h-3.5 text-ui-accent shrink-0" />
            ) : (
              <Maximize2 className="w-3.5 h-3.5 text-ui-accent shrink-0" />
            )}
            <h2
              id="resize-canvas-modal-title"
              className="text-xs font-medium text-ui-primary tracking-wide truncate"
            >
              {t('Resize Canvas')}
            </h2>
            <GripHorizontal className="w-3.5 h-3.5 text-ui-disabled shrink-0" />
          </div>

          <div className="flex items-center gap-0.5 shrink-0">
            <button
              type="button"
              onClick={() => uiStoreActions.setResizeInspectorCollapsed(true)}
              aria-label={t('Collapse panel')}
              title={t('Hide panel while cropping on canvas')}
              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"
            >
              <PanelRightClose className="w-3.5 h-3.5" />
            </button>
            <button
              type="button"
              onClick={onClose}
              aria-label={t('Close')}
              title={t('Cancel (Esc)')}
              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"
            >
              <X className="w-3.5 h-3.5" />
            </button>
          </div>
        </div>

        {/* Body */}
        <div className="p-3 space-y-2.5 max-h-[calc(100vh-150px)] overflow-y-auto">
          {/* Mode Toggle */}
          <div className="grid grid-cols-2 gap-1.5">
            <button
              type="button"
              onClick={() => handleSetScaleContent(false)}
              className={`p-2 rounded-ui-md border text-left transition-colors cursor-pointer ${
                isCropping
                  ? 'bg-ui-accent-subtle border-ui-accent-border text-ui-primary'
                  : 'bg-ui-header border-ui-subtle text-ui-muted hover:bg-ui-control-hover hover:text-ui-primary'
              }`}
            >
              <div className="flex items-center gap-1.5 font-medium text-[11px] text-ui-primary mb-0.5">
                <Crop className="w-3 h-3 text-ui-accent shrink-0" />
                <span>{t('Canvas Bounds')}</span>
              </div>
              <p className="text-[10px] text-ui-muted leading-tight">
                {t('Crop or expand directly on canvas without distorting pixels.')}
              </p>
            </button>

            <button
              type="button"
              onClick={() => handleSetScaleContent(true)}
              className={`p-2 rounded-ui-md border text-left transition-colors cursor-pointer ${
                scaleContent
                  ? 'bg-ui-accent-subtle border-ui-accent-border text-ui-primary'
                  : 'bg-ui-header border-ui-subtle text-ui-muted hover:bg-ui-control-hover hover:text-ui-primary'
              }`}
            >
              <div className="flex items-center gap-1.5 font-medium text-[11px] text-ui-primary mb-0.5">
                <Maximize2 className="w-3 h-3 text-ui-accent shrink-0" />
                <span>{t('Scale Content')}</span>
              </div>
              <p className="text-[10px] text-ui-muted leading-tight">
                {t('Resamples and scales all artwork to new dimensions.')}
              </p>
            </button>
          </div>

          {/* Current Dimensions Status Bar */}
          <div className="bg-ui-header border border-ui-subtle rounded-ui-md px-3 py-1.5 flex items-center justify-between">
            <span className="text-ui-muted text-[11px]">{t('Current')}</span>
            <div className="flex items-center gap-1.5 font-ui-mono tabular-nums text-[11px]">
              <span className="text-ui-primary font-medium">
                {currentDimensions.width} × {currentDimensions.height} px
              </span>
              <span className="text-ui-disabled">|</span>
              <span className="text-ui-accent">{currentDimensions.dpi || 300} DPI</span>
            </div>
          </div>

          {/* New Dimensions & Aspect Ratio */}
          <div className="bg-ui-header border border-ui-subtle rounded-ui-md p-2.5 space-y-2.5">
            <div className="flex items-center justify-between">
              <span className="text-[10px] font-medium text-ui-muted uppercase tracking-wider">
                {t('New Dimensions')}
              </span>
              <div className="flex items-center gap-1">
                <button
                  type="button"
                  onClick={handleToggleLockRatio}
                  className={`flex items-center gap-1 px-2 py-0.5 rounded-ui-sm text-[10px] transition-colors border cursor-pointer ${
                    lockRatio
                      ? 'bg-ui-accent-subtle border-ui-accent-border text-ui-accent font-medium'
                      : 'bg-ui-control border-ui-subtle text-ui-muted hover:text-ui-primary hover:bg-ui-control-hover'
                  }`}
                  title={
                    lockRatio
                      ? t('Keep aspect ratio locked (Shift also locks while dragging)')
                      : t('Aspect ratio free (hold Shift while dragging handles to lock)')
                  }
                >
                  {lockRatio ? (
                    <Lock className="w-2.5 h-2.5" />
                  ) : (
                    <Unlock className="w-2.5 h-2.5 text-ui-icon-muted" />
                  )}
                  <span>{lockRatio ? t('Keep Aspect Ratio') : t('Ratio Free')}</span>
                </button>
                <button
                  type="button"
                  onClick={() => updateDraft((prev) => applySwapDimensionsToDraft(prev))}
                  className="p-1 rounded-ui-sm bg-ui-control hover:bg-ui-control-hover border border-ui-subtle text-ui-muted hover:text-ui-primary transition-colors cursor-pointer"
                  title={t('Swap Width and Height (Landscape ⇄ Portrait)')}
                >
                  <ArrowLeftRight className="w-3 h-3" />
                </button>
              </div>
            </div>

            <div className="grid grid-cols-2 gap-2.5">
              <div className="space-y-1">
                <div className="flex items-center justify-between">
                  <label htmlFor={widthInputId} className="text-[11px] text-ui-muted">
                    {t('Width (px)')}
                  </label>
                  <span className="text-[10px] font-ui-mono tabular-nums text-ui-muted">
                    {percentW}%
                  </span>
                </div>
                <NumericDraftInput
                  id={widthInputId}
                  min={MIN_CANVAS_DIM}
                  max={MAX_CANVAS_DIM}
                  value={width}
                  onCommit={(val) => updateDraft((prev) => applyWidthToDraft(prev, val))}
                  className="w-full bg-ui-input border border-ui-default rounded-ui-sm px-2.5 py-1 font-ui-mono tabular-nums text-xs text-ui-primary focus:border-ui-focus"
                />
              </div>

              <div className="space-y-1">
                <div className="flex items-center justify-between">
                  <label htmlFor={heightInputId} className="text-[11px] text-ui-muted">
                    {t('Height (px)')}
                  </label>
                  <span className="text-[10px] font-ui-mono tabular-nums text-ui-muted">
                    {percentH}%
                  </span>
                </div>
                <NumericDraftInput
                  id={heightInputId}
                  min={MIN_CANVAS_DIM}
                  max={MAX_CANVAS_DIM}
                  value={height}
                  onCommit={(val) => updateDraft((prev) => applyHeightToDraft(prev, val))}
                  className="w-full bg-ui-input border border-ui-default rounded-ui-sm px-2.5 py-1 font-ui-mono tabular-nums text-xs text-ui-primary focus:border-ui-focus"
                />
              </div>
            </div>

            {/* Quick Ratio Presets */}
            <div className="flex flex-wrap items-center gap-1 pt-0.5">
              <button
                type="button"
                onClick={() => {
                  userToggledLockRef.current = true;
                  updateDraft((prev) => applyLockRatioToggleToDraft(prev, false));
                }}
                className={`px-1.5 py-0.5 rounded-ui-sm text-[10px] font-medium transition-colors border cursor-pointer ${
                  !lockRatio
                    ? 'bg-ui-accent border-transparent text-ui-accent-contrast'
                    : 'bg-ui-input border-ui-subtle text-ui-secondary hover:bg-ui-control-hover hover:text-ui-primary'
                }`}
              >
                {tc('aspectRatio', 'Free')}
              </button>
              {RATIO_PRESETS.map((r) => {
                const isActive = lockRatio && Math.abs(width / Math.max(1, height) - r.x / r.y) < 0.015;
                return (
                  <button
                    key={r.label}
                    type="button"
                    onClick={() => {
                      userToggledLockRef.current = true;
                      updateDraft((prev) => applyRatioPresetToDraft(prev, r.x, r.y));
                    }}
                    className={`px-1.5 py-0.5 rounded-ui-sm text-[10px] font-ui-mono tabular-nums transition-colors border cursor-pointer ${
                      isActive
                        ? 'bg-ui-accent border-transparent text-ui-accent-contrast font-medium'
                        : 'bg-ui-input border-ui-subtle text-ui-secondary hover:bg-ui-control-hover hover:text-ui-primary'
                    }`}
                  >
                    {r.label}
                  </button>
                );
              })}
            </div>
          </div>

          {/* Interactive Crop Bounds & Anchor (Canvas Bounds Mode) */}
          {isCropping && (
            <div className="bg-ui-header border border-ui-subtle rounded-ui-md p-2.5 space-y-2.5">
              <div className="flex items-center justify-between gap-2">
                <span className="text-[10px] font-medium text-ui-muted uppercase tracking-wider">
                  {t('Crop Frame & Anchor')}
                </span>
                <span className="text-[10px] text-ui-accent font-medium truncate">
                  {anchor ? td(ANCHOR_LABELS[anchor]) : t('Custom Crop')}
                </span>
              </div>

              {/* Crop Offset X / Y */}
              <div className="grid grid-cols-2 gap-2.5">
                <div className="space-y-0.5">
                  <label htmlFor={cropXInputId} className="text-[10px] text-ui-muted block">
                    {t('Crop X (px)')}
                  </label>
                  <NumericDraftInput
                    id={cropXInputId}
                    min={-MAX_CANVAS_DIM}
                    max={MAX_CANVAS_DIM}
                    value={cropX}
                    onCommit={(val) => updateDraft((prev) => applyCropXToDraft(prev, val))}
                    className="w-full bg-ui-input border border-ui-default rounded-ui-sm px-2.5 py-1 font-ui-mono tabular-nums text-xs text-ui-primary focus:border-ui-focus"
                  />
                </div>
                <div className="space-y-0.5">
                  <label htmlFor={cropYInputId} className="text-[10px] text-ui-muted block">
                    {t('Crop Y (px)')}
                  </label>
                  <NumericDraftInput
                    id={cropYInputId}
                    min={-MAX_CANVAS_DIM}
                    max={MAX_CANVAS_DIM}
                    value={cropY}
                    onCommit={(val) => updateDraft((prev) => applyCropYToDraft(prev, val))}
                    className="w-full bg-ui-input border border-ui-default rounded-ui-sm px-2.5 py-1 font-ui-mono tabular-nums text-xs text-ui-primary focus:border-ui-focus"
                  />
                </div>
              </div>

              {/* 3x3 Anchor Grid + On-Canvas Crop Shortcuts */}
              <div className="pt-2 border-t border-ui-subtle flex items-center justify-between gap-2">
                <div className="space-y-1.5 min-w-0 flex-1">
                  <p className="text-[10px] text-ui-muted leading-snug">
                    {t('Drag handles on canvas to crop or expand. Drag inside to move, or drag outside to draw a new crop.')}
                  </p>
                  <div className="flex flex-wrap items-center gap-1">
                    <button
                      type="button"
                      disabled={!modified}
                      onClick={() => updateDraft((prev) => applyResetCropToDraft(prev))}
                      className={`inline-flex items-center gap-1 px-2 py-1 rounded-ui-xs border text-[10px] transition-colors ${
                        modified
                          ? 'bg-ui-control hover:bg-ui-control-hover border-ui-subtle text-ui-primary cursor-pointer'
                          : 'bg-ui-input border-ui-subtle text-ui-disabled cursor-default opacity-60'
                      }`}
                      title={t('Reset crop box to current canvas dimensions')}
                    >
                      <RotateCcw className="w-3 h-3" />
                      <span>{t('Reset')}</span>
                    </button>

                    <button
                      type="button"
                      onClick={() =>
                        updateDraft((prev) => ({
                          ...prev,
                          gridMode: cycleCropGridMode(prev.gridMode),
                        }))
                      }
                      className="inline-flex items-center gap-1 px-2 py-1 rounded-ui-xs bg-ui-control hover:bg-ui-control-hover border border-ui-subtle text-[10px] text-ui-secondary hover:text-ui-primary transition-colors cursor-pointer"
                      title={t('Cycle crop composition guide grid')}
                    >
                      <Grid3X3 className="w-3 h-3" />
                      <span>{t('Grid: {mode}', { mode: td(formatGridMode(gridMode)) })}</span>
                    </button>

                    {selectionBounds && selectionBounds.width >= 1 && selectionBounds.height >= 1 && (
                      <button
                        type="button"
                        onClick={() =>
                          updateDraft((prev) => applyFitBoundsToDraft(prev, selectionBounds))
                        }
                        className="inline-flex items-center gap-1 px-2 py-1 rounded-ui-xs bg-ui-accent-subtle hover:bg-ui-accent-hover border border-ui-accent-border text-[10px] text-ui-accent font-medium transition-colors cursor-pointer"
                        title={t('Snap crop frame to active selection bounds')}
                      >
                        <SquareDashed className="w-3 h-3" />
                        <span>{t('Selection')}</span>
                      </button>
                    )}
                  </div>
                </div>

                <div className="grid grid-cols-3 gap-0.5 bg-ui-panel p-1 rounded-ui-md border border-ui-subtle shrink-0">
                  {ANCHOR_GRID.map((item) => {
                    const isSelected = anchor === item.id;
                    return (
                      <button
                        key={item.id}
                        type="button"
                        onClick={() => updateDraft((prev) => applyAnchorToDraft(prev, item.id))}
                        className={`w-6 h-6 rounded-ui-xs flex items-center justify-center transition-colors cursor-pointer ${
                          isSelected
                            ? 'bg-ui-accent text-ui-accent-contrast'
                            : 'bg-ui-input text-ui-muted hover:bg-ui-control-hover hover:text-ui-primary'
                        }`}
                        title={td(item.label)}
                      >
                        {item.icon}
                      </button>
                    );
                  })}
                </div>
              </div>
            </div>
          )}

          {/* Resolution (DPI) */}
          <div className="bg-ui-header border border-ui-subtle rounded-ui-md p-2.5 space-y-2">
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-1.5">
                <Printer className="w-3 h-3 text-ui-icon-muted" />
                <span className="text-[10px] font-medium text-ui-muted uppercase tracking-wider">
                  {t('Resolution (DPI)')}
                </span>
              </div>
              <span className="font-ui-mono tabular-nums text-[10px] text-ui-accent">
                {printDimensionsCm.w} × {printDimensionsCm.h} cm
              </span>
            </div>

            <div className="grid grid-cols-6 gap-1">
              {DPI_PRESETS.map((p) => {
                const isSelected = dpi === p.dpi;
                return (
                  <button
                    key={p.dpi}
                    type="button"
                    onClick={() => updateDraft((prev) => ({ ...prev, dpi: p.dpi }))}
                    className={`flex flex-col items-center justify-center py-1 px-0.5 rounded-ui-sm border transition-colors cursor-pointer ${
                      isSelected
                        ? 'bg-ui-accent border-transparent text-ui-accent-contrast font-medium'
                        : 'bg-ui-input border-ui-subtle text-ui-secondary hover:bg-ui-control-hover hover:text-ui-primary'
                    }`}
                  >
                    <span className="font-ui-mono tabular-nums text-[10px] font-semibold">
                      {p.dpi}
                    </span>
                  </button>
                );
              })}
            </div>

            <div className="pt-1.5 border-t border-ui-subtle flex items-center justify-between">
              <div className="flex items-center gap-1.5">
                <label htmlFor={dpiInputId} className="text-[10px] text-ui-muted">
                  {t('Manual DPI:')}
                </label>
                <NumericDraftInput
                  id={dpiInputId}
                  min={1}
                  max={4800}
                  value={dpi}
                  onCommit={(val) =>
                    updateDraft((prev) => ({
                      ...prev,
                      dpi: Math.max(1, Math.min(4800, Math.round(val) || 1)),
                    }))
                  }
                  className="w-16 bg-ui-input border border-ui-default rounded-ui-sm px-2 py-0.5 text-center font-ui-mono tabular-nums text-[11px] text-ui-primary focus:border-ui-focus"
                />
              </div>
              <span className="text-[10px] text-ui-muted font-ui-mono tabular-nums">
                {megapixels} MP
              </span>
            </div>
          </div>
        </div>

        {/* Footer */}
        <div className="px-3 py-2 bg-ui-header border-t border-ui-subtle flex items-center justify-between shrink-0 gap-2">
          <span className="text-[10px] text-ui-muted truncate">
            {t('Ratio:')}{' '}
            <span className="font-ui-mono tabular-nums text-ui-primary">{simplifiedRatio}</span>
          </span>

          <div className="flex items-center gap-1.5 shrink-0">
            <button
              type="button"
              onClick={onClose}
              className="px-3 py-1 rounded-ui-sm bg-ui-control hover:bg-ui-control-hover border border-ui-default text-[11px] font-medium text-ui-primary transition-colors cursor-pointer"
            >
              {t('Cancel')}
            </button>
            <button
              type="button"
              onClick={handleApplyResize}
              className="inline-flex items-center gap-1 px-3 py-1 rounded-ui-sm bg-ui-accent text-ui-accent-contrast hover:opacity-90 text-[11px] font-medium transition-opacity cursor-pointer"
            >
              <Check className="w-3.5 h-3.5" />
              <span>{applyButtonLabel}</span>
            </button>
          </div>
        </div>
      </div>
    </div>
  );
};