/* ───────────────────────────────────────────────────────────────────────────
   Wivexx live timer countdown — a small always-on-top widget that lists running
   timers and ticks them down. Auto-shown by Python while timers run; each row
   can be cancelled (×). Python pushes the list (with `ends` epochs) via
   `window.wivexxTimers.setTimers`; the page ticks locally between pushes.
   ─────────────────────────────────────────────────────────────────────────── */
(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 listEl = () => document.getElementById("list");
  let _timers = [];
  let _sig = "";

  function fmt(sec) {
    sec = Math.max(0, Math.round(sec));
    const h = Math.floor(sec / 3600), m = Math.floor((sec % 3600) / 60), s = sec % 60;
    const mm = String(m).padStart(2, "0"), ss = String(s).padStart(2, "0");
    return h ? (h + ":" + mm + ":" + ss) : (mm + ":" + ss);
  }

  function rebuild() {
    const el = listEl();
    if (!_timers.length) { el.innerHTML = '<div class="empty">no active timers</div>'; return; }
    el.innerHTML = _timers.map((t) =>
      '<div class="trow" data-id="' + t.id + '">' +
        '<span class="tlabel"></span>' +
        '<span class="ttime">--:--</span>' +
        '<button class="tx" data-cancel="' + t.id + '" aria-label="Cancel timer">&#10005;</button>' +
      "</div>").join("");
    const rows = el.querySelectorAll(".trow");
    _timers.forEach((t, i) => { const l = rows[i] && rows[i].querySelector(".tlabel"); if (l) l.textContent = t.label || "timer"; });
    el.querySelectorAll("[data-cancel]").forEach((b) => b.addEventListener("click", () =>
      py("cancel", parseInt(b.getAttribute("data-cancel"), 10))));
  }

  function tick() {
    if (!_timers.length) return;
    const now = Date.now() / 1000;
    const el = listEl();
    _timers.forEach((t) => {
      const row = el.querySelector('.trow[data-id="' + t.id + '"]');
      if (!row) return;
      const rem = (t.ends || 0) - now;
      const tm = row.querySelector(".ttime");
      if (tm) tm.textContent = fmt(rem);
      row.classList.toggle("soon", rem <= 10);
    });
  }

  window.wivexxTimers = {
    setTimers(list) {
      _timers = list || [];
      const sig = _timers.map((t) => t.id).join(",");
      if (sig !== _sig) { _sig = sig; rebuild(); }
      tick();
    },
  };

  function wireDrag() {
    let dx = 0, dy = 0, dragging = false;
    const bar = document.getElementById("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() {
    document.getElementById("x").addEventListener("click", () => py("close"));
    wireDrag();
    setInterval(tick, 250);
    py("ready");
  }
  if (window.pywebview && window.pywebview.api) { _pyReady = true; }
  window.addEventListener("pywebviewready", flush);
  if (document.readyState === "loading") document.addEventListener("DOMContentLoaded", boot);
  else boot();
})();
