(function () {
  var ctrl = window.harmonyChromeControls;
  if (!ctrl) return;

  var minBtn = document.getElementById('harmony-tb-minimize');
  var maxBtn = document.getElementById('harmony-tb-maximize');
  var closeBtn = document.getElementById('harmony-tb-close');

  if (minBtn) minBtn.addEventListener('click', function () { ctrl.minimize(); });
  if (closeBtn) closeBtn.addEventListener('click', function () { ctrl.close(); });

  if (maxBtn) {
    maxBtn.addEventListener('click', function () { ctrl.maximize(); });

    // Sync initial state
    ctrl.isMaximized().then(function (m) {
      if (m) maxBtn.classList.add('is-maximized');
      else maxBtn.classList.remove('is-maximized');
    });

    // Listen for state changes
    ctrl.onMaximizedChange(function (m) {
      if (m) maxBtn.classList.add('is-maximized');
      else maxBtn.classList.remove('is-maximized');
    });
  }

  // Double-click titlebar to maximize/restore (like native)
  var brand = document.getElementById('harmony-titlebar-brand');
  var drag = document.getElementById('harmony-titlebar-drag');
  function onDblClick() { ctrl.maximize(); }
  if (brand) brand.addEventListener('dblclick', onDblClick);
  if (drag) drag.addEventListener('dblclick', onDblClick);
})();
