File size: 26,909 Bytes
b2c1b6b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
/* =========================================================
   Watermark Remover β€” Frontend Logic
   ========================================================= */

"use strict";

// ── State ─────────────────────────────────────────────────

const state = {
  fileId:      null,
  ext:         null,
  isVideo:     false,
  method:      "opencv",
  videoMode:   "fast",
  tool:        "brush",    // "brush" | "box" | "eraser"
  drawing:     false,
  brushSize:   24,
  originalW:   0,
  originalH:   0,
  displayScale:1,
  lastX:       null,
  lastY:       null,
  boxStartX:   null,
  boxStartY:   null,
  boxSnapshot: null,
  sliderPct:   50,         // compare slider position (0–100)
  sliderDragging: false,
  downloadUrl: null,
};

// ── Elements ──────────────────────────────────────────────

const dropZone        = document.getElementById("drop-zone");
const fileInput       = document.getElementById("file-input");
const chooseBtn       = document.getElementById("choose-btn");
const changeFileBtn   = document.getElementById("change-file-btn");
const maskPanel       = document.getElementById("mask-panel");
const comparePanel    = document.getElementById("compare-panel");
const canvasScroll    = document.getElementById("canvas-scroll");
const imgCanvas       = document.getElementById("img-canvas");
const overlayCanvas   = document.getElementById("overlay-canvas");
const brushRange      = document.getElementById("brush-size");
const brushLabel      = document.getElementById("brush-label");
const brushBtn        = document.getElementById("brush-btn");
const boxBtn          = document.getElementById("box-btn");
const eraserBtn       = document.getElementById("eraser-btn");
const samBtn          = document.getElementById("sam-btn");
const clearBtn        = document.getElementById("clear-btn");
const fileNameLabel   = document.getElementById("file-name-label");
const sourceVideoBar  = document.getElementById("source-video-bar");
const sourceVideo     = document.getElementById("source-video");
const detectBtn       = document.getElementById("detect-btn");
const processBtn      = document.getElementById("process-btn");
const methodSeg       = document.getElementById("method-seg");
const modeSeg         = document.getElementById("mode-seg");
const videoOpts       = document.getElementById("video-opts");
const lamaBtn         = document.getElementById("lama-btn");
const sdBtn           = document.getElementById("sd-btn");
const statusBlock     = document.getElementById("status-block");
const statusText      = document.getElementById("status-text");
const statusSpinner   = document.getElementById("status-spinner");
const progressWrap    = document.getElementById("progress-wrap");
const progressFill    = document.getElementById("progress-fill");
const progressLabel   = document.getElementById("progress-label");
const resultSection   = document.getElementById("result-section");
const downloadBtn     = document.getElementById("download-btn");
const capsBar         = document.getElementById("caps-bar");
const backToMaskBtn   = document.getElementById("back-to-mask-btn");
const newFileBtn      = document.getElementById("new-file-btn");
const cmpFileLabel    = document.getElementById("cmp-file-label");

// Compare slider elements
const compareWrap     = document.getElementById("compare-wrap");
const compareHandle   = document.getElementById("compare-handle");
const compareBefore   = document.getElementById("compare-before");
const cmpBeforeImg    = document.getElementById("cmp-before-img");
const cmpAfterImg     = document.getElementById("cmp-after-img");
const cmpBeforeVideo  = document.getElementById("cmp-before-video");
const cmpAfterVideo   = document.getElementById("cmp-after-video");
const compareVideoBar = document.getElementById("compare-video-bar");
const cmpPlayBtn      = document.getElementById("cmp-play-btn");
const cmpPlayIcon     = document.getElementById("cmp-play-icon");
const cmpSeek         = document.getElementById("cmp-seek");
const cmpTime         = document.getElementById("cmp-time");

const imgCtx    = imgCanvas.getContext("2d");
const overlayCtx= overlayCanvas.getContext("2d");

// ── Init ─────────────────────────────────────────────────

(async function init() {
  try {
    const res  = await fetch("/capabilities");
    const caps = await res.json();
    [{ label: "OpenCV", on: caps.opencv }, { label: "LaMa", on: caps.lama },
     { label: "SD", on: caps.sd }, { label: "EasyOCR", on: caps.easyocr },
     { label: "SAM", on: caps.sam }]
      .forEach(({ label, on }) => {
        const b = document.createElement("span");
        b.className = "cap-badge" + (on ? " active" : "");
        b.textContent = label;
        capsBar.appendChild(b);
      });
    if (!caps.lama) { lamaBtn.disabled = true; lamaBtn.title = "Install simple-lama-inpainting to enable"; }
    if (!caps.sam)  { samBtn.disabled  = true; samBtn.title  = "SAM model not available"; }
    if (!caps.sd)   { sdBtn.disabled   = true; sdBtn.title   = "Install diffusers to enable"; }
  } catch (_) {}
})();

// ── File handling ─────────────────────────────────────────

chooseBtn.addEventListener("click",    () => fileInput.click());
changeFileBtn.addEventListener("click",() => fileInput.click());
fileInput.addEventListener("change",   () => { if (fileInput.files[0]) handleFile(fileInput.files[0]); });

dropZone.addEventListener("dragover",  (e) => { e.preventDefault(); dropZone.classList.add("drag-over"); });
dropZone.addEventListener("dragleave", ()  => dropZone.classList.remove("drag-over"));
dropZone.addEventListener("drop",      (e) => { e.preventDefault(); dropZone.classList.remove("drag-over"); if (e.dataTransfer.files[0]) handleFile(e.dataTransfer.files[0]); });

async function handleFile(file) {
  setStatus("Uploading…");

  const form = new FormData();
  form.append("file", file);

  let data;
  try {
    const res = await fetch("/upload", { method: "POST", body: form });
    if (!res.ok) throw new Error(await res.text());
    data = await res.json();
  } catch (err) {
    setStatus("Upload failed: " + err.message, "error");
    return;
  }

  state.fileId  = data.file_id;
  state.ext     = data.ext;
  state.isVideo = data.is_video;
  state.downloadUrl = null;

  clearStatus();
  hideResult();
  showMaskPanel();

  fileNameLabel.textContent = file.name;
  cmpFileLabel.textContent  = file.name;
  videoOpts.classList.toggle("hidden", !data.is_video);

  // Video: show the source player so user can watch original before masking
  if (data.is_video) {
    sourceVideo.src = `/source/${data.file_id}${data.ext}`;
    sourceVideoBar.classList.remove("hidden");
  } else {
    sourceVideo.src = "";
    sourceVideoBar.classList.add("hidden");
  }

  // Load first-frame preview into canvas
  await loadPreview(data.file_id);

  detectBtn.disabled = false;
  processBtn.disabled = false;
}

function showMaskPanel() {
  dropZone.classList.add("hidden");
  maskPanel.classList.remove("hidden");
  comparePanel.classList.add("hidden");
}

function showComparePanel() {
  maskPanel.classList.add("hidden");
  comparePanel.classList.remove("hidden");
}

backToMaskBtn.addEventListener("click", showMaskPanel);
newFileBtn.addEventListener("click", () => fileInput.click());

// ── Canvas preview ────────────────────────────────────────

async function loadPreview(fileId) {
  await new Promise((r) => requestAnimationFrame(r));

  return new Promise((resolve, reject) => {
    const img = new Image();
    img.onload = () => {
      state.originalW = img.naturalWidth;
      state.originalH = img.naturalHeight;

      const maxW = Math.max(canvasScroll.clientWidth  - 48, 400);
      const maxH = Math.max(canvasScroll.clientHeight - 48, 300);
      const scale = Math.min(maxW / img.naturalWidth, maxH / img.naturalHeight, 1);
      state.displayScale = scale;

      const dw = Math.round(img.naturalWidth  * scale);
      const dh = Math.round(img.naturalHeight * scale);

      imgCanvas.width = overlayCanvas.width  = dw;
      imgCanvas.height= overlayCanvas.height = dh;

      imgCtx.drawImage(img, 0, 0, dw, dh);
      clearOverlay();
      resolve();
    };
    img.onerror = reject;
    img.src = `/preview/${fileId}?t=${Date.now()}`;
  });
}

// ── Tool: Brush ───────────────────────────────────────────

function drawStroke(x, y) {
  overlayCtx.save();
  overlayCtx.globalCompositeOperation = state.tool === "eraser" ? "destination-out" : "source-over";
  overlayCtx.fillStyle  = "rgba(220, 60, 60, 0.55)";
  overlayCtx.strokeStyle= "rgba(220, 60, 60, 0.55)";
  overlayCtx.lineWidth  = state.brushSize * state.displayScale;
  overlayCtx.lineCap    = "round";
  overlayCtx.lineJoin   = "round";

  if (state.lastX !== null) {
    overlayCtx.beginPath();
    overlayCtx.moveTo(state.lastX, state.lastY);
    overlayCtx.lineTo(x, y);
    overlayCtx.stroke();
  }

  overlayCtx.beginPath();
  overlayCtx.arc(x, y, (state.brushSize * state.displayScale) / 2, 0, Math.PI * 2);
  overlayCtx.fill();
  overlayCtx.restore();

  state.lastX = x;
  state.lastY = y;
}

// ── Tool: Box ────────────────────────────────────────────

function boxDragStart(x, y) {
  state.boxStartX  = x;
  state.boxStartY  = y;
  state.boxSnapshot= overlayCtx.getImageData(0, 0, overlayCanvas.width, overlayCanvas.height);
}

function boxDragMove(x, y) {
  if (state.boxSnapshot) overlayCtx.putImageData(state.boxSnapshot, 0, 0);
  const rx = Math.min(state.boxStartX, x);
  const ry = Math.min(state.boxStartY, y);
  const rw = Math.abs(x - state.boxStartX);
  const rh = Math.abs(y - state.boxStartY);
  overlayCtx.save();
  overlayCtx.globalCompositeOperation = "source-over";
  overlayCtx.fillStyle  = "rgba(220, 60, 60, 0.45)";
  overlayCtx.strokeStyle= "rgba(220, 60, 60, 0.9)";
  overlayCtx.lineWidth  = 1.5;
  overlayCtx.fillRect(rx, ry, rw, rh);
  overlayCtx.strokeRect(rx, ry, rw, rh);
  overlayCtx.restore();
}

function boxDragEnd(x, y) {
  boxDragMove(x, y);
  state.boxSnapshot = null;
  state.boxStartX   = null;
  state.boxStartY   = null;
}

// ── Canvas pointer routing ────────────────────────────────

function getCanvasPos(e) {
  const rect   = overlayCanvas.getBoundingClientRect();
  const clientX= e.touches ? e.touches[0].clientX : e.clientX;
  const clientY= e.touches ? e.touches[0].clientY : e.clientY;
  return {
    x: (clientX - rect.left) * (overlayCanvas.width  / rect.width),
    y: (clientY - rect.top)  * (overlayCanvas.height / rect.height),
  };
}

overlayCanvas.addEventListener("mousedown", (e) => {
  const { x, y } = getCanvasPos(e);
  if (state.tool === "sam") { samSegment(x, y); return; }
  state.drawing = true;
  if (state.tool === "box") { boxDragStart(x, y); }
  else { state.lastX = null; drawStroke(x, y); }
});

overlayCanvas.addEventListener("mousemove", (e) => {
  if (!state.drawing) return;
  const { x, y } = getCanvasPos(e);
  if (state.tool === "box") { boxDragMove(x, y); }
  else { drawStroke(x, y); }
});

overlayCanvas.addEventListener("mouseup", (e) => {
  if (!state.drawing) return;
  const { x, y } = getCanvasPos(e);
  if (state.tool === "box") boxDragEnd(x, y);
  state.drawing = false; state.lastX = null; state.lastY = null;
});

overlayCanvas.addEventListener("mouseleave", () => {
  if (state.drawing && state.tool === "box" && state.boxSnapshot) state.boxSnapshot = null;
  state.drawing = false; state.lastX = null; state.lastY = null;
});

overlayCanvas.addEventListener("touchstart", (e) => {
  e.preventDefault(); state.drawing = true;
  const { x, y } = getCanvasPos(e);
  if (state.tool === "box") { boxDragStart(x, y); } else { state.lastX = null; drawStroke(x, y); }
}, { passive: false });

overlayCanvas.addEventListener("touchmove", (e) => {
  e.preventDefault(); if (!state.drawing) return;
  const { x, y } = getCanvasPos(e);
  if (state.tool === "box") { boxDragMove(x, y); } else { drawStroke(x, y); }
}, { passive: false });

overlayCanvas.addEventListener("touchend", (e) => {
  if (state.drawing && state.tool === "box") {
    const { x, y } = getCanvasPos({ touches: e.changedTouches });
    boxDragEnd(x, y);
  }
  state.drawing = false; state.lastX = null; state.lastY = null;
});

// ── Toolbar controls ──────────────────────────────────────

function setTool(tool) {
  state.tool = tool;
  overlayCanvas.style.cursor = tool === "sam" ? "cell" : "crosshair";
  [brushBtn, boxBtn, eraserBtn, samBtn].forEach((b) => b.classList.remove("active"));
  ({ brush: brushBtn, box: boxBtn, eraser: eraserBtn, sam: samBtn })[tool]?.classList.add("active");
}

brushBtn.addEventListener("click",  () => setTool("brush"));
boxBtn.addEventListener("click",    () => setTool("box"));
eraserBtn.addEventListener("click", () => setTool("eraser"));
samBtn.addEventListener("click",    () => setTool("sam"));

brushRange.addEventListener("input", () => {
  state.brushSize = parseInt(brushRange.value);
  brushLabel.textContent = brushRange.value + "px";
});

clearBtn.addEventListener("click", clearOverlay);

function clearOverlay() {
  overlayCtx.clearRect(0, 0, overlayCanvas.width, overlayCanvas.height);
}

// SAM click-to-segment
async function samSegment(x, y) {
  if (!state.fileId) return;
  samBtn.disabled = true;
  samBtn.textContent = "SAM…";
  overlayCanvas.style.cursor = "wait";

  try {
    const form = new FormData();
    form.append("file_id",  state.fileId);
    form.append("ext",      state.ext);
    form.append("x",        x);
    form.append("y",        y);
    form.append("canvas_w", overlayCanvas.width);
    form.append("canvas_h", overlayCanvas.height);

    const res  = await fetch("/segment", { method: "POST", body: form });
    const data = await res.json();
    if (!res.ok) throw new Error(data.detail || "SAM failed");

    // Paint the returned mask onto the overlay canvas
    const img = new Image();
    img.onload = () => {
      overlayCtx.save();
      overlayCtx.globalCompositeOperation = "source-over";
      // Tint the mask red (draw mask, then composite colour)
      const tmpCanvas = document.createElement("canvas");
      tmpCanvas.width  = overlayCanvas.width;
      tmpCanvas.height = overlayCanvas.height;
      const tmpCtx = tmpCanvas.getContext("2d");
      tmpCtx.drawImage(img, 0, 0, overlayCanvas.width, overlayCanvas.height);
      // Use the mask as alpha, fill red
      tmpCtx.globalCompositeOperation = "source-in";
      tmpCtx.fillStyle = "rgba(220, 60, 60, 0.55)";
      tmpCtx.fillRect(0, 0, tmpCanvas.width, tmpCanvas.height);
      overlayCtx.drawImage(tmpCanvas, 0, 0);
      overlayCtx.restore();
    };
    img.src = data.mask;
  } catch (err) {
    setStatus("SAM error: " + err.message, "error");
  } finally {
    samBtn.disabled = false;
    samBtn.textContent = "SAM ✦";
    overlayCanvas.style.cursor = "cell";
  }
}

// Segmented controls
function bindSegmented(el, key) {
  el.querySelectorAll("button").forEach((btn) =>
    btn.addEventListener("click", () => {
      if (btn.disabled) return;
      el.querySelectorAll("button").forEach((b) => b.classList.remove("active"));
      btn.classList.add("active");
      state[key] = btn.dataset.val;
    })
  );
}
bindSegmented(methodSeg, "method");
bindSegmented(modeSeg,   "videoMode");

// ── Mask extraction ───────────────────────────────────────

function getMaskDataURL() {
  const tmp = document.createElement("canvas");
  tmp.width  = state.originalW;
  tmp.height = state.originalH;
  const ctx  = tmp.getContext("2d");
  ctx.drawImage(overlayCanvas, 0, 0, state.originalW, state.originalH);
  const d    = ctx.getImageData(0, 0, state.originalW, state.originalH);
  for (let i = 0; i < d.data.length; i += 4) {
    const v = d.data[i + 3] > 10 ? 255 : 0;
    d.data[i] = d.data[i+1] = d.data[i+2] = v;
    d.data[i+3] = 255;
  }
  ctx.putImageData(d, 0, 0);
  return tmp.toDataURL("image/png");
}

function hasMask() {
  const d = overlayCtx.getImageData(0, 0, overlayCanvas.width, overlayCanvas.height).data;
  for (let i = 3; i < d.length; i += 4) if (d[i] > 10) return true;
  return false;
}

// ── Auto-detect ───────────────────────────────────────────

detectBtn.addEventListener("click", async () => {
  if (!state.fileId) return;
  setStatus("Detecting watermarks…");
  detectBtn.disabled = true;
  try {
    const form = new FormData();
    form.append("file_id", state.fileId);
    form.append("ext",     state.ext);
    const res    = await fetch("/detect", { method: "POST", body: form });
    if (!res.ok) throw new Error(await res.text());
    const data   = await res.json();
    if (!data.regions?.length) {
      setStatus("No watermarks detected automatically. Draw the mask manually.", "warn");
      return;
    }
    const sx = overlayCanvas.width  / data.image_width;
    const sy = overlayCanvas.height / data.image_height;
    overlayCtx.save();
    overlayCtx.fillStyle = "rgba(220, 60, 60, 0.55)";
    data.regions.forEach(({ x, y, w, h }) => overlayCtx.fillRect(x*sx, y*sy, w*sx, h*sy));
    overlayCtx.restore();
    setStatus(`Detected ${data.regions.length} region(s). Adjust the mask if needed, then click Remove.`, "success");
  } catch (err) {
    setStatus("Detection failed: " + err.message, "error");
  } finally {
    detectBtn.disabled = false;
  }
});

// ── Process ───────────────────────────────────────────────

processBtn.addEventListener("click", async () => {
  if (!state.fileId) return;
  if (!hasMask()) { setStatus("Draw a mask over the watermark first, or use Auto Detect.", "warn"); return; }

  // SD is images only β€” too slow for per-frame video
  if (state.isVideo && state.method === "sd") {
    setStatus("⚠ Stable Diffusion is for images only β€” switch to OpenCV or LaMa for video.", "warn");
    return;
  }

  // Warn when LaMa + thorough video would take hours (allow after confirmation)
  if (state.isVideo && state.videoMode === "thorough" && state.method === "lama") {
    const ok = confirm("LaMa + Thorough inpaints every frame with the ML model β€” expect 30–60 s per frame on CPU.\n\nFor an 8-second video that could be several hours.\n\nProceed anyway?");
    if (!ok) {
      setStatus("⚠ LaMa + Thorough can take hours. Switched to OpenCV or Fast mode recommended.", "warn");
      return;
    }
  }

  setStatus(state.isVideo ? "Starting video processing…" : "Starting inpainting…");
  showProgress(0, state.method === "lama" ? "Loading LaMa model (first run ~20s)…" : "");
  processBtn.disabled = true;
  detectBtn.disabled  = true;
  hideResult();

  const maskDataURL = getMaskDataURL();
  const form        = new FormData();
  form.append("file_id",   state.fileId);
  form.append("ext",       state.ext);
  form.append("mask_data", maskDataURL);
  form.append("method",    state.method);
  if (state.isVideo) form.append("mode", state.videoMode);

  try {
    const res = await fetch(state.isVideo ? "/process/video" : "/process/image", { method: "POST", body: form });
    if (!res.ok) throw new Error(await res.text());
    const { job_id } = await res.json();
    await pollJob(job_id);
  } catch (err) {
    setStatus("Failed: " + err.message, "error");
    hideProgress();
  } finally {
    processBtn.disabled = false;
    detectBtn.disabled  = false;
  }
});

async function pollJob(jobId) {
  while (true) {
    await new Promise((r) => setTimeout(r, 800));

    let data;
    try {
      const res = await fetch(`/status/${jobId}`);
      data = await res.json();
    } catch (_) {
      continue;
    }

    const pct = data.total > 0 ? Math.round((data.progress / data.total) * 100) : null;
    setStatus(data.message || "Processing…");
    if (pct !== null) showProgress(pct, data.message);

    if (data.status === "done") {
      hideProgress();
      state.downloadUrl = data.download_url;
      await showResult(data.download_url);
      setStatus("Done β€” drag the slider to compare.", "success");
      break;
    } else if (data.status === "error") {
      hideProgress();
      setStatus("Error: " + data.message, "error");
      break;
    }
  }
}

// ── Result / Compare view ─────────────────────────────────

async function showResult(downloadUrl) {
  resultSection.classList.remove("hidden");
  downloadBtn.href = downloadUrl;
  downloadBtn.classList.remove("hidden");

  if (state.isVideo) {
    // Hide images, show videos
    cmpBeforeImg.style.display  = "none";
    cmpAfterImg.style.display   = "none";
    cmpBeforeVideo.style.display= "";
    cmpAfterVideo.style.display = "";

    cmpBeforeVideo.src = `/source/${state.fileId}${state.ext}`;
    cmpAfterVideo.src  = downloadUrl;
    await Promise.all([loadMedia(cmpBeforeVideo), loadMedia(cmpAfterVideo)]);

    compareVideoBar.classList.remove("hidden");
    wireVideoSync();
  } else {
    // Hide videos, show images
    cmpBeforeVideo.style.display = "none";
    cmpAfterVideo.style.display  = "none";
    cmpBeforeImg.style.display   = "";
    cmpAfterImg.style.display    = "";

    cmpBeforeImg.src = `/preview/${state.fileId}?t=${Date.now()}`;
    cmpAfterImg.src  = downloadUrl + `?t=${Date.now()}`;
    await Promise.all([loadMedia(cmpBeforeImg), loadMedia(cmpAfterImg)]);

    compareVideoBar.classList.add("hidden");
  }

  setSlider(50);
  showComparePanel();
}

function loadMedia(el) {
  return new Promise((resolve) => {
    if (el.tagName === "IMG") {
      if (el.complete) { resolve(); return; }
      el.onload = el.onerror = resolve;
    } else {
      el.onloadedmetadata = el.onerror = resolve;
      el.load();
    }
  });
}

function hideResult() {
  resultSection.classList.add("hidden");
  downloadBtn.classList.add("hidden");
  compareVideoBar.classList.add("hidden");
}

// ── Compare slider ────────────────────────────────────────

function setSlider(pct) {
  state.sliderPct = Math.max(0, Math.min(100, pct));
  compareBefore.style.clipPath  = `inset(0 ${100 - state.sliderPct}% 0 0)`;
  compareHandle.style.left      = state.sliderPct + "%";
}

function sliderPosFromEvent(e) {
  const rect = compareWrap.getBoundingClientRect();
  const clientX = e.touches ? e.touches[0].clientX : e.clientX;
  return ((clientX - rect.left) / rect.width) * 100;
}

compareWrap.addEventListener("mousedown", (e) => {
  state.sliderDragging = true;
  setSlider(sliderPosFromEvent(e));
});

window.addEventListener("mousemove", (e) => {
  if (!state.sliderDragging) return;
  setSlider(sliderPosFromEvent(e));
});

window.addEventListener("mouseup", () => { state.sliderDragging = false; });

compareWrap.addEventListener("touchstart", (e) => {
  state.sliderDragging = true;
  setSlider(sliderPosFromEvent(e));
}, { passive: true });

window.addEventListener("touchmove", (e) => {
  if (!state.sliderDragging) return;
  setSlider(sliderPosFromEvent(e));
}, { passive: true });

window.addEventListener("touchend", () => { state.sliderDragging = false; });

// ── Video sync (compare) ──────────────────────────────────

let _syncWired = false;

function wireVideoSync() {
  if (_syncWired) { _syncWired = false; cmpAfterVideo.pause(); }

  // After video is the "controller" β€” before video follows
  const sync = () => {
    if (Math.abs(cmpAfterVideo.currentTime - cmpBeforeVideo.currentTime) > 0.15) {
      cmpBeforeVideo.currentTime = cmpAfterVideo.currentTime;
    }
  };

  cmpAfterVideo.addEventListener("timeupdate", sync);
  cmpAfterVideo.addEventListener("play",  () => cmpBeforeVideo.play().catch(() => {}));
  cmpAfterVideo.addEventListener("pause", () => cmpBeforeVideo.pause());
  cmpAfterVideo.addEventListener("seeked",() => { cmpBeforeVideo.currentTime = cmpAfterVideo.currentTime; });

  // Play/pause button
  cmpPlayBtn.onclick = () => {
    if (cmpAfterVideo.paused) { cmpAfterVideo.play(); } else { cmpAfterVideo.pause(); }
  };

  // Seek bar
  cmpAfterVideo.addEventListener("timeupdate", () => {
    if (cmpAfterVideo.duration) {
      cmpSeek.value = (cmpAfterVideo.currentTime / cmpAfterVideo.duration) * 100;
      cmpTime.textContent = `${fmt(cmpAfterVideo.currentTime)} / ${fmt(cmpAfterVideo.duration)}`;
    }
  });

  cmpSeek.addEventListener("input", () => {
    cmpAfterVideo.currentTime = (parseFloat(cmpSeek.value) / 100) * cmpAfterVideo.duration;
  });

  cmpAfterVideo.addEventListener("play",  () => { cmpPlayBtn.querySelector("svg").innerHTML = '<rect x="6" y="4" width="4" height="16"/><rect x="14" y="4" width="4" height="16"/>'; });
  cmpAfterVideo.addEventListener("pause", () => { cmpPlayBtn.querySelector("svg").innerHTML = '<polygon points="5 3 19 12 5 21 5 3"/>'; });

  _syncWired = true;
}

function fmt(s) {
  const m = Math.floor(s / 60);
  const ss= Math.floor(s % 60).toString().padStart(2, "0");
  return `${m}:${ss}`;
}

// ── Auto-detect ───────────────────────────────────────────

// (wired above, no duplicate needed)

// ── Status + progress helpers ─────────────────────────────

function setStatus(msg, type = "") {
  statusBlock.classList.remove("hidden", "error", "success", "warn");
  statusText.textContent = msg;
  // Show spinner only while actively processing (no type = still running)
  statusSpinner.classList.toggle("hidden", !!type);
  if (type) statusBlock.classList.add(type);
}

function showProgress(pct, label = "") {
  progressWrap.classList.remove("hidden");
  progressFill.style.width  = pct + "%";
  progressLabel.textContent = pct + "%";
  if (label) statusText.textContent = label;
}

function hideProgress() {
  progressWrap.classList.add("hidden");
  progressFill.style.width = "0%";
}

function clearStatus() {
  statusBlock.classList.add("hidden");
  hideProgress();
}