Skip to content

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

58.8 KB
Raw Blame
import React, { useCallback, useEffect, useRef, useState } from 'react';
import {
  Camera,
  Check,
  ChevronDown,
  ChevronLeft,
  ChevronRight,
  Circle,
  Download,
  Film,
  FolderClock,
  HardDrive,
  Loader2,
  Maximize2,
  Pause,
  Play,
  RefreshCw,
  Repeat,
  SkipBack,
  SlidersHorizontal,
  Square,
  Stamp,
  Trash2,
  X,
} from 'lucide-react';
import {
  formatTimelapseBytes,
  globalTimelapseManager,
  StoredRecordingSummary,
  TimelapseAspectRatio,
  TimelapseBackgroundMode,
  TimelapseCaptureArea,
  TimelapseCaptureResolution,
  TimelapseDurationPreset,
  TimelapseFps,
  TimelapseQualityPreset,
  TimelapseResolution,
  TimelapseWatermarkConfig,
} from '../utils/timelapseEngine';
import {
  loadSavedWatermarkConfig,
  saveWatermarkConfig,
} from '../utils/timelapseWatermark';
import { saveFileWithDialog } from '../utils/fileSaveDialog';
import { sanitizeDocumentStem } from '../utils/saveManager/fileNameUtils';
import { documentStoreActions, useUiStore } from '../stores';
import { ToggleSwitch } from './ui';
import {
  formatTimecode,
  TimelapsePlaybackSpeed,
  useTimelapsePreviewPlayer,
} from './timelapse/useTimelapsePreviewPlayer';
import { TimelapseFullscreenViewer } from './timelapse/TimelapseFullscreenViewer';
import { TimelapseWatermarkControls } from './timelapse/TimelapseWatermarkControls';
import { isImeComposing, useI18n } from '../i18n';

interface TimelapseExportModalProps {
  isOpen: boolean;
  onClose: () => void;
  documentId: string | null;
  documentName: string;
  onCaptureNow?: () => void;
  showToast?: (msg: string) => void;
}

type InspectorTab = 'export' | 'watermark' | 'library';

const CAPTURE_AREA_OPTIONS: Array<{
  value: TimelapseCaptureArea;
  label: string;
  description: string;
}> = [
  {
    value: 'artwork',
    label: 'Artwork only',
    description: 'Clean upright canvas without UI or zoom wobble',
  },
  {
    value: 'canvas-view',
    label: 'Canvas view',
    description: 'Live viewport with pan, zoom, rotation & view flip',
  },
  {
    value: 'app-window',
    label: 'App window',
    description: 'Entire Ink Studio window including panels & canvas',
  },
];

const CAPTURE_RES_OPTIONS: Array<{ value: TimelapseCaptureResolution; label: string }> = [
  { value: '720p', label: '720p' },
  { value: '1080p', label: '1080p' },
  { value: '2k', label: '2K' },
  { value: '4k', label: '4K' },
];

const DURATION_OPTIONS: Array<{ value: TimelapseDurationPreset; label: string }> = [
  { value: '15s', label: '15s' },
  { value: '30s', label: '30s' },
  { value: '60s', label: '60s' },
  { value: '120s', label: '2m' },
  { value: 'full', label: 'Full' },
  { value: 'custom', label: 'Custom' },
];

const FPS_OPTIONS: TimelapseFps[] = [24, 30, 60];

const QUALITY_OPTIONS: Array<{ value: TimelapseQualityPreset; label: string }> = [
  { value: 'standard', label: 'Std' },
  { value: 'high', label: 'High' },
  { value: 'ultra', label: 'Ultra' },
  { value: 'lossless', label: 'Max' },
];

const EXPORT_RES_OPTIONS: Array<{ value: TimelapseResolution; label: string }> = [
  { value: '720p', label: '720p' },
  { value: '1080p', label: '1080p' },
  { value: '2k', label: '2K' },
  { value: '4k', label: '4K' },
];

const ASPECT_RATIO_OPTIONS: Array<{ value: TimelapseAspectRatio; label: string }> = [
  { value: 'original', label: 'Orig' },
  { value: '16:9', label: '16:9' },
  { value: '9:16', label: '9:16' },
  { value: '1:1', label: '1:1' },
  { value: '4:5', label: '4:5' },
];

const SPEED_CYCLE: TimelapsePlaybackSpeed[] = [0.5, 1, 2];

export const TimelapseExportModal: React.FC<TimelapseExportModalProps> = ({
  isOpen,
  onClose,
  documentId,
  documentName,
  onCaptureNow,
  showToast,
}) => {
  const { t, tc, td, formatDateTime } = useI18n();
  const userName = useUiStore((s) => s.appSettings.userName);

  const formatRecordedDate = useCallback(
    (ts: number): string => {
      if (!ts) return t('Unknown date');
      const formatted = formatDateTime(ts, {
        month: 'short',
        day: 'numeric',
        hour: '2-digit',
        minute: '2-digit',
      });
      return formatted || t('Saved locally');
    },
    [formatDateTime, t]
  );

  // Export & Preview Settings
  const [duration, setDuration] = useState<TimelapseDurationPreset>('30s');
  const [customDurationSec, setCustomDurationSec] = useState<number>(45);
  const [fps, setFps] = useState<TimelapseFps>(30);
  const [quality, setQuality] = useState<TimelapseQualityPreset>('high');
  const [aspectRatio, setAspectRatio] = useState<TimelapseAspectRatio>('original');
  const [resolution, setResolution] = useState<TimelapseResolution>('1080p');
  const [backgroundMode, setBackgroundMode] = useState<TimelapseBackgroundMode>('white');
  const [customBgColor, setCustomBgColor] = useState<string>('#202024');
  const [preferFfmpeg, setPreferFfmpeg] = useState(false);
  const [ffmpegAvailable, setFfmpegAvailable] = useState(false);

  // Watermark State (persisted across sessions)
  const [watermark, setWatermark] = useState<TimelapseWatermarkConfig>(() =>
    loadSavedWatermarkConfig(userName ? `@${userName}` : 'Ink Studio')
  );

  // UI / Playback / Dropdown / Library State
  const [activeTab, setActiveTab] = useState<InspectorTab>('export');
  const [isFullscreen, setIsFullscreen] = useState(false);
  const [playbackSpeed, setPlaybackSpeed] = useState<TimelapsePlaybackSpeed>(1);
  const [loop, setLoop] = useState(true);
  const [openDropdown, setOpenDropdown] = useState<'capture' | 'max-size' | null>(null);
  const [storedRecordings, setStoredRecordings] = useState<StoredRecordingSummary[]>([]);
  const [loadingRecordings, setLoadingRecordings] = useState(false);

  const [stats, setStats] = useState(() => globalTimelapseManager.getStats(documentId));
  const [isExporting, setIsExporting] = useState(false);
  const [exportProgress, setExportProgress] = useState(0);
  const [errorMsg, setErrorMsg] = useState<string | null>(null);

  const dropdownBarRef = useRef<HTMLDivElement | null>(null);

  const effectiveBgColor =
    backgroundMode === 'dark'
      ? '#141414'
      : backgroundMode === 'custom'
        ? customBgColor
        : '#ffffff';

  const player = useTimelapsePreviewPlayer({
    isOpen,
    documentId,
    frameCount: stats.frameCount,
    duration,
    customDurationSec,
    fps,
    aspectRatio,
    resolution,
    backgroundMode,
    backgroundColor: effectiveBgColor,
    watermark,
    playbackSpeed,
    loop,
    isFullscreen,
  });

  const refreshStoredRecordings = useCallback(async () => {
    setLoadingRecordings(true);
    try {
      const list = await globalTimelapseManager.listStoredRecordings();
      setStoredRecordings(list);
    } finally {
      setLoadingRecordings(false);
    }
  }, []);

  // Subscribe to session stats & check FFmpeg on modal open
  useEffect(() => {
    if (!isOpen) {
      setIsFullscreen(false);
      setOpenDropdown(null);
      return;
    }
    setStats(globalTimelapseManager.getStats(documentId));
    globalTimelapseManager.checkFfmpegAvailable().then((ok) => {
      setFfmpegAvailable(ok);
      if (ok) setPreferFfmpeg(true);
    });
    const unsub = globalTimelapseManager.subscribe(() => {
      setStats(globalTimelapseManager.getStats(documentId));
    });
    return () => {
      unsub();
    };
  }, [isOpen, documentId]);

  useEffect(() => {
    if (isOpen && activeTab === 'library') {
      void refreshStoredRecordings();
    }
  }, [isOpen, activeTab, refreshStoredRecordings]);

  // Close capture/resolution popover when clicking outside
  useEffect(() => {
    if (!openDropdown) return;
    const handlePointerDown = (e: MouseEvent) => {
      if (
        dropdownBarRef.current &&
        e.target instanceof Node &&
        !dropdownBarRef.current.contains(e.target)
      ) {
        setOpenDropdown(null);
      }
    };
    window.addEventListener('mousedown', handlePointerDown);
    return () => window.removeEventListener('mousedown', handlePointerDown);
  }, [openDropdown]);

  // Keyboard shortcuts: Esc, F (fullscreen), Space (play/pause), Left/Right arrows (step)
  useEffect(() => {
    if (!isOpen) return;
    const handleKeyDown = (e: KeyboardEvent) => {
      if (isImeComposing(e)) return;
      const target = e.target as HTMLElement | null;
      const isTextInput =
        target &&
        (target.tagName === 'INPUT' ||
          target.tagName === 'TEXTAREA' ||
          target.isContentEditable);

      if (e.key === 'Escape') {
        e.preventDefault();
        e.stopPropagation();
        if (openDropdown) {
          setOpenDropdown(null);
        } else if (isFullscreen) {
          setIsFullscreen(false);
        } else if (!isExporting) {
          onClose();
        }
        return;
      }

      if (isTextInput || isExporting) return;

      if (e.key === 'f' || e.key === 'F') {
        if (stats.frameCount > 0) {
          e.preventDefault();
          setIsFullscreen((prev) => !prev);
        }
      } else if (e.key === ' ') {
        if (stats.frameCount > 1 && target?.tagName !== 'BUTTON') {
          e.preventDefault();
          player.togglePlay();
        }
      } else if (e.key === 'ArrowLeft' && stats.frameCount > 0) {
        e.preventDefault();
        player.stepBy(-1);
      } else if (e.key === 'ArrowRight' && stats.frameCount > 0) {
        e.preventDefault();
        player.stepBy(1);
      }
    };
    window.addEventListener('keydown', handleKeyDown, true);
    return () => window.removeEventListener('keydown', handleKeyDown, true);
  }, [isOpen, isExporting, isFullscreen, openDropdown, stats.frameCount, onClose, player]);

  const handleWatermarkChange = useCallback((next: TimelapseWatermarkConfig) => {
    setWatermark(next);
    saveWatermarkConfig(next);
  }, []);

  if (!isOpen) return null;

  const cleanDocName = (documentName || 'Untitled').replace(/\*+$/, '').trim() || 'Untitled';
  const activeAreaMeta =
    CAPTURE_AREA_OPTIONS.find((o) => o.value === stats.captureArea) ?? CAPTURE_AREA_OPTIONS[0];
  const activeCapResMeta =
    CAPTURE_RES_OPTIONS.find((o) => o.value === stats.captureResolution) ?? CAPTURE_RES_OPTIONS[1];

  const handleToggleRecording = () => {
    if (!documentId) return;
    const next = globalTimelapseManager.toggleRecording(documentId, cleanDocName);
    documentStoreActions.markDocumentDirty(documentId, true);
    if (next) {
      onCaptureNow?.();
      showToast?.(t('Time-lapse recording enabled (saved locally)'));
    } else {
      showToast?.(t('Time-lapse recording paused'));
    }
  };

  const handleSelectCaptureArea = (area: TimelapseCaptureArea) => {
    if (!documentId) return;
    globalTimelapseManager.setCaptureArea(documentId, area);
    documentStoreActions.markDocumentDirty(documentId, true);
    setOpenDropdown(null);
    const label = CAPTURE_AREA_OPTIONS.find((o) => o.value === area)?.label ?? area;
    showToast?.(t('Capture area set to {label}', { label: t(label) }));
  };

  const handleSelectCaptureResolution = (res: TimelapseCaptureResolution) => {
    if (!documentId) return;
    globalTimelapseManager.setCaptureResolution(documentId, res);
    documentStoreActions.markDocumentDirty(documentId, true);
    setOpenDropdown(null);
  };

  const handleClear = async () => {
    if (!documentId) return;
    player.setIsPlaying(false);
    setIsFullscreen(false);
    await globalTimelapseManager.clearSession(documentId);
    documentStoreActions.markDocumentDirty(documentId, true);
    showToast?.(t('Time-lapse recording cleared'));
    if (activeTab === 'library') {
      void refreshStoredRecordings();
    }
  };

  const handleAttachRecording = async (rec: StoredRecordingSummary) => {
    if (!documentId) return;
    player.setIsPlaying(false);
    const res = await globalTimelapseManager.attachExistingRecording(
      documentId,
      rec.recordingId,
      cleanDocName
    );
    documentStoreActions.markDocumentDirty(documentId, true);
    showToast?.(
      t('Attached "{name}" ({count} frames)', {
        name: rec.documentName,
        count: res.frameCount,
      })
    );
    setActiveTab('export');
  };

  const handleDeleteStoredRecording = async (rec: StoredRecordingSummary) => {
    await globalTimelapseManager.deleteStoredRecording(rec.recordingId);
    showToast?.(t('Deleted local recording "{name}"', { name: rec.documentName }));
    void refreshStoredRecordings();
  };

  const handleCycleSpeed = () => {
    setPlaybackSpeed((prev) => {
      const idx = SPEED_CYCLE.indexOf(prev);
      return SPEED_CYCLE[(idx + 1) % SPEED_CYCLE.length];
    });
  };

  const handleExport = async () => {
    if (!documentId) return;
    setIsExporting(true);
    setExportProgress(0);
    setErrorMsg(null);
    player.setIsPlaying(false);
    try {
      const result = await globalTimelapseManager.exportVideo(
        documentId,
        {
          duration,
          customDurationSec,
          aspectRatio,
          resolution,
          fps,
          quality,
          backgroundMode,
          backgroundColor: effectiveBgColor,
          watermark,
          preferFfmpeg,
        },
        (p) => setExportProgress(p)
      );
      const safeName = sanitizeDocumentStem(cleanDocName, 'timelapse');
      const durTag = duration === 'custom' ? `${Math.round(customDurationSec)}s` : duration;
      const suggestedName = `${safeName}_timelapse_${durTag}_${fps}fps${result.extension}`;
      const saveRes = await saveFileWithDialog({
        data: result.blob,
        suggestedName,
        mimeType: result.mimeType,
        description: result.extension === '.mp4' ? t('MP4 Video') : t('WebM Video'),
        extensions: [result.extension],
        category: 'timelapse',
        title: t('Save Time-lapse Video As'),
      });
      if (saveRes.canceled) {
        return;
      }
      showToast?.(
        t('Exported {duration}s time-lapse ({fps} FPS, {ext})', {
          duration: result.durationSec.toFixed(1),
          fps,
          ext: result.extension,
        })
      );
    } catch (err) {
      setErrorMsg(err instanceof Error ? err.message : t('Time-lapse export failed'));
    } finally {
      setIsExporting(false);
    }
  };

  const storageLabel =
    stats.storageBackend === 'disk'
      ? t('Local app storage')
      : stats.storageBackend === 'indexeddb'
        ? t('Browser storage')
        : t('Session RAM');

  const progressPct =
    player.totalTimelineFrames > 1
      ? (player.timelineIndex / (player.totalTimelineFrames - 1)) * 100
      : 0;

  return (
    <>
      <div
        role="dialog"
        aria-modal="true"
        aria-labelledby="timelapse-modal-title"
        className="fixed inset-0 z-50 flex items-center justify-center bg-ui-overlay p-3 sm:p-4 select-none"
        onClick={() => {
          if (!isExporting && !isFullscreen) onClose();
        }}
      >
        <div
          onClick={(e) => e.stopPropagation()}
          className="w-[840px] max-w-[96vw] max-h-[92vh] bg-ui-panel border border-ui-default rounded-ui-lg shadow-ui-popover overflow-hidden text-xs text-ui-primary flex flex-col"
        >
          {/* Header */}
          <div className="h-10 px-4 bg-ui-header border-b border-ui-subtle flex items-center justify-between shrink-0">
            <div className="flex items-center gap-2 font-medium text-ui-primary">
              <Film className="w-3.5 h-3.5 text-ui-accent" />
              <span id="timelapse-modal-title">{t('Time-lapse Studio')}</span>
            </div>
            <button
              type="button"
              onClick={onClose}
              disabled={isExporting}
              aria-label={t('Close')}
              title={t('Close (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 disabled:opacity-40"
            >
              <X className="w-3.5 h-3.5" />
            </button>
          </div>

          {/* Top Recording & Capture Area Strip */}
          <div
            ref={dropdownBarRef}
            className="px-4 py-2.5 bg-ui-header/70 border-b border-ui-subtle space-y-2 shrink-0"
          >
            <div className="flex flex-wrap items-end justify-between gap-3">
              {/* Capture Area + Max Size Dropdowns */}
              <div className="flex items-end gap-2.5">
                {/* Capture Area Dropdown */}
                <div className="relative">
                  <span className="block text-[10px] text-ui-muted mb-1">{t('Capture')}</span>
                  <button
                    type="button"
                    disabled={!documentId || isExporting}
                    aria-haspopup="listbox"
                    aria-expanded={openDropdown === 'capture'}
                    onClick={() =>
                      setOpenDropdown((prev) => (prev === 'capture' ? null : 'capture'))
                    }
                    className={`h-7 min-w-[138px] px-2.5 rounded-ui-sm bg-ui-input border text-xs font-medium text-ui-primary flex items-center justify-between gap-2 cursor-pointer transition-colors disabled:opacity-40 ${
                      openDropdown === 'capture'
                        ? 'border-ui-focus bg-ui-control'
                        : 'border-ui-default hover:border-ui-strong'
                    }`}
                  >
                    <span>{t(activeAreaMeta.label)}</span>
                    <ChevronDown
                      className={`w-3 h-3 text-ui-muted transition-transform ${
                        openDropdown === 'capture' ? 'rotate-180' : ''
                      }`}
                    />
                  </button>

                  {openDropdown === 'capture' && (
                    <div
                      role="listbox"
                      aria-label={t('Capture area')}
                      className="absolute left-0 top-full mt-1 w-64 z-30 bg-ui-floating border border-ui-strong rounded-ui-md shadow-ui-popover p-1 space-y-0.5"
                    >
                      {CAPTURE_AREA_OPTIONS.map((opt) => {
                        const selected = stats.captureArea === opt.value;
                        return (
                          <button
                            key={opt.value}
                            type="button"
                            role="option"
                            aria-selected={selected}
                            onClick={() => handleSelectCaptureArea(opt.value)}
                            className={`w-full text-left px-2 py-1.5 rounded-ui-sm flex items-start gap-2 cursor-pointer transition-colors ${
                              selected
                                ? 'bg-ui-control-active text-ui-primary'
                                : 'text-ui-secondary hover:bg-ui-control-hover hover:text-ui-primary'
                            }`}
                          >
                            <span className="w-3.5 h-3.5 mt-0.5 flex items-center justify-center shrink-0">
                              {selected && <Check className="w-3.5 h-3.5 text-ui-accent" />}
                            </span>
                            <span className="min-w-0">
                              <span className="block text-xs font-medium leading-tight">
                                {t(opt.label)}
                              </span>
                              <span className="block text-[10px] text-ui-muted leading-snug mt-0.5">
                                {t(opt.description)}
                              </span>
                            </span>
                          </button>
                        );
                      })}
                    </div>
                  )}
                </div>

                {/* Maximum Capture Resolution Dropdown */}
                <div className="relative">
                  <span className="block text-[10px] text-ui-muted mb-1">{t('Maximum')}</span>
                  <button
                    type="button"
                    disabled={!documentId || isExporting}
                    aria-haspopup="listbox"
                    aria-expanded={openDropdown === 'max-size'}
                    onClick={() =>
                      setOpenDropdown((prev) => (prev === 'max-size' ? null : 'max-size'))
                    }
                    className={`h-7 min-w-[78px] px-2.5 rounded-ui-sm bg-ui-input border text-xs font-ui-mono font-medium text-ui-primary flex items-center justify-between gap-2 cursor-pointer transition-colors disabled:opacity-40 ${
                      openDropdown === 'max-size'
                        ? 'border-ui-focus bg-ui-control'
                        : 'border-ui-default hover:border-ui-strong'
                    }`}
                  >
                    <span>{activeCapResMeta.label}</span>
                    <ChevronDown
                      className={`w-3 h-3 text-ui-muted transition-transform ${
                        openDropdown === 'max-size' ? 'rotate-180' : ''
                      }`}
                    />
                  </button>

                  {openDropdown === 'max-size' && (
                    <div
                      role="listbox"
                      aria-label={t('Maximum capture resolution')}
                      className="absolute left-0 top-full mt-1 w-32 z-30 bg-ui-floating border border-ui-strong rounded-ui-md shadow-ui-popover p-1 space-y-0.5"
                    >
                      {CAPTURE_RES_OPTIONS.map((opt) => {
                        const selected = stats.captureResolution === opt.value;
                        return (
                          <button
                            key={opt.value}
                            type="button"
                            role="option"
                            aria-selected={selected}
                            onClick={() => handleSelectCaptureResolution(opt.value)}
                            className={`w-full text-left px-2 py-1.5 rounded-ui-sm flex items-center gap-2 font-ui-mono text-xs cursor-pointer transition-colors ${
                              selected
                                ? 'bg-ui-control-active text-ui-primary font-semibold'
                                : 'text-ui-secondary hover:bg-ui-control-hover hover:text-ui-primary'
                            }`}
                          >
                            <span className="w-3.5 h-3.5 flex items-center justify-center">
                              {selected && <Check className="w-3.5 h-3.5 text-ui-accent" />}
                            </span>
                            <span>{opt.label}</span>
                          </button>
                        );
                      })}
                    </div>
                  )}
                </div>
              </div>

              {/* Record / Snapshot / Clear Action Controls */}
              <div className="flex items-center gap-1.5">
                <button
                  type="button"
                  disabled={!documentId || isExporting}
                  onClick={handleToggleRecording}
                  className={`h-7 px-3 rounded-ui-sm text-[11px] font-medium flex items-center gap-1.5 cursor-pointer transition-colors disabled:opacity-40 border ${
                    stats.enabled
                      ? 'bg-ui-danger/20 hover:bg-ui-danger/30 text-ui-danger border-ui-danger/45'
                      : 'bg-ui-control hover:bg-ui-control-hover text-ui-primary border-ui-default'
                  }`}
                >
                  {stats.enabled ? (
                    <>
                      <Square className="w-3 h-3 fill-current" />
                      <span>{t('Pause Recording')}</span>
                    </>
                  ) : (
                    <>
                      <Circle className="w-3 h-3 text-ui-danger fill-ui-danger" />
                      <span>{stats.frameCount > 0 ? t('Continue Recording') : t('Record')}</span>
                    </>
                  )}
                </button>

                <button
                  type="button"
                  disabled={!documentId || !stats.enabled || isExporting}
                  onClick={() => onCaptureNow?.()}
                  title={t('Capture keyframe now')}
                  className="h-7 px-2 rounded-ui-sm bg-ui-control hover:bg-ui-control-hover border border-ui-default text-ui-secondary hover:text-ui-primary transition-colors cursor-pointer disabled:opacity-35"
                >
                  <Camera className="w-3.5 h-3.5" />
                </button>

                <button
                  type="button"
                  disabled={!documentId || stats.frameCount === 0 || isExporting}
                  onClick={handleClear}
                  title={t('Clear recorded keyframes')}
                  className="h-7 px-2 rounded-ui-sm bg-ui-control hover:bg-ui-danger/15 border border-ui-subtle hover:border-ui-danger/40 text-ui-muted hover:text-ui-danger transition-colors cursor-pointer disabled:opacity-35"
                >
                  <Trash2 className="w-3.5 h-3.5" />
                </button>
              </div>
            </div>

            {/* Compact Session Telemetry Line */}
            <div className="flex flex-wrap items-center justify-between gap-2 text-[11px] text-ui-muted">
              <div className="flex items-center gap-2 min-w-0">
                <span
                  className={`w-2 h-2 rounded-full shrink-0 ${
                    stats.enabled ? 'bg-ui-danger animate-pulse' : 'bg-ui-disabled'
                  }`}
                />
                <span className="text-ui-secondary font-medium truncate max-w-[180px]">
                  {td(cleanDocName)}
                </span>
                <span className="font-ui-mono tabular-nums">
                  ·{' '}
                  {stats.frameCount === 1
                    ? t('{count} frame', { count: 1 })
                    : t('{count} frames', { count: stats.frameCount })}{' '}
                  · {formatTimelapseBytes(stats.storageBytes)}
                </span>
              </div>
              <div className="flex items-center gap-1.5 text-[10px] text-ui-muted">
                <HardDrive className="w-3 h-3 text-ui-accent" />
                <span>
                  {t('{storage} · resumes automatically after restart', {
                    storage: storageLabel,
                  })}
                </span>
              </div>
            </div>
          </div>

          {/* Two-Column Body: Live Preview Left + Inspector Tabs Right */}
          <div className="flex-1 min-h-0 grid grid-cols-1 md:grid-cols-12 overflow-y-auto md:overflow-hidden">
            {/* LEFT: WYSIWYG Preview Player */}
            <div className="md:col-span-7 p-4 flex flex-col gap-2.5 border-b md:border-b-0 md:border-r border-ui-subtle bg-ui-panel">
              {/* Preview Canvas Viewport */}
              <div className="relative flex-1 min-h-[250px] max-h-[380px] flex items-center justify-center overflow-hidden rounded-ui-md bg-ui-void border border-ui-subtle group">
                {stats.frameCount > 0 ? (
                  <>
                    <canvas
                      ref={player.modalCanvasRef}
                      onClick={player.togglePlay}
                      onDoubleClick={() => setIsFullscreen(true)}
                      title={t('Click to Play/Pause · Double-click for Full-Screen')}
                      className="max-h-full max-w-full object-contain cursor-pointer"
                    />
                    {/* Top-left info badge */}
                    <div className="absolute top-2 left-2 px-2 py-0.5 rounded-ui-xs bg-black/65 text-white/90 text-[10px] font-ui-mono tabular-nums pointer-events-none">
                      {player.outputDims.width}×{player.outputDims.height} · {fps} FPS
                      {watermark.enabled ? ` · ${t('WM')}` : ''}
                    </div>
                    {/* Top-right Full-Screen Trigger */}
                    <button
                      type="button"
                      onClick={() => setIsFullscreen(true)}
                      aria-label={t('View in full-screen')}
                      title={t('Full-Screen Preview (F)')}
                      className="absolute top-2 right-2 px-2 py-1 rounded-ui-sm bg-black/65 hover:bg-black/85 text-white text-[10px] flex items-center gap-1 cursor-pointer transition-colors"
                    >
                      <Maximize2 className="w-3 h-3" />
                      <span>{t('Full-screen')}</span>
                    </button>
                  </>
                ) : (
                  <div className="text-[11px] text-ui-muted text-center px-6 space-y-1.5">
                    <Film className="w-6 h-6 mx-auto text-ui-disabled" />
                    <div className="text-ui-secondary font-medium">
                      {t('No time-lapse frames yet')}
                    </div>
                    <div>
                      {t(
                        'Click Record and draw strokes to capture keyframes automatically in external storage.'
                      )}
                    </div>
                  </div>
                )}
              </div>

              {/* Direct In-App Preview Interval Switcher (15s / 30s / 60s / 2m / Full / Custom) */}
              <div className="flex flex-wrap items-center justify-between gap-2 bg-ui-header rounded-ui-md border border-ui-subtle px-2.5 py-1.5">
                <span className="text-[10px] uppercase tracking-wider text-ui-muted">
                  {t('Preview clip')}
                </span>
                <div className="flex items-center gap-1 flex-wrap">
                  {DURATION_OPTIONS.map((opt) => (
                    <button
                      key={opt.value}
                      type="button"
                      disabled={isExporting}
                      onClick={() => setDuration(opt.value)}
                      className={`px-2 py-0.5 rounded-ui-xs font-ui-mono tabular-nums text-[10px] cursor-pointer transition-colors ${
                        duration === opt.value
                          ? 'bg-ui-accent text-ui-accent-contrast font-semibold'
                          : 'bg-ui-control text-ui-muted hover:text-ui-primary hover:bg-ui-control-hover'
                      }`}
                    >
                      {opt.value === 'full' ? tc('timelapse', opt.label) : t(opt.label)}
                    </button>
                  ))}
                  {duration === 'custom' && (
                    <div className="flex items-center gap-1 ml-1">
                      <input
                        type="number"
                        min={2}
                        max={600}
                        value={customDurationSec}
                        disabled={isExporting}
                        onChange={(e) =>
                          setCustomDurationSec(
                            Math.max(2, Math.min(600, Number(e.target.value) || 30))
                          )
                        }
                        onKeyDown={(e) => {
                          e.stopPropagation();
                          if (isImeComposing(e)) return;
                        }}
                        aria-label={t('Custom duration seconds')}
                        className="w-12 h-5 px-1 rounded-ui-xs bg-ui-input border border-ui-default text-[10px] font-ui-mono text-ui-primary text-right"
                      />
                      <span className="text-[10px] text-ui-muted">{tc('unit', 's')}</span>
                    </div>
                  )}
                </div>
              </div>

              {/* Timeline Scrubber & Transport Controls */}
              <div className="bg-ui-header rounded-ui-md border border-ui-subtle p-2 space-y-2">
                <div className="flex items-center gap-2">
                  <span className="text-[10px] font-ui-mono tabular-nums text-ui-primary w-11">
                    {formatTimecode(player.currentTimeSec)}
                  </span>
                  <input
                    type="range"
                    aria-label={t('Time-lapse preview timeline')}
                    disabled={stats.frameCount === 0}
                    min={0}
                    max={Math.max(0, player.totalTimelineFrames - 1)}
                    value={Math.min(
                      player.timelineIndex,
                      Math.max(0, player.totalTimelineFrames - 1)
                    )}
                    onChange={(e) => player.seekTo(Number(e.target.value))}
                    className="flex-1 cursor-pointer disabled:opacity-40"
                    style={{
                      background: `linear-gradient(to right, var(--ui-accent) ${progressPct}%, var(--ui-bg-input) ${progressPct}%)`,
                    }}
                  />
                  <span className="text-[10px] font-ui-mono tabular-nums text-ui-muted w-11 text-right">
                    {formatTimecode(player.totalDurationSec)}
                  </span>
                </div>

                <div className="flex items-center justify-between gap-2">
                  <div className="flex items-center gap-1">
                    <button
                      type="button"
                      disabled={stats.frameCount === 0}
                      onClick={player.restart}
                      title={t('Jump to start')}
                      className="p-1 rounded-ui-sm bg-ui-control hover:bg-ui-control-hover border border-ui-subtle text-ui-secondary hover:text-ui-primary cursor-pointer disabled:opacity-35"
                    >
                      <SkipBack className="w-3 h-3" />
                    </button>
                    <button
                      type="button"
                      disabled={stats.frameCount === 0}
                      onClick={() => player.stepBy(-1)}
                      title={t('Previous frame (Left Arrow)')}
                      className="p-1 rounded-ui-sm bg-ui-control hover:bg-ui-control-hover border border-ui-subtle text-ui-secondary hover:text-ui-primary cursor-pointer disabled:opacity-35"
                    >
                      <ChevronLeft className="w-3 h-3" />
                    </button>
                    <button
                      type="button"
                      disabled={stats.frameCount <= 1}
                      onClick={player.togglePlay}
                      title={t('Play / Pause (Space)')}
                      className="px-2.5 py-1 rounded-ui-sm bg-ui-control-active hover:bg-ui-control-hover border border-ui-default text-ui-primary flex items-center gap-1 text-[11px] font-medium cursor-pointer disabled:opacity-35"
                    >
                      {player.isPlaying ? (
                        <>
                          <Pause className="w-3 h-3" />
                          <span>{t('Pause')}</span>
                        </>
                      ) : (
                        <>
                          <Play className="w-3 h-3" />
                          <span>{t('Play')}</span>
                        </>
                      )}
                    </button>
                    <button
                      type="button"
                      disabled={stats.frameCount === 0}
                      onClick={() => player.stepBy(1)}
                      title={t('Next frame (Right Arrow)')}
                      className="p-1 rounded-ui-sm bg-ui-control hover:bg-ui-control-hover border border-ui-subtle text-ui-secondary hover:text-ui-primary cursor-pointer disabled:opacity-35"
                    >
                      <ChevronRight className="w-3 h-3" />
                    </button>
                    <button
                      type="button"
                      onClick={() => setLoop((l) => !l)}
                      title={loop ? t('Loop playback on') : t('Loop playback off')}
                      className={`p-1 rounded-ui-sm border cursor-pointer transition-colors ${
                        loop
                          ? 'bg-ui-accent-subtle border-ui-accent-border text-ui-accent'
                          : 'bg-ui-control border-ui-subtle text-ui-muted hover:text-ui-primary'
                      }`}
                    >
                      <Repeat className="w-3 h-3" />
                    </button>
                    <button
                      type="button"
                      onClick={handleCycleSpeed}
                      title={t('Preview playback speed')}
                      className="px-1.5 py-0.5 rounded-ui-sm bg-ui-control hover:bg-ui-control-hover border border-ui-subtle text-[10px] font-ui-mono tabular-nums text-ui-secondary cursor-pointer"
                    >
                      {playbackSpeed}×
                    </button>
                  </div>

                  <div className="flex items-center gap-2">
                    <span className="text-[10px] font-ui-mono tabular-nums text-ui-muted">
                      {stats.frameCount > 0
                        ? t('Key {current}/{total}', {
                            current: Math.min(player.currentSourceFrameIndex + 1, stats.frameCount),
                            total: stats.frameCount,
                          })
                        : '0/0'}
                    </span>
                    <button
                      type="button"
                      disabled={stats.frameCount === 0}
                      onClick={() => setIsFullscreen(true)}
                      title={t('Full-Screen Preview (F)')}
                      className="p-1 rounded-ui-sm bg-ui-control hover:bg-ui-control-hover border border-ui-default text-ui-primary cursor-pointer disabled:opacity-35"
                    >
                      <Maximize2 className="w-3 h-3" />
                    </button>
                  </div>
                </div>
              </div>
            </div>

            {/* RIGHT: Tabbed Export, Watermark & Saved Recordings Controls */}
            <div className="md:col-span-5 flex flex-col min-h-0 bg-ui-panel">
              {/* Inspector Tabs */}
              <div className="grid grid-cols-3 border-b border-ui-subtle bg-ui-header shrink-0">
                <button
                  type="button"
                  onClick={() => setActiveTab('export')}
                  className={`h-9 text-[11px] font-medium flex items-center justify-center gap-1.5 border-b-2 cursor-pointer transition-colors ${
                    activeTab === 'export'
                      ? 'border-ui-accent text-ui-primary bg-ui-panel'
                      : 'border-transparent text-ui-muted hover:text-ui-primary'
                  }`}
                >
                  <SlidersHorizontal className="w-3 h-3" />
                  <span>{t('Export')}</span>
                </button>
                <button
                  type="button"
                  onClick={() => setActiveTab('watermark')}
                  className={`h-9 text-[11px] font-medium flex items-center justify-center gap-1.5 border-b-2 cursor-pointer transition-colors ${
                    activeTab === 'watermark'
                      ? 'border-ui-accent text-ui-primary bg-ui-panel'
                      : 'border-transparent text-ui-muted hover:text-ui-primary'
                  }`}
                >
                  <Stamp className="w-3 h-3" />
                  <span>{t('Watermark')}</span>
                  {watermark.enabled && (
                    <span className="w-1.5 h-1.5 rounded-full bg-ui-accent" />
                  )}
                </button>
                <button
                  type="button"
                  onClick={() => setActiveTab('library')}
                  className={`h-9 text-[11px] font-medium flex items-center justify-center gap-1.5 border-b-2 cursor-pointer transition-colors ${
                    activeTab === 'library'
                      ? 'border-ui-accent text-ui-primary bg-ui-panel'
                      : 'border-transparent text-ui-muted hover:text-ui-primary'
                  }`}
                >
                  <FolderClock className="w-3 h-3" />
                  <span>{t('Library')}</span>
                </button>
              </div>

              <div className="flex-1 overflow-y-auto p-3.5 space-y-3">
                {activeTab === 'export' && (
                  <>
                    {/* FPS & Quality */}
                    <div className="grid grid-cols-2 gap-2.5">
                      <div className="space-y-1">
                        <label className="text-[10px] uppercase tracking-wider text-ui-muted block">
                          FPS
                        </label>
                        <div className="grid grid-cols-3 gap-0.5 bg-ui-input border border-ui-subtle p-0.5 rounded-ui-sm">
                          {FPS_OPTIONS.map((f) => (
                            <button
                              key={f}
                              type="button"
                              disabled={isExporting}
                              onClick={() => setFps(f)}
                              className={`py-1 rounded-ui-xs font-ui-mono tabular-nums text-[10px] cursor-pointer transition-colors ${
                                fps === f
                                  ? 'bg-ui-control-active text-ui-primary font-semibold'
                                  : 'text-ui-muted hover:text-ui-primary'
                              }`}
                            >
                              {f}
                            </button>
                          ))}
                        </div>
                      </div>

                      <div className="space-y-1">
                        <label className="text-[10px] uppercase tracking-wider text-ui-muted block">
                          {t('Quality')}
                        </label>
                        <div className="grid grid-cols-4 gap-0.5 bg-ui-input border border-ui-subtle p-0.5 rounded-ui-sm">
                          {QUALITY_OPTIONS.map((q) => (
                            <button
                              key={q.value}
                              type="button"
                              disabled={isExporting}
                              onClick={() => setQuality(q.value)}
                              className={`py-1 rounded-ui-xs text-[10px] cursor-pointer transition-colors ${
                                quality === q.value
                                  ? 'bg-ui-control-active text-ui-primary font-semibold'
                                  : 'text-ui-muted hover:text-ui-primary'
                              }`}
                            >
                              {t(q.label)}
                            </button>
                          ))}
                        </div>
                      </div>
                    </div>

                    {/* Export Resolution */}
                    <div className="space-y-1">
                      <label className="text-[10px] uppercase tracking-wider text-ui-muted block">
                        {t('Export Resolution')}
                      </label>
                      <div className="grid grid-cols-4 gap-1 bg-ui-input border border-ui-subtle p-0.5 rounded-ui-sm">
                        {EXPORT_RES_OPTIONS.map((res) => (
                          <button
                            key={res.value}
                            type="button"
                            disabled={isExporting}
                            onClick={() => setResolution(res.value)}
                            className={`py-1 rounded-ui-xs font-ui-mono tabular-nums text-[10px] cursor-pointer transition-colors ${
                              resolution === res.value
                                ? 'bg-ui-control-active text-ui-primary font-semibold'
                                : 'text-ui-muted hover:text-ui-primary'
                            }`}
                          >
                            {res.label}
                          </button>
                        ))}
                      </div>
                    </div>

                    {/* Aspect Ratio */}
                    <div className="space-y-1">
                      <label className="text-[10px] uppercase tracking-wider text-ui-muted block">
                        {t('Aspect Ratio')}
                      </label>
                      <div className="grid grid-cols-5 gap-0.5 bg-ui-input border border-ui-subtle p-0.5 rounded-ui-sm">
                        {ASPECT_RATIO_OPTIONS.map((ar) => (
                          <button
                            key={ar.value}
                            type="button"
                            disabled={isExporting}
                            onClick={() => setAspectRatio(ar.value)}
                            className={`py-1 rounded-ui-xs font-ui-mono tabular-nums text-[10px] cursor-pointer transition-colors ${
                              aspectRatio === ar.value
                                ? 'bg-ui-control-active text-ui-primary font-semibold'
                                : 'text-ui-muted hover:text-ui-primary'
                            }`}
                          >
                            {ar.value === 'original' ? t(ar.label) : ar.label}
                          </button>
                        ))}
                      </div>
                    </div>

                    {/* Letterbox Backdrop */}
                    <div className="space-y-1">
                      <label className="text-[10px] uppercase tracking-wider text-ui-muted block">
                        {t('Letterbox Backdrop')}
                      </label>
                      <div className="grid grid-cols-4 gap-1 bg-ui-input border border-ui-subtle p-0.5 rounded-ui-sm">
                        {(
                          [
                            { value: 'white', label: 'White' },
                            { value: 'dark', label: 'Dark' },
                            { value: 'blur', label: 'Blur' },
                            { value: 'custom', label: 'Custom' },
                          ] as const
                        ).map((bg) => (
                          <button
                            key={bg.value}
                            type="button"
                            disabled={isExporting}
                            onClick={() => setBackgroundMode(bg.value)}
                            className={`py-1 rounded-ui-xs text-[10px] cursor-pointer transition-colors ${
                              backgroundMode === bg.value
                                ? 'bg-ui-control-active text-ui-primary font-semibold'
                                : 'text-ui-muted hover:text-ui-primary'
                            }`}
                          >
                            {tc('backdrop', bg.label)}
                          </button>
                        ))}
                      </div>
                      {backgroundMode === 'custom' && (
                        <div className="flex items-center justify-between bg-ui-header border border-ui-subtle rounded-ui-sm px-2.5 py-1 mt-1">
                          <span className="text-[10px] text-ui-muted">{t('Background color')}</span>
                          <div className="flex items-center gap-1.5">
                            <span className="text-[10px] font-ui-mono text-ui-secondary uppercase">
                              {customBgColor}
                            </span>
                            <input
                              type="color"
                              value={customBgColor}
                              disabled={isExporting}
                              onChange={(e) => setCustomBgColor(e.target.value)}
                              className="w-5 h-5 bg-transparent border-0 cursor-pointer"
                            />
                          </div>
                        </div>
                      )}
                    </div>

                    {/* FFmpeg Hardware-Friendly MP4 Toggle */}
                    {ffmpegAvailable && (
                      <div className="flex items-center justify-between bg-ui-header border border-ui-subtle px-2.5 py-2 rounded-ui-sm">
                        <div>
                          <div className="text-[11px] text-ui-primary font-medium">
                            {t('Native FFmpeg (.mp4)')}
                          </div>
                          <div className="text-[10px] text-ui-muted">
                            {t('Fast H.264 encode with watermark & CRF quality')}
                          </div>
                        </div>
                        <ToggleSwitch
                          checked={preferFfmpeg}
                          onChange={setPreferFfmpeg}
                          disabled={isExporting}
                          aria-label={t('Use native FFmpeg encoder')}
                        />
                      </div>
                    )}

                    {/* Quick Watermark Summary Link */}
                    <button
                      type="button"
                      onClick={() => setActiveTab('watermark')}
                      className="w-full flex items-center justify-between bg-ui-header hover:bg-ui-control border border-ui-subtle px-2.5 py-2 rounded-ui-sm text-left cursor-pointer transition-colors"
                    >
                      <div className="flex items-center gap-2 min-w-0">
                        <Stamp className="w-3.5 h-3.5 text-ui-accent shrink-0" />
                        <div className="min-w-0">
                          <div className="text-[11px] text-ui-primary font-medium">{t('Watermark')}</div>
                          <div className="text-[10px] text-ui-muted truncate">
                            {watermark.enabled
                              ? watermark.mode === 'image'
                                ? t('Custom logo enabled')
                                : t('"{text}" · {position}', {
                                    text: watermark.text || t('Text'),
                                    position: td(watermark.position),
                                  })
                              : t('Off — click to add text or logo')}
                          </div>
                        </div>
                      </div>
                      <ChevronRight className="w-3.5 h-3.5 text-ui-muted shrink-0" />
                    </button>
                  </>
                )}

                {activeTab === 'watermark' && (
                  <TimelapseWatermarkControls
                    config={watermark}
                    onChange={handleWatermarkChange}
                    disabled={isExporting}
                    onError={(msg) => setErrorMsg(msg)}
                  />
                )}

                {activeTab === 'library' && (
                  <div className="space-y-2.5">
                    <div className="flex items-center justify-between">
                      <div className="text-[10px] text-ui-muted leading-snug">
                        {t(
                          'Saved locally outside your .ink files so projects stay fast & lightweight.'
                        )}
                      </div>
                      <button
                        type="button"
                        onClick={() => void refreshStoredRecordings()}
                        title={t('Refresh local recordings')}
                        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 cursor-pointer shrink-0"
                      >
                        <RefreshCw
                          className={`w-3 h-3 ${loadingRecordings ? 'animate-spin' : ''}`}
                        />
                      </button>
                    </div>

                    {storedRecordings.length === 0 ? (
                      <div className="py-8 text-center text-[11px] text-ui-muted bg-ui-header/50 rounded-ui-md border border-ui-subtle">
                        {t('No locally stored recordings found yet.')}
                      </div>
                    ) : (
                      <div className="space-y-1.5">
                        {storedRecordings.map((rec) => {
                          const isCurrent = rec.recordingId === stats.recordingId;
                          return (
                            <div
                              key={rec.recordingId}
                              className={`p-2 rounded-ui-md border flex items-center justify-between gap-2 ${
                                isCurrent
                                  ? 'bg-ui-accent-subtle/50 border-ui-accent-border'
                                  : 'bg-ui-header border-ui-subtle'
                              }`}
                            >
                              <div className="min-w-0">
                                <div className="flex items-center gap-1.5">
                                  <span className="text-[11px] font-medium text-ui-primary truncate">
                                    {rec.documentName}
                                  </span>
                                  {isCurrent && (
                                    <span className="px-1 py-0.2 rounded-ui-xs bg-ui-accent text-ui-accent-contrast text-[9px] font-semibold">
                                      {t('Active')}
                                    </span>
                                  )}
                                </div>
                                <div className="text-[10px] font-ui-mono tabular-nums text-ui-muted">
                                  {t('{count} frames', { count: rec.frameCount })} ·{' '}
                                  {formatTimelapseBytes(rec.totalBytes)} ·{' '}
                                  {formatRecordedDate(rec.updatedAt)}
                                </div>
                              </div>
                              <div className="flex items-center gap-1 shrink-0">
                                {!isCurrent && documentId && (
                                  <button
                                    type="button"
                                    disabled={isExporting}
                                    onClick={() => void handleAttachRecording(rec)}
                                    className="px-2 py-1 rounded-ui-xs bg-ui-control hover:bg-ui-control-hover border border-ui-default text-[10px] text-ui-primary cursor-pointer"
                                  >
                                    {t('Load')}
                                  </button>
                                )}
                                <button
                                  type="button"
                                  disabled={isExporting}
                                  onClick={() => void handleDeleteStoredRecording(rec)}
                                  title={t('Delete recording from local storage')}
                                  className="p-1 rounded-ui-xs bg-ui-control hover:bg-ui-danger/15 border border-ui-subtle text-ui-muted hover:text-ui-danger cursor-pointer"
                                >
                                  <Trash2 className="w-3 h-3" />
                                </button>
                              </div>
                            </div>
                          );
                        })}
                      </div>
                    )}
                  </div>
                )}

                {errorMsg && (
                  <div className="text-[11px] text-ui-danger bg-ui-danger/15 border border-ui-danger/40 rounded-ui-sm px-2.5 py-2">
                    {errorMsg}
                  </div>
                )}
              </div>
            </div>
          </div>

          {/* Export Progress Bar */}
          {isExporting && (
            <div className="px-4 py-2 bg-ui-header border-t border-ui-subtle space-y-1 shrink-0">
              <div className="flex items-center justify-between text-[10px] text-ui-muted">
                <span>
                  {t('Encoding {width}×{height} @ {fps} FPS...', {
                    width: player.outputDims.width,
                    height: player.outputDims.height,
                    fps,
                  })}
                </span>
                <span className="font-ui-mono tabular-nums">
                  {Math.round(exportProgress * 100)}%
                </span>
              </div>
              <div className="w-full h-1.5 bg-ui-input border border-ui-subtle rounded-full overflow-hidden">
                <div
                  className="h-full bg-ui-accent transition-all duration-100"
                  style={{ width: `${Math.round(exportProgress * 100)}%` }}
                />
              </div>
            </div>
          )}

          {/* Footer */}
          <div className="px-4 py-2.5 bg-ui-header border-t border-ui-subtle flex flex-wrap items-center justify-between gap-2 shrink-0">
            <div className="text-[10px] font-ui-mono tabular-nums text-ui-muted">
              {t('Output: {width}×{height} · {fps} FPS · {duration}s · {quality} · {format}', {
                width: player.outputDims.width,
                height: player.outputDims.height,
                fps,
                duration: player.totalDurationSec.toFixed(1),
                quality: td(quality, 'timelapseQuality'),
                format: ffmpegAvailable && preferFfmpeg ? 'MP4' : 'WebM',
              })}
            </div>

            <div className="flex items-center gap-2">
              <button
                type="button"
                onClick={onClose}
                disabled={isExporting}
                className="px-3.5 py-1.5 rounded-ui-sm bg-ui-control hover:bg-ui-control-hover border border-ui-default text-ui-primary font-medium transition-colors cursor-pointer disabled:opacity-40"
              >
                {t('Close')}
              </button>
              <button
                type="button"
                disabled={!documentId || stats.frameCount === 0 || isExporting}
                onClick={handleExport}
                className="px-4 py-1.5 rounded-ui-sm bg-ui-accent text-ui-accent-contrast hover:opacity-90 font-medium flex items-center gap-1.5 transition-opacity cursor-pointer disabled:opacity-40"
              >
                {isExporting ? (
                  <>
                    <Loader2 className="w-3.5 h-3.5 animate-spin" />
                    <span>{t('Exporting...')}</span>
                  </>
                ) : (
                  <>
                    <Download className="w-3.5 h-3.5" />
                    <span>{t('Export Video')}</span>
                  </>
                )}
              </button>
            </div>
          </div>
        </div>
      </div>

      {/* Full-Screen Immersive Playback Viewer */}
      <TimelapseFullscreenViewer
        isOpen={isFullscreen}
        onExit={() => setIsFullscreen(false)}
        documentName={cleanDocName}
        canvasRef={player.fullscreenCanvasRef}
        isPlaying={player.isPlaying}
        onTogglePlay={player.togglePlay}
        onStepBy={player.stepBy}
        onRestart={player.restart}
        timelineIndex={player.timelineIndex}
        totalTimelineFrames={player.totalTimelineFrames}
        onSeek={player.seekTo}
        currentTimeSec={player.currentTimeSec}
        totalDurationSec={player.totalDurationSec}
        currentSourceFrameIndex={player.currentSourceFrameIndex}
        totalCapturedFrames={stats.frameCount}
        duration={duration}
        onChangeDuration={setDuration}
        fps={fps}
        outputDims={player.outputDims}
        playbackSpeed={playbackSpeed}
        onCycleSpeed={handleCycleSpeed}
        loop={loop}
        onToggleLoop={() => setLoop((l) => !l)}
      />
    </>
  );
};