File size: 26,910 Bytes
1d8be9a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
"use client";

import Image from "next/image";
import {
  Check,
  CircleHelp,
  Download,
  FileImage,
  Image as ImageIcon,
  LoaderCircle,
  Plus,
  Trash2,
  Upload,
  WandSparkles,
  X,
} from "lucide-react";
import { useEffect, useRef, useState, type ChangeEvent, type DragEvent } from "react";
import { ComparisonViewer } from "@/components/ComparisonViewer";
import { enhanceImage, EnhancementApiError } from "@/lib/api";
import { formatFileSize, validateImageFile } from "@/lib/fileValidation";
import { createImageArchive } from "@/lib/imageArchive";
import type { EnhancementResponse, EnhancementSettings, OutputFormat, UpscaleFactor } from "@/types/enhancement";

const MAX_BATCH_FILES = 10;
const MAX_BATCH_OUTPUT_PIXELS = 64_000_000;
const DEFAULT_SETTINGS: EnhancementSettings = { scale: 4, outputFormat: "png" };

type BatchItemStatus = "queued" | "processing" | "complete" | "failed";

type BatchItem = {
  id: string;
  file: File;
  width: number;
  height: number;
  previewUrl: string;
  resultPreviewUrl: string | null;
  result: EnhancementResponse | null;
  status: BatchItemStatus;
  error: string | null;
};

type BatchEnhancerProps = {
  accessToken: string | null;
  requiresAuth: boolean;
  onBusyChange: (busy: boolean) => void;
};

const formats: { value: OutputFormat; label: string; detail: string }[] = [
  { value: "png", label: "PNG", detail: "Lossless" },
  { value: "jpeg", label: "JPG", detail: "Smaller file" },
  { value: "webp", label: "WEBP", detail: "Modern" },
];

function makeId(): string {
  return globalThis.crypto?.randomUUID?.() ?? `${Date.now()}-${Math.random().toString(36).slice(2)}`;
}

function errorMessage(error: unknown): string {
  return error instanceof EnhancementApiError
    ? error.message
    : "Something went wrong while enhancing this image.";
}

function saveResult(item: BatchItem): void {
  if (!item.result) return;
  const downloadUrl = URL.createObjectURL(item.result.blob);
  const anchor = document.createElement("a");
  anchor.href = downloadUrl;
  anchor.download = item.result.metadata.filename;
  document.body.append(anchor);
  anchor.click();
  anchor.remove();
  window.setTimeout(() => URL.revokeObjectURL(downloadUrl), 1_000);
}

export function BatchEnhancer({ accessToken, requiresAuth, onBusyChange }: BatchEnhancerProps) {
  const [items, setItems] = useState<BatchItem[]>([]);
  const [settings, setSettings] = useState<EnhancementSettings>(DEFAULT_SETTINGS);
  const [selectedItemId, setSelectedItemId] = useState<string | null>(null);
  const [isProcessing, setIsProcessing] = useState(false);
  const [isPackaging, setIsPackaging] = useState(false);
  const [isStopRequested, setIsStopRequested] = useState(false);
  const [isPreviewing, setIsPreviewing] = useState(false);
  const [isDragging, setIsDragging] = useState(false);
  const [progress, setProgress] = useState({ current: 0, total: 0 });
  const [archiveProgress, setArchiveProgress] = useState({ current: 0, total: 0 });
  const [zoomState, setZoomState] = useState<{ itemId: string | null; value: number }>({ itemId: null, value: 1 });
  const [notice, setNotice] = useState<string | null>(null);
  const [requestStatus, setRequestStatus] = useState<string | null>(null);
  const fileInput = useRef<HTMLInputElement>(null);
  const packagingRef = useRef(false);
  const previewingRef = useRef(false);
  const stopAfterCurrentRef = useRef(false);
  const itemsRef = useRef(items);
  const archiveUrlRef = useRef<string | null>(null);
  const archiveUrlTimerRef = useRef<number | null>(null);

  const isBusy = isProcessing || isPackaging || isPreviewing;
  const selected = items.find((item) => item.id === selectedItemId) ?? items[0] ?? null;
  const zoom = zoomState.itemId === selected?.id ? zoomState.value : 1;
  const completedCount = items.filter((item) => item.status === "complete").length;
  const failedCount = items.filter((item) => item.status === "failed").length;
  const pendingCount = items.filter((item) => item.status === "queued" || item.status === "failed").length;
  const expectedOutputPixels = items.reduce((total, item) => total + (item.result
    ? item.result.metadata.enhancedWidth * item.result.metadata.enhancedHeight
    : item.width * item.height * settings.scale * settings.scale), 0);
  const exceedsOutputBudget = expectedOutputPixels > MAX_BATCH_OUTPUT_PIXELS;

  useEffect(() => {
    onBusyChange(isBusy);
  }, [isBusy, onBusyChange]);

  useEffect(() => {
    itemsRef.current = items;
  }, [items]);

  useEffect(() => () => {
    for (const item of itemsRef.current) {
      URL.revokeObjectURL(item.previewUrl);
      if (item.resultPreviewUrl) URL.revokeObjectURL(item.resultPreviewUrl);
    }
    if (archiveUrlTimerRef.current !== null) {
      window.clearTimeout(archiveUrlTimerRef.current);
    }
    if (archiveUrlRef.current) URL.revokeObjectURL(archiveUrlRef.current);
  }, []);

  function releaseArchiveDownload() {
    if (archiveUrlTimerRef.current !== null) {
      window.clearTimeout(archiveUrlTimerRef.current);
      archiveUrlTimerRef.current = null;
    }
    if (archiveUrlRef.current) {
      URL.revokeObjectURL(archiveUrlRef.current);
      archiveUrlRef.current = null;
    }
  }

  function saveArchive(blob: Blob) {
    releaseArchiveDownload();
    const downloadUrl = URL.createObjectURL(blob);
    archiveUrlRef.current = downloadUrl;
    const anchor = document.createElement("a");
    anchor.href = downloadUrl;
    anchor.download = `sharpify-enhanced-${new Date().toISOString().replace(/[:.]/g, "-")}.zip`;
    document.body.append(anchor);
    anchor.click();
    anchor.remove();
    archiveUrlTimerRef.current = window.setTimeout(() => {
      if (archiveUrlRef.current === downloadUrl) archiveUrlRef.current = null;
      archiveUrlTimerRef.current = null;
      URL.revokeObjectURL(downloadUrl);
    }, 60_000);
  }

  async function addFiles(fileList: FileList | File[]) {
    if (isBusy || packagingRef.current || previewingRef.current || isProcessing) return;
    const files = Array.from(fileList);
    if (files.length === 0) return;

    const availableSlots = MAX_BATCH_FILES - items.length;
    if (availableSlots <= 0) {
      setNotice(`A batch can contain up to ${MAX_BATCH_FILES} images. Remove an image before adding more.`);
      return;
    }

    const rejected: string[] = [];
    const additions: BatchItem[] = [];
    let capacityReached = false;
    previewingRef.current = true;
    setIsPreviewing(true);
    onBusyChange(true);
    setNotice(null);

    try {
      for (const file of files) {
        if (additions.length >= availableSlots) {
          capacityReached = true;
          break;
        }

        const validation = validateImageFile(file);
        if (validation) {
          rejected.push(`${file.name || "Selected file"}: ${validation}`);
          continue;
        }

        const previewUrl = URL.createObjectURL(file);
        try {
          const image = new window.Image();
          image.src = previewUrl;
          await image.decode();
          if (image.naturalWidth < 1 || image.naturalHeight < 1) {
            throw new Error("The image has invalid dimensions.");
          }
          additions.push({
            id: makeId(),
            file,
            width: image.naturalWidth,
            height: image.naturalHeight,
            previewUrl,
            resultPreviewUrl: null,
            result: null,
            status: "queued",
            error: null,
          });
        } catch {
          URL.revokeObjectURL(previewUrl);
          rejected.push(`${file.name || "Selected file"}: This image could not be previewed.`);
        }
      }

      if (additions.length > 0) {
        releaseArchiveDownload();
        setItems((current) => [...current, ...additions]);
        setSelectedItemId((current) => current ?? additions[0].id);
      }
      const visibleRejections = rejected.slice(0, capacityReached ? 2 : 3);
      if (capacityReached) {
        visibleRejections.push(`The ${MAX_BATCH_FILES}-image batch limit was reached; some selected images were not added.`);
      }
      setNotice(visibleRejections.length > 0 ? visibleRejections.join(" ") : null);
    } finally {
      previewingRef.current = false;
      setIsPreviewing(false);
      onBusyChange(false);
    }
  }

  async function processQueue() {
    if (isBusy || packagingRef.current || isProcessing || previewingRef.current || pendingCount === 0) return;
    const queue = items.filter((item) => item.status === "queued" || item.status === "failed");
    if (queue.length === 0) return;

    releaseArchiveDownload();
    stopAfterCurrentRef.current = false;
    setIsStopRequested(false);
    setNotice(null);
    setIsProcessing(true);
    setProgress({ current: 0, total: queue.length });
    onBusyChange(true);
    setRequestStatus(null);
    let encounteredFailure = false;
    let stoppedAfterCurrent = false;
    let requiresSignIn = false;

    try {
      for (const [index, item] of queue.entries()) {
        if (stopAfterCurrentRef.current) {
          stoppedAfterCurrent = true;
          break;
        }

        setProgress({ current: index + 1, total: queue.length });
        setSelectedItemId(item.id);
        setItems((current) => current.map((candidate) => candidate.id === item.id
          ? { ...candidate, status: "processing", error: null }
          : candidate));

        try {
          const result = await enhanceImage(item.file, settings, {
            width: item.width,
            height: item.height,
          }, accessToken, (requestProgress) => {
            if (requestProgress.stage === "queued") {
              setRequestStatus(requestProgress.position
                ? `Waiting in shared GPU queue · position ${requestProgress.position}`
                : "Waiting for the shared GPU queue…");
            } else if (requestProgress.stage === "working") {
              setRequestStatus("Enhancing with Real-ESRGAN…");
            }
          });
          const resultPreviewUrl = URL.createObjectURL(result.blob);
          setItems((current) => current.map((candidate) => candidate.id === item.id
            ? { ...candidate, result, resultPreviewUrl, status: "complete", error: null }
            : candidate));
        } catch (error) {
          encounteredFailure = true;
          setItems((current) => current.map((candidate) => candidate.id === item.id
            ? { ...candidate, status: "failed", error: errorMessage(error) }
            : candidate));
          if (error instanceof EnhancementApiError && ["auth_required", "unauthorized"].includes(error.code ?? "")) {
            requiresSignIn = true;
            stoppedAfterCurrent = true;
            break;
          }
        }

        if (stopAfterCurrentRef.current) {
          stoppedAfterCurrent = encounteredFailure || index < queue.length - 1;
          break;
        }

        if (index < queue.length - 1) {
          await new Promise<void>((resolve) => window.setTimeout(resolve, 0));
        }
      }
    } finally {
      setIsProcessing(false);
      setIsStopRequested(false);
      stopAfterCurrentRef.current = false;
      setRequestStatus(null);
      onBusyChange(false);
      if (requiresSignIn) {
        setNotice("Your Hugging Face sign-in expired. Sign in again, then retry the unfinished images.");
      } else if (stoppedAfterCurrent) {
        setNotice("Batch paused after the current image. Unfinished images remain available to continue or retry.");
      } else if (encounteredFailure) {
        setNotice("Some images could not be enhanced. Their individual errors are shown in the queue; run the batch again to retry them.");
      }
    }
  }

  async function downloadCompletedImages() {
    if (isBusy || packagingRef.current) return;
    const completed = items.filter((item) => item.status === "complete" && item.result);
    if (completed.length === 0) return;

    packagingRef.current = true;
    setNotice(null);
    setArchiveProgress({ current: 0, total: completed.length });
    setIsPackaging(true);
    onBusyChange(true);

    try {
      const archive = await createImageArchive(
        completed.map((item) => ({ filename: item.result!.metadata.filename, blob: item.result!.blob })),
        (current, total) => setArchiveProgress({ current, total }),
      );
      saveArchive(archive);
    } catch {
      setNotice("The ZIP could not be prepared. You can still download each completed image individually.");
    } finally {
      packagingRef.current = false;
      setIsPackaging(false);
      onBusyChange(false);
    }
  }

  function requestStopAfterCurrent() {
    if (!isProcessing || isStopRequested) return;
    stopAfterCurrentRef.current = true;
    setIsStopRequested(true);
  }

  function removeItem(id: string) {
    if (isBusy || packagingRef.current) return;
    const item = items.find((candidate) => candidate.id === id);
    if (!item) return;
    releaseArchiveDownload();
    URL.revokeObjectURL(item.previewUrl);
    if (item.resultPreviewUrl) URL.revokeObjectURL(item.resultPreviewUrl);
    const remaining = items.filter((candidate) => candidate.id !== id);
    setItems(remaining);
    if (selectedItemId === id) setSelectedItemId(remaining[0]?.id ?? null);
    if (fileInput.current) fileInput.current.value = "";
  }

  function clearBatch() {
    if (isBusy || packagingRef.current) return;
    releaseArchiveDownload();
    for (const item of items) {
      URL.revokeObjectURL(item.previewUrl);
      if (item.resultPreviewUrl) URL.revokeObjectURL(item.resultPreviewUrl);
    }
    setItems([]);
    setSelectedItemId(null);
    setNotice(null);
    if (fileInput.current) fileInput.current.value = "";
  }

  function handleInputChange(event: ChangeEvent<HTMLInputElement>) {
    const files = Array.from(event.currentTarget.files ?? []);
    event.currentTarget.value = "";
    if (files.length > 0) void addFiles(files);
  }

  function handleDrop(event: DragEvent<HTMLDivElement>) {
    event.preventDefault();
    setIsDragging(false);
    if (event.dataTransfer.files.length > 0) void addFiles(event.dataTransfer.files);
  }

  function changeSetting<K extends keyof EnhancementSettings>(key: K, value: EnhancementSettings[K]) {
    setSettings((current) => ({ ...current, [key]: value }));
  }

  function changeZoom(value: number) {
    if (selected) setZoomState({ itemId: selected.id, value });
  }

  const selectedResult = selected?.result ?? null;

  return (
    <div
      className={`studio-layout batch-layout${isDragging ? " is-dragging" : ""}`}
      onDragEnter={(event) => {
        if (event.dataTransfer.types.includes("Files")) setIsDragging(true);
      }}
      onDragOver={(event) => {
        if (event.dataTransfer.types.includes("Files")) event.preventDefault();
      }}
      onDragLeave={(event) => {
        if (!event.currentTarget.contains(event.relatedTarget as Node | null)) setIsDragging(false);
      }}
      onDrop={handleDrop}
    >
      <input
        ref={fileInput}
        aria-label="Choose images for batch enhancement"
        className="visually-hidden-input"
        accept="image/jpeg,image/png,image/webp,.jpg,.jpeg,.png,.webp"
        disabled={isBusy}
        multiple
        onChange={handleInputChange}
        type="file"
      />

      <section className="image-workspace" aria-label="Batch image workspace">
        <div className="workspace-toolbar">
          <div className="workspace-status">
            <span className={items.length > 0 ? "status-dot" : "status-dot status-dot-muted"} />
            {isProcessing
              ? `PROCESSING ${progress.current} / ${progress.total}`
              : items.length > 0
                ? `${completedCount} OF ${items.length} COMPLETE`
                : "BATCH QUEUE"}
          </div>
          <div className="workspace-actions">
            <span className="local-badge"><ImageIcon size={13} /> UP TO {MAX_BATCH_FILES} IMAGES</span>
            <button className="text-button" onClick={() => fileInput.current?.click()} type="button" disabled={isBusy || items.length >= MAX_BATCH_FILES}>
              <Plus size={14} /> Add images
            </button>
            {items.length > 0 && (
              <button className="icon-button" aria-label="Clear batch" onClick={clearBatch} type="button" disabled={isBusy}>
                <Trash2 size={14} />
              </button>
            )}
          </div>
        </div>

        <div className="image-stage batch-image-stage">
          {selected && selectedResult && selected.resultPreviewUrl ? (
            <ComparisonViewer
              key={selected.id}
              afterUrl={selected.resultPreviewUrl}
              beforeUrl={selected.previewUrl}
              metadata={selectedResult.metadata}
              onZoomChange={changeZoom}
              zoom={zoom}
            />
          ) : selected ? (
            <div className="original-preview">
              <div className="original-preview-image">
                <Image src={selected.previewUrl} alt={`Original image: ${selected.file.name}`} fill sizes="(max-width: 960px) 100vw, 65vw" unoptimized />
                <span className="comparison-label label-before">ORIGINAL</span>
              </div>
              <div className="original-file-card">
                <span className="file-card-icon"><ImageIcon size={16} /></span>
                <span className="file-card-name"><strong>{selected.file.name}</strong><small>{selected.width.toLocaleString()} × {selected.height.toLocaleString()} px · {formatFileSize(selected.file.size)}</small></span>
                <span className="file-card-ready">{selected.status === "processing" ? "WORKING" : selected.status === "failed" ? "FAILED" : "QUEUED"}</span>
              </div>
            </div>
          ) : (
            <div className={`batch-dropzone${isDragging ? " is-dragging" : ""}`}>
              <div className="upload-icon-wrap"><FileImage size={24} strokeWidth={1.6} /></div>
              <p className="upload-kicker">PROCESS A SMALL SET TOGETHER</p>
              <h3>Add images to your batch</h3>
              <p className="upload-description">Choose up to {MAX_BATCH_FILES} JPG, PNG, or WEBP images. Each image is enhanced in sequence.</p>
              <button className="button button-dark upload-button" type="button" onClick={() => fileInput.current?.click()} disabled={isBusy}>
                <Upload size={17} /> Choose images
              </button>
              <div className="upload-file-types"><span>JPG</span><span>PNG</span><span>WEBP</span><i /> <span>20 MB each</span></div>
              <div className="upload-privacy"><Check size={14} /> Images stay in this session and are not permanently stored.</div>
              {isDragging && <div className="drop-overlay"><FileImage size={19} /> Drop images to add them</div>}
            </div>
          )}
        </div>

        {selectedResult && (
          <div className="result-file-row">
            <div className="result-file-label"><span className="result-check"><Check size={13} /></span><span><strong>{selectedResult.metadata.filename}</strong><small>{formatFileSize(selectedResult.blob.size)} · Full-resolution output</small></span></div>
            <button className="text-button result-start-over" type="button" onClick={() => selected && saveResult(selected)}><Download size={14} /> Download</button>
          </div>
        )}

        {items.length > 0 && (
          <div className="batch-queue-section">
            <div className="batch-queue-heading"><strong>Image queue</strong><span>{completedCount} complete · {pendingCount} remaining</span></div>
            {completedCount > 0 && (
              <div className="batch-archive-row">
                <button className="text-button batch-archive-button" onClick={() => void downloadCompletedImages()} type="button" disabled={isBusy}>
                  {isPackaging ? <LoaderCircle className="spin" size={14} /> : <Download size={14} />}
                  <span aria-live="polite">{isPackaging
                    ? `Preparing ZIP · ${archiveProgress.current} of ${archiveProgress.total} images`
                    : `Download ${completedCount} completed ${completedCount === 1 ? "image" : "images"} as ZIP`}</span>
                </button>
              </div>
            )}
            {isProcessing && (
              <div className="batch-progress">
                <div className="batch-progress-status" role="status" aria-live="polite">
                  <LoaderCircle className="spin" size={15} />
                  <span>{requestStatus || `Enhancing image ${progress.current} of ${progress.total}. Images run one at a time to protect available memory.`}</span>
                </div>
                <button className="batch-progress-stop" onClick={requestStopAfterCurrent} type="button" disabled={isStopRequested}>
                  {isStopRequested ? "Stopping…" : "Stop after this image"}
                </button>
              </div>
            )}
            <ul className="batch-queue-list" aria-label="Batch enhancement progress">
              {items.map((item) => (
                <li className={`batch-queue-item${selected?.id === item.id ? " is-selected" : ""}`} key={item.id}>
                  <button
                    aria-pressed={selected?.id === item.id}
                    className="batch-queue-select"
                    onClick={() => setSelectedItemId(item.id)}
                    type="button"
                  >
                    <span className="batch-thumbnail"><Image src={item.previewUrl} alt="" fill sizes="52px" unoptimized /></span>
                    <span className="batch-file-copy"><strong title={item.file.name}>{item.file.name}</strong><small>{formatFileSize(item.file.size)} · {item.width.toLocaleString()} × {item.height.toLocaleString()}</small></span>
                    <span className={`batch-status batch-status-${item.status}`}>
                      {item.status === "processing" && <LoaderCircle className="spin" size={11} />}
                      {item.status === "queued" ? "QUEUED" : item.status === "processing" ? "WORKING" : item.status === "complete" ? "DONE" : "FAILED"}
                    </span>
                  </button>
                  {item.error && <p className="batch-item-error">{item.error}</p>}
                  <div className="batch-item-actions">
                    {item.result && (
                      <button aria-label={`Download ${item.result.metadata.filename}`} className="icon-button" onClick={() => saveResult(item)} type="button">
                        <Download size={14} />
                      </button>
                    )}
                    <button aria-label={`Remove ${item.file.name}`} className="icon-button batch-remove-button" onClick={() => removeItem(item.id)} type="button" disabled={isBusy}>
                      <X size={13} />
                    </button>
                  </div>
                </li>
              ))}
            </ul>
          </div>
        )}

        {notice && (
          <div className="error-notice" role="alert"><span className="error-mark">!</span><span>{notice}</span><button aria-label="Dismiss message" onClick={() => setNotice(null)} type="button"><X size={14} /></button></div>
        )}
      </section>

      <aside className="settings-panel" aria-label="Batch enhancement settings">
        <div className="settings-heading">
          <div><p className="section-kicker">ONE SET OF SETTINGS</p><h3>Batch settings</h3></div>
          <span className="settings-step">02 <span>/ 02</span></span>
        </div>

        <fieldset className="settings-field" disabled={isBusy}>
          <legend>Upscale size</legend>
          <p className="field-caption">Applied to every image in the next run.</p>
          <div className="scale-options" role="group" aria-label="Batch upscale factor">
            {([2, 4] as const).map((scale: UpscaleFactor) => (
              <button aria-pressed={settings.scale === scale} className={`scale-option${settings.scale === scale ? " is-selected" : ""}`} key={scale} onClick={() => changeSetting("scale", scale)} type="button">
                <span className="scale-option-top">{scale}×</span><span className="scale-option-bottom">{scale === 2 ? "Balanced" : "Maximum detail"}</span>
                {settings.scale === scale && <span className="selected-mark"><Check size={11} /></span>}
              </button>
            ))}
          </div>
        </fieldset>

        <fieldset className="settings-field format-field" disabled={isBusy}>
          <legend>Save format</legend>
          <p className="field-caption">Choose one output format for this run.</p>
          <div className="format-options" role="group" aria-label="Batch output image format">
            {formats.map((format) => (
              <button aria-pressed={settings.outputFormat === format.value} className={`format-option${settings.outputFormat === format.value ? " is-selected" : ""}`} key={format.value} onClick={() => changeSetting("outputFormat", format.value)} type="button">
                <span className="format-label">{format.label}</span><span className="format-detail">{format.detail}</span>
              </button>
            ))}
          </div>
        </fieldset>

        <div className="batch-settings-summary">
          <strong>{items.length} / {MAX_BATCH_FILES} images</strong>
          <span>{completedCount} enhanced{failedCount > 0 ? ` · ${failedCount} failed` : ""}</span>
        </div>
        <p className={`batch-output-budget${exceedsOutputBudget ? " is-over-limit" : ""}`}>
          Batch output budget: {Math.ceil(expectedOutputPixels / 1_000_000)}M / {MAX_BATCH_OUTPUT_PIXELS / 1_000_000}M pixels
        </p>

        <button className="button button-dark enhance-button" type="button" onClick={() => void processQueue()} disabled={items.length === 0 || pendingCount === 0 || isBusy || exceedsOutputBudget || (requiresAuth && !accessToken)}>
          {isBusy ? <LoaderCircle className="spin" size={17} /> : <WandSparkles size={17} />}
          {isPreviewing ? "Preparing images…" : isProcessing ? "Enhancing batch…" : requiresAuth && !accessToken ? "Sign in to enhance" : exceedsOutputBudget ? "Reduce batch output size" : pendingCount > 0 ? `${failedCount > 0 ? "Retry and enhance" : "Enhance"} ${pendingCount} image${pendingCount === 1 ? "" : "s"}` : "Batch complete"}
        </button>
        <p className="settings-footnote"><CircleHelp size={13} /> Images run sequentially. A failed image won’t stop the rest.</p>
        <p className="batch-memory-note">For stability, a batch is limited to 64 million total output pixels. Remove images or lower the upscale to stay within the limit. Completed files stay in this browser tab until removed or cleared.</p>
      </aside>
    </div>
  );
}