/* ───────────────────────────────────────────────────────────────────────────
   Wivexx status overlay — small always-on-top widget: state, active timers,
   today's API usage/cost. Matches the control room design.
   ─────────────────────────────────────────────────────────────────────────── */
(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) {} } }
  function esc(s) { return (s == null ? "" : String(s)).replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" }[c])); }
  const bodyEl = () => document.getElementById("body");

  function render(d) {
    d = d || {};
    const rows = [];
    rows.push('<div class="row"><div class="k">state</div><div class="v">' + esc(d.state || "idle") + "</div></div>");
    const timers = d.timers || [];
    rows.push('<div class="row"><div class="k">active timers</div>' +
      (timers.length ? timers.map((t) => '<div class="muted">' + esc(t) + "</div>").join("")
        : '<div class="muted">none</div>') + "</div>");
    const u = d.usage || {};
    rows.push('<div class="row"><div class="k">today</div>' +
      '<div class="v big">' + esc(u.cost || "$0.00") + "</div>" +
      '<div class="muted">' + esc(u.calls != null ? u.calls + " API calls" : "") + "</div></div>");
    bodyEl().innerHTML = rows.join("");
  }

  window.wivexxStatus = { setStatus: render };

  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();
    py("ready");
  }
  if (window.pywebview && window.pywebview.api) { _pyReady = true; }
  window.addEventListener("pywebviewready", flush);
  if (document.readyState === "loading") document.addEventListener("DOMContentLoaded", boot);
  else boot();
})();
