/* The chrome a borderless window has to draw for itself.

   With no OS frame there is nothing to drag the window by, nothing to
   minimize it with, and — on Windows, where frameless sets the form border
   style to None — no resize edges either. Those three jobs move into the
   page, so they live here rather than in core.js: the CUT editor has its
   own top bar and does not load core.js, and a window you cannot move on
   one screen out of six is not a window.

   Mounts into whichever bar the page has: #app-nav (the library screens)
   or .topbar (the editor). Does nothing at all in a browser tab, which has
   chrome of its own. */
'use strict';
(function () {
  var mounted = false;

  function icon(name) {
    return '<svg style="width:15px;height:15px" aria-hidden="true">' +
           '<use href="#i-' + name + '"/></svg>';
  }

  /* One request in flight at a time. This is driven by mousemove, and
     queueing every frame floods the loopback and lags behind the cursor. */
  var busy = false, pending = null;
  function sendSize() {
    if (busy || !pending) return;
    busy = true;
    var size = pending; pending = null;
    fetch('/api/window/resize', {
      method: 'POST', headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(size)
    }).catch(function () {}).then(function () { busy = false; sendSize(); });
  }

  function grip() {
    if (document.getElementById('win-grip')) return;
    var g = document.createElement('div');
    g.id = 'win-grip';
    g.title = 'drag to resize';
    g.style.cssText = 'position:fixed;right:0;bottom:0;width:16px;height:16px;' +
      'z-index:2147483647;cursor:nwse-resize;' +
      'background:linear-gradient(135deg,transparent 50%,var(--border-hi) 50%,' +
      'var(--border-hi) 62%,transparent 62%,transparent 74%,var(--border-hi) 74%,' +
      'var(--border-hi) 86%,transparent 86%)';
    document.body.appendChild(g);
    g.addEventListener('mousedown', function (down) {
      down.preventDefault();
      /* frameless: the viewport IS the window, so there is no frame to add */
      var x0 = down.screenX, y0 = down.screenY;
      var w0 = window.innerWidth, h0 = window.innerHeight;
      function move(m) {
        pending = { w: Math.round(w0 + m.screenX - x0),
                    h: Math.round(h0 + m.screenY - y0) };
        sendSize();
      }
      function up() {
        window.removeEventListener('mousemove', move);
        window.removeEventListener('mouseup', up);
      }
      window.addEventListener('mousemove', move);
      window.addEventListener('mouseup', up);
    });
  }

  function buttons(bar) {
    var ctl = document.createElement('div');
    ctl.id = 'win-ctl';
    ctl.style.cssText = 'display:flex;gap:2px;align-items:center;margin-right:-12px';
    ctl.innerHTML = ['minimize', 'maximize', 'close'].map(function (act) {
      return '<button data-win="' + act + '" title="' + (act === 'close'
          ? 'close to the tray — recording keeps going' : act) + '" ' +
        'style="background:none;border:0;color:var(--text-dim);cursor:pointer;' +
        'padding:8px 11px;border-radius:8px;display:flex;align-items:center">' +
        icon(act) + '</button>';
    }).join('');
    bar.appendChild(ctl);
    ctl.querySelectorAll('[data-win]').forEach(function (b) {
      b.addEventListener('mouseenter', function () {
        b.style.background = b.dataset.win === 'close'
          ? 'var(--accent)' : 'rgba(255,255,255,0.09)';
        b.style.color = b.dataset.win === 'close' ? '#14100a' : 'var(--text)';
      });
      b.addEventListener('mouseleave', function () {
        b.style.background = 'none'; b.style.color = 'var(--text-dim)';
      });
      b.addEventListener('click', function () {
        fetch('/api/window/' + b.dataset.win, { method: 'POST' }).catch(function () {});
      });
    });
  }

  /* The drag handle is the empty space in the bar and ONLY that. A drag
     region over the whole bar would swallow the clicks on everything in it,
     trading the title bar for the navigation. The editor already has a
     .spacer doing that job; the library screens get one added. */
  function dragHandle(bar) {
    var spacer = bar.querySelector('.spacer');
    if (spacer) {
      spacer.classList.add('pywebview-drag-region');
      return;
    }
    var d = document.createElement('div');
    d.className = 'pywebview-drag-region';
    d.style.cssText = 'flex:1;align-self:stretch;min-width:20px';
    bar.appendChild(d);
  }

  /* A page with no bar of its own — the setup wizard, which owns the very
     first run and is therefore the FIRST window anyone tries to move. It
     gets a strip of its own across the top rather than nothing. Kept thin
     and pinned above the content: the wizard's own top edge is empty
     space, and a fatter one would start eating clicks. */
  function ownBar() {
    var bar = document.createElement('div');
    bar.id = 'win-bar';
    bar.style.cssText = 'position:fixed;top:0;left:0;right:0;height:30px;' +
      'display:flex;align-items:center;justify-content:flex-end;' +
      'padding-right:12px;z-index:2147483646';
    document.body.appendChild(bar);
    return bar;
  }

  function mount() {
    if (mounted) return;
    var bar = document.getElementById('app-nav') || document.querySelector('.topbar');
    if (bar && bar.querySelector('#win-ctl')) return;
    mounted = true;
    bar = bar || ownBar();
    dragHandle(bar);
    buttons(bar);
    grip();
  }

  window.mountWindowChrome = mount;

  fetch('/api/health/ping').then(function (r) { return r.json(); }).then(function (j) {
    if (!j.frameless) return;
    window.__frameless = true;
    document.readyState === 'loading'
      ? document.addEventListener('DOMContentLoaded', mount) : mount();
  }).catch(function () {});
})();
