/* ───────────────────────────────────────────────────────────────────────────
   Wivexx transfer overlay — a small always-on-top HUD shown while photos/videos
   import from a drive (and, later, while a delivery uploads). Drive name, a live
   progress bar, files x/total, ETA, plus pause/resume + cancel. Matches the
   control-room design. Python drives it through `window.wivexxTransfer.setStatus`;
   this page calls back via `pywebview.api.*` (pause/resume/cancel/close/start_drag).
   ─────────────────────────────────────────────────────────────────────────── */
(function () {
  "use strict";
  let _pyReady = false;
  const _queue = [];
  function py(method) {
    const args = Array.prototype.slice.call(arguments, 1);
    const run = () => { try { return window.pywebview.api[method].apply(null, args); } catch (e) {} };
    if (_pyReady && window.pywebview && window.pywebview.api) return run();
    _queue.push(run);
  }
  function flush() { _pyReady = true; while (_queue.length) { try { _queue.shift()(); } catch (e) {} } }

  const $ = (id) => document.getElementById(id);
  let _paused = false;

  function fmtEta(sec) {
    if (sec == null || !isFinite(sec) || sec < 0) return "";
    sec = Math.round(sec);
    if (sec < 60) return "~" + sec + "s left";
    const m = Math.floor(sec / 60), s = sec % 60;
    if (m < 60) return "~" + m + "m " + (s ? s + "s " : "") + "left";
    const h = Math.floor(m / 60);
    return "~" + h + "h " + (m % 60) + "m left";
  }

  function setTitle(text, cls) {
    const t = $("title");
    t.className = "t" + (cls ? " " + cls : "");
    $("title-text").textContent = text;
  }

  function render(d) {
    d = d || {};
    const phase = d.phase || "copying";
    const kind = d.kind === "deliver" ? (d.stage || "delivering") : "importing";
    _paused = !!d.paused;

    $("drive").textContent = d.label || "storage";

    const total = d.total || 0;
    const copied = d.copied || 0;
    const pct = d.percent != null ? d.percent : 0;
    const fill = $("fill");

    if (phase === "scanning") {
      setTitle("scanning", "");
      $("sub").textContent = "counting files…";
      fill.classList.add("indet");
      $("count").textContent = "";
      $("pct").textContent = "";
      $("file").textContent = "";
    } else if (phase === "done" || phase === "cancelled" || phase === "failed") {
      const verb = phase === "done" ? "complete" : phase;
      setTitle(verb, "done");
      fill.classList.remove("indet");
      fill.style.width = (phase === "done" ? 100 : pct) + "%";
      const parts = [];
      if (copied) parts.push(copied + " copied");
      if (d.skipped) parts.push(d.skipped + " skipped");
      if (d.failed) parts.push(d.failed + " failed");
      $("sub").textContent = parts.join(" · ") || "nothing new";
      $("count").textContent = total ? copied + " of " + total + " files" : "";
      $("pct").textContent = phase === "done" ? "100%" : pct + "%";
      $("file").textContent = "";
    } else {
      // copying / paused
      setTitle(_paused ? "paused" : kind, _paused ? "paused" : "");
      fill.classList.remove("indet");
      fill.style.width = pct + "%";
      $("count").textContent = total ? copied + " of " + total + " files" : copied + " files";
      $("pct").textContent = pct + "%";
      $("sub").textContent = _paused ? "paused" : (fmtEta(d.eta) || "working…");
      $("file").textContent = d.current || "";
    }

    // buttons: only meaningful while running/paused
    const running = (phase === "copying" || phase === "paused" || phase === "uploading");
    const pause = $("pause"), cancel = $("cancel");
    pause.classList.toggle("hidden", !running);
    cancel.classList.toggle("hidden", !running);
    pause.textContent = _paused ? "resume" : "pause";
    if (!running) {
      // terminal — turn cancel into a dismiss
      cancel.classList.remove("hidden");
      cancel.textContent = "close";
      cancel.dataset.mode = "close";
    } else {
      cancel.textContent = "cancel";
      cancel.dataset.mode = "cancel";
    }
  }

  window.wivexxTransfer = { setStatus: render };

  function wireDrag() {
    let dx = 0, dy = 0, dragging = false;
    const bar = $("bar");
    bar.addEventListener("mousedown", (e) => {
      if (e.button !== 0 || e.target.id === "x") return;
      dx = e.screenX; dy = e.screenY; dragging = false; e.preventDefault();
    });
    document.addEventListener("mousemove", (e) => {
      if (e.buttons === 0 || dragging) return;
      if (Math.abs(e.screenX - dx) > 4 || Math.abs(e.screenY - dy) > 4) { dragging = true; py("start_drag"); }
    });
    document.addEventListener("mouseup", () => { dragging = false; });
  }

  function boot() {
    $("x").addEventListener("click", () => py("close"));
    $("pause").addEventListener("click", () => { py(_paused ? "resume" : "pause"); });
    $("cancel").addEventListener("click", (e) => {
      py(e.target.dataset.mode === "close" ? "close" : "cancel");
    });
    wireDrag();
    py("ready");
  }
  if (window.pywebview && window.pywebview.api) { _pyReady = true; }
  window.addEventListener("pywebviewready", flush);
  if (document.readyState === "loading") document.addEventListener("DOMContentLoaded", boot);
  else boot();
})();
