import { useEffect, useState, useRef } from "react"; import type { FileEntry } from "../types"; import { api } from "../api"; import { fmt } from "../utils"; import { extractStorageCredentials, exportCredentialsToFile, importCredentialsFromFile, mergeCredentialsIntoSettings } from "../utils/credentials"; interface MergeItem { uid: string; file: FileEntry; } // ─── MergeModal ────────────────────────────────────────────────────────────── export function MergeModal({ files, onClose, onMergeStarted }: { files: FileEntry[]; onClose: () => void; onMergeStarted: () => void; }) { const [items, setItems] = useState(() => files.map((f) => ({ uid: `$${f.id}_$${Math.random().toString(16).slice(2)}`, file: f })) ); const [outName, setOutName] = useState(""); const [busy, setBusy] = useState(false); const [error, setError] = useState(null); const dragUid = useRef(null); const dragOverUid = useRef(null); useEffect(() => { const firstFile = files[0]; if (!firstFile) { setOutName("merged_output.mkv"); return; } const name = firstFile.name; const lastDotIndex = name.lastIndexOf("."); if (lastDotIndex > 0) { const baseName = name.slice(0, lastDotIndex); const ext = name.slice(lastDotIndex); setOutName(`$${baseName}_merged$${ext}`); } else { setOutName(`${name}_merged.mkv`); } }, [files]); const moveUp = (idx: number) => { if (idx === 0) return; const next = [...items]; [next[idx - 1], next[idx]] = [next[idx], next[idx - 1]]; setItems(next); }; const moveDown = (idx: number) => { if (idx === items.length - 1) return; const next = [...items]; [next[idx], next[idx + 1]] = [next[idx + 1], next[idx]]; setItems(next); }; const handleDragStart = (uid: string) => { dragUid.current = uid; }; const handleDragOver = (e: React.DragEvent, uid: string) => { e.preventDefault(); dragOverUid.current = uid; }; const handleDrop = () => { if (!dragUid.current || !dragOverUid.current || dragUid.current === dragOverUid.current) return; const from = items.findIndex((i) => i.uid === dragUid.current); const to = items.findIndex((i) => i.uid === dragOverUid.current); if (from === -1 || to === -1) return; const next = [...items]; const [moved] = next.splice(from, 1); next.splice(to, 0, moved); setItems(next); dragUid.current = null; dragOverUid.current = null; }; const removeItem = (uid: string) => setItems((prev) => prev.filter((i) => i.uid !== uid)); const handleMerge = async () => { if (items.length < 2) { setError("Need at least 2 files to merge"); return; } if (!outName.trim()) { setError("Output filename is required"); return; } setError(null); setBusy(true); try { const r = await fetch("/api/merge", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ fileIds: items.map((i) => i.file.id), outputFilename: outName.trim() }), }); const data = await r.json(); if (data.error) { setError(data.error); setBusy(false); return; } onMergeStarted(); onClose(); } catch { setError("Failed to start merge"); setBusy(false); } }; return (
e.stopPropagation()}>
🔗

Merge Files

{items.length} files
Drag rows or use ↑↓ to set order. Files joined top→bottom via stream copy (lossless, instant).
{items.map((item, idx) => (
handleDragStart(item.uid)} onDragOver={(e) => handleDragOver(e, item.uid)} onDrop={handleDrop} className="flex items-center gap-3 px-4 py-3 hover:bg-slate-50 cursor-grab active:cursor-grabbing transition-colors"> {idx + 1}

{item.file.name}

{fmt(item.file.sizeBytes)} · {item.file.folder}

{items.length > 2 && ( )}
))}
setOutName(e.target.value)} className="w-full rounded-lg border border-slate-200 px-3 py-2 text-sm focus:border-violet-400 focus:outline-none focus:ring-2 focus:ring-violet-100" />
{error &&

{error}

}
💡 Output saved to same folder as the first selected file. Stream copy = instant, lossless.
); } // ─── MoveModal ─────────────────────────────────────────────────────────────── export function MoveModal({ files, folders, onClose, onMoved }: { files: FileEntry[]; folders: string[]; onClose: () => void; onMoved: () => void; }) { const [busy, setBusy] = useState(false); const [error, setError] = useState(null); const itemCount = files.length; const handleMove = async (targetFolder: string) => { if (files.every((f) => (f.folder || "/") === targetFolder)) { onClose(); return; } setBusy(true); setError(null); try { const ids = files.map((f) => f.id); const data = await api.batchMove(ids, targetFolder); if (data.error) { setError(data.error); setBusy(false); return; } onMoved(); onClose(); } catch { setError("Failed to move file(s)"); setBusy(false); } }; const allFolders = Array.from(new Set(["/", ...folders])).sort((a, b) => { if (a === "/") return -1; if (b === "/") return 1; return a.localeCompare(b); }); return (
e.stopPropagation()}>
↗️

Move {itemCount === 1 ? "File" : `${itemCount} Files`}

{itemCount === 1 ? files[0].name : `${itemCount} selected files`}

Select destination folder:

{error &&

{error}

}
{allFolders.map((folder) => { const isCurrent = files.every((f) => (f.folder || "/") === folder); return ( ); })}
{busy &&

Moving…

}
); } // ─── CreateFolderModal ─────────────────────────────────────────────────────── export function CreateFolderModal({ onClose, onCreated }: { onClose: () => void; onCreated: (name: string) => void }) { const [name, setName] = useState(""); const [busy, setBusy] = useState(false); const [error, setError] = useState(null); const handleCreate = async () => { const trimmed = name.trim(); if (!trimmed) { setError("Folder name is required"); return; } setBusy(true); setError(null); try { const data = await api.createFolder(trimmed); if (data.error) { setError(data.error); setBusy(false); return; } onCreated(data.folder ?? `/${trimmed}`); onClose(); } catch { setError("Failed to create folder"); setBusy(false); } }; return (
e.stopPropagation()}>
📁

New Folder

setName(e.target.value)} onKeyDown={(e) => { if (e.key === "Enter") handleCreate(); if (e.key === "Escape") onClose(); }} className="w-full rounded-lg border border-slate-200 px-3 py-2 text-sm focus:border-violet-400 focus:outline-none focus:ring-2 focus:ring-violet-100" /> {error &&

{error}

}
); } // ─── PreviewModal ──────────────────────────────────────────────────────────── export function PreviewModal({ title, url, onClose }: { title: string; url: string; onClose: () => void }) { return (
e.stopPropagation()}>

{title}

{title}
); } // ─── CredentialsModal ────────────────────────────────────────────────────────── export function CredentialsModal({ settings, onClose, onSettingsUpdated }: { settings: any; onClose: () => void; onSettingsUpdated: (newSettings: any) => void; }) { const [busy, setBusy] = useState(false); const [error, setError] = useState(null); const [success, setSuccess] = useState(null); const [importFile, setImportFile] = useState(null); const fileInputRef = useRef(null); const handleExport = () => { try { const credentials = extractStorageCredentials(settings); exportCredentialsToFile(credentials, 'storage_credentials.json'); setSuccess('Credentials exported successfully!'); setTimeout(() => setSuccess(null), 3000); } catch (err) { setError('Failed to export credentials'); console.error('Export error:', err); } }; const handleImportFileChange = (e: React.ChangeEvent) => { const file = e.target.files?.[0]; if (file) { setImportFile(file); setError(null); setSuccess(null); } }; const handleImport = async () => { if (!importFile) return; setBusy(true); setError(null); setSuccess(null); try { const importedCredentials = await importCredentialsFromFile(importFile); const mergedSettings = mergeCredentialsIntoSettings(settings, importedCredentials); // Save the merged settings const response = await fetch('/api/settings', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(mergedSettings) }); if (!response.ok) { throw new Error('Failed to save settings'); } setSuccess('Credentials imported successfully!'); onSettingsUpdated(mergedSettings); setTimeout(() => { setSuccess(null); onClose(); }, 2000); } catch (err) { setError(err instanceof Error ? err.message : 'Failed to import credentials'); console.error('Import error:', err); } finally { setBusy(false); setImportFile(null); if (fileInputRef.current) { fileInputRef.current.value = ''; } } }; const handleCancelImport = () => { setImportFile(null); setError(null); setSuccess(null); if (fileInputRef.current) { fileInputRef.current.value = ''; } }; const credentials = extractStorageCredentials(settings); return (
e.stopPropagation()}>
🔑

Storage Credentials Manager

Export Credentials

Download your storage credentials to import into another instance.

Import Credentials

Upload a credentials file to import storage settings.

{!importFile ? ( ) : (
📄 {importFile.name}
)}
{error && (

❌ {error}

)} {success && (

✅ {success}

)}

Credentials Summary

B2 Connections: {credentials.b2SavedConnections?.length || 0}
Remote URLs: {credentials.remoteUrlHistory?.length || 0}
Per-remote creds: {credentials.remoteCredentials ? Object.keys(credentials.remoteCredentials).length : 0}
Current Remote: {credentials.remoteUrl || 'None'}
Legacy HF Token: {credentials.remoteHfToken ? '✓ Set' : 'Not set'}
); }