/* ───────────────────────────────────────────────────────────────────────────
   Wivexx "today's focus" goals overlay — a small always-on-top to-do widget,
   shown by the goals-overlay shortcut. 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 call(m) { const r = py.apply(null, arguments); return (r && r.then) ? r : Promise.resolve(r); }
  function esc(s) { return (s == null ? "" : String(s)).replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" }[c])); }

  const list = () => document.getElementById("list");
  const today = () => new Date().toISOString().slice(0, 10);

  function render(goals) {
    goals = goals || [];
    if (!goals.length) { list().innerHTML = '<div class="empty">Nothing on your focus list.<br>Say “add a goal …”.</div>'; return; }
    list().innerHTML = goals.map((g) => {
      let meta = [];
      if (g.priority === "high") meta.push('<span class="hi">high</span>');
      if (g.due) { const o = g.due < today(), t = g.due === today();
        meta.push('<span class="' + (o ? "over" : t ? "today" : "") + '">' + (o ? "overdue" : t ? "due today" : "due " + esc(g.due)) + "</span>"); }
      return '<div class="g ' + (g.done ? "done" : "") + '"><div class="c" data-id="' + g.id + '"></div>' +
        '<div><div class="tt">' + esc(g.title) + '</div>' + (meta.length ? '<div class="m">' + meta.join(" · ") + "</div>" : "") + "</div></div>";
    }).join("");
    Array.prototype.forEach.call(list().querySelectorAll(".c"), (c) =>
      c.addEventListener("click", () => call("toggle", parseInt(c.getAttribute("data-id"), 10)).then(render)));
  }

  window.wivexxGoals = { setGoals: 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"));
    document.getElementById("more").addEventListener("click", () => py("open_full"));
    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();
})();
