Spaces:
Sleeping

File size: 16,892 Bytes
7d751ef
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
import { useEffect, useState, useRef } from "react";
import type { FileEntry } from "../types";
import { api } from "../api";
import { fmt } from "../utils";

interface MergeItem { uid: string; file: FileEntry; }

// ─── MergeModal ──────────────────────────────────────────────────────────────
export function MergeModal({ files, onClose, onMergeStarted }: {
  files: FileEntry[];
  onClose: () => void;
  onMergeStarted: () => void;
}) {
  const [items, setItems] = useState<MergeItem[]>(() =>
    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<string | null>(null);
  const dragUid = useRef<string | null>(null);
  const dragOverUid = useRef<string | null>(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 (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/40 backdrop-blur-sm" onClick={onClose}>
      <div className="bg-white rounded-2xl shadow-2xl w-full max-w-lg max-h-[90vh] flex flex-col" onClick={(e) => e.stopPropagation()}>
        <div className="flex items-center justify-between px-5 py-4 border-b border-slate-100 flex-shrink-0">
          <div className="flex items-center gap-2">
            <span className="text-lg">πŸ”—</span>
            <h2 className="text-sm font-bold text-slate-800">Merge Files</h2>
            <span className="rounded-full bg-violet-100 px-2 py-0.5 text-xs font-semibold text-violet-700">{items.length} files</span>
          </div>
          <button onClick={onClose} className="rounded-lg p-1.5 text-slate-400 hover:bg-slate-100 hover:text-slate-600 transition-colors">
            <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
              <path strokeLinecap="round" strokeLinejoin="round" d="M6 18 18 6M6 6l12 12" />
            </svg>
          </button>
        </div>
        <div className="flex-1 overflow-y-auto p-5 space-y-3">
          <div className="text-[11px] text-slate-400 bg-slate-50 rounded-lg px-3 py-2">
            Drag rows or use ↑↓ to set order. Files joined topβ†’bottom via stream copy (lossless, instant).
          </div>
          <div className="rounded-xl border border-slate-200 bg-white overflow-hidden divide-y divide-slate-100">
            {items.map((item, idx) => (
              <div key={item.uid} draggable onDragStart={() => 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">
                <svg className="h-4 w-4 flex-shrink-0 text-slate-300" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                  <path strokeLinecap="round" strokeLinejoin="round" d="M3.75 9h16.5m-16.5 6.75h16.5" />
                </svg>
                <span className="flex h-6 w-6 items-center justify-center rounded-full bg-violet-100 text-[11px] font-bold text-violet-700 flex-shrink-0">{idx + 1}</span>
                <div className="flex-1 min-w-0">
                  <p className="truncate text-sm font-medium text-slate-800" title={item.file.name}>{item.file.name}</p>
                  <p className="text-[10px] text-slate-400">{fmt(item.file.sizeBytes)} Β· {item.file.folder}</p>
                </div>
                <div className="flex items-center gap-1 flex-shrink-0">
                  <button onClick={() => moveUp(idx)} disabled={idx === 0}
                    className="rounded p-1 text-slate-400 hover:bg-slate-100 hover:text-slate-600 disabled:opacity-30 disabled:cursor-not-allowed">
                    <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                      <path strokeLinecap="round" strokeLinejoin="round" d="m4.5 15.75 7.5-7.5 7.5 7.5" />
                    </svg>
                  </button>
                  <button onClick={() => moveDown(idx)} disabled={idx === items.length - 1}
                    className="rounded p-1 text-slate-400 hover:bg-slate-100 hover:text-slate-600 disabled:opacity-30 disabled:cursor-not-allowed">
                    <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                      <path strokeLinecap="round" strokeLinejoin="round" d="m19.5 8.25-7.5 7.5-7.5-7.5" />
                    </svg>
                  </button>
                  {items.length > 2 && (
                    <button onClick={() => removeItem(item.uid)}
                      className="rounded p-1 text-red-400 hover:bg-red-50 hover:text-red-600">
                      <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                        <path strokeLinecap="round" strokeLinejoin="round" d="M6 18 18 6M6 6l12 12" />
                      </svg>
                    </button>
                  )}
                </div>
              </div>
            ))}
          </div>
          <div className="space-y-1">
            <label className="text-xs font-semibold uppercase tracking-wider text-slate-500">Output Filename</label>
            <input type="text" value={outName} onChange={(e) => 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" />
          </div>
          {error && <p className="text-xs text-red-500">{error}</p>}
          <div className="text-xs text-slate-400 bg-slate-50 rounded-lg px-3 py-2">
            πŸ’‘ Output saved to same folder as the first selected file. Stream copy = instant, lossless.
          </div>
        </div>
        <div className="px-5 pb-5 flex-shrink-0">
          <button onClick={handleMerge} disabled={busy || items.length < 2 || !outName.trim()}
            className="w-full rounded-xl bg-violet-600 py-2.5 text-sm font-semibold text-white transition-colors hover:bg-violet-700 disabled:opacity-50">
            {busy ? "Starting Merge…" : `πŸ”— Merge ${items.length} Files`}
          </button>
        </div>
      </div>
    </div>
  );
}

// ─── 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<string | null>(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 (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/40 backdrop-blur-sm" onClick={onClose}>
      <div className="bg-white rounded-2xl shadow-2xl w-full max-w-sm" onClick={(e) => e.stopPropagation()}>
        <div className="flex items-center justify-between px-5 py-4 border-b border-slate-100">
          <div className="flex items-center gap-2 min-w-0">
            <span className="text-lg flex-shrink-0">↗️</span>
            <div className="min-w-0">
              <h2 className="text-sm font-bold text-slate-800">Move {itemCount === 1 ? "File" : `${itemCount} Files`}</h2>
              <p className="text-[10px] text-slate-400 truncate">
                {itemCount === 1 ? files[0].name : `${itemCount} selected files`}
              </p>
            </div>
          </div>
          <button onClick={onClose} className="flex-shrink-0 rounded-lg p-1.5 text-slate-400 hover:bg-slate-100 hover:text-slate-600">
            <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
              <path strokeLinecap="round" strokeLinejoin="round" d="M6 18 18 6M6 6l12 12" />
            </svg>
          </button>
        </div>
        <div className="p-4 space-y-2">
          <p className="text-xs text-slate-500 mb-3">Select destination folder:</p>
          {error && <p className="text-xs text-red-500 mb-2">{error}</p>}
          <div className="rounded-xl border border-slate-200 overflow-hidden divide-y divide-slate-100 max-h-64 overflow-y-auto">
            {allFolders.map((folder) => {
              const isCurrent = files.every((f) => (f.folder || "/") === folder);
              return (
                <button key={folder} onClick={() => !busy && handleMove(folder)} disabled={busy || isCurrent}
                  className={`w-full flex items-center gap-3 px-4 py-3 text-left transition-colors ${
                    isCurrent ? "bg-violet-50 cursor-not-allowed" : "hover:bg-slate-50"
                  }`}>
                  <svg className={`h-4 w-4 flex-shrink-0 ${isCurrent ? "text-violet-500" : "text-amber-500"}`} fill="currentColor" viewBox="0 0 24 24">
                    <path d="M19.5 21a3 3 0 0 0 3-3v-4.5a3 3 0 0 0-3-3h-15a3 3 0 0 0-3 3V18a3 3 0 0 0 3 3h15ZM1.5 10.146V6a3 3 0 0 1 3-3h5.379a2.25 2.25 0 0 1 1.59.659l2.122 2.121c.14.141.331.22.53.22H19.5a3 3 0 0 1 3 3v1.146A4.483 4.483 0 0 0 19.5 12h-15a4.483 4.483 0 0 0-3 1.146V10.146Z" />
                  </svg>
                  <span className={`text-sm font-medium flex-1 truncate ${isCurrent ? "text-violet-700" : "text-slate-700"}`}>
                    {folder === "/" ? "/ (root)" : folder}
                  </span>
                  {isCurrent && (
                    <span className="text-[10px] text-violet-500 font-semibold flex-shrink-0">current</span>
                  )}
                </button>
              );
            })}
          </div>
          {busy && <p className="text-xs text-slate-400 text-center">Moving…</p>}
        </div>
      </div>
    </div>
  );
}

// ─── 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<string | null>(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 (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/40 backdrop-blur-sm" onClick={onClose}>
      <div className="bg-white rounded-2xl shadow-2xl w-full max-w-xs" onClick={(e) => e.stopPropagation()}>
        <div className="flex items-center justify-between px-5 py-4 border-b border-slate-100">
          <div className="flex items-center gap-2">
            <span className="text-lg">πŸ“</span>
            <h2 className="text-sm font-bold text-slate-800">New Folder</h2>
          </div>
          <button onClick={onClose} className="rounded-lg p-1.5 text-slate-400 hover:bg-slate-100 hover:text-slate-600">
            <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
              <path strokeLinecap="round" strokeLinejoin="round" d="M6 18 18 6M6 6l12 12" />
            </svg>
          </button>
        </div>
        <div className="p-5 space-y-4">
          <input autoFocus type="text" placeholder="Folder name…" value={name}
            onChange={(e) => 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 && <p className="text-xs text-red-500">{error}</p>}
          <button onClick={handleCreate} disabled={busy || !name.trim()}
            className="w-full rounded-xl bg-violet-600 py-2.5 text-sm font-semibold text-white hover:bg-violet-700 disabled:opacity-50 transition-colors">
            {busy ? "Creating…" : "Create Folder"}
          </button>
        </div>
      </div>
    </div>
  );
}

// ─── PreviewModal ────────────────────────────────────────────────────────────
export function PreviewModal({ title, url, onClose }: { title: string; url: string; onClose: () => void }) {
  return (
    <div className="fixed inset-0 z-[60] flex items-center justify-center bg-black/70 backdrop-blur-sm p-4" onClick={onClose}>
      <div className="bg-white rounded-2xl shadow-2xl w-full max-w-4xl" onClick={(e) => e.stopPropagation()}>
        <div className="flex items-center justify-between px-5 py-3 border-b border-slate-100">
          <h2 className="text-sm font-bold text-slate-800 truncate pr-2">{title}</h2>
          <button onClick={onClose} className="rounded-lg p-1.5 text-slate-400 hover:bg-slate-100 hover:text-slate-600">
            <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
              <path strokeLinecap="round" strokeLinejoin="round" d="M6 18 18 6M6 6l12 12" />
            </svg>
          </button>
        </div>
        <div className="p-2">
          <img src={url} alt={title} className="w-full rounded-xl max-h-[80vh] object-contain" />
        </div>
      </div>
    </div>
  );
}