/**
 * Collapsible left nav: click toggle + horizontal drag on handle (open on drag right).
 */
(function () {
  'use strict';

  var DRAG_THRESHOLD_PX = 20;

  function setOpen(nav, handle, open) {
    nav.classList.toggle('open', open);
    if (handle) {
      handle.setAttribute('aria-expanded', open ? 'true' : 'false');
    }
  }

  function bindNavShell(paneId, handleId) {
    var nav = document.getElementById(paneId);
    var handle = document.getElementById(handleId);
    if (!nav || !handle) return;

    setOpen(nav, handle, nav.classList.contains('open'));

    var drag = null;
    var suppressClick = false;

    handle.addEventListener('click', function (ev) {
      if (suppressClick) {
        suppressClick = false;
        ev.preventDefault();
        return;
      }
      setOpen(nav, handle, !nav.classList.contains('open'));
    });

    handle.addEventListener('pointerdown', function (ev) {
      if (ev.button !== 0) return;
      drag = { x: ev.clientX, moved: false };
      handle.setPointerCapture(ev.pointerId);
      handle.classList.add('is-dragging');
      ev.preventDefault();
    });

    handle.addEventListener('pointermove', function (ev) {
      if (!drag || !handle.hasPointerCapture(ev.pointerId)) return;
      var dx = ev.clientX - drag.x;
      if (Math.abs(dx) < 4) return;
      drag.moved = true;
      if (dx > DRAG_THRESHOLD_PX) {
        setOpen(nav, handle, true);
        drag.x = ev.clientX;
      } else if (dx < -DRAG_THRESHOLD_PX) {
        setOpen(nav, handle, false);
        drag.x = ev.clientX;
      }
    });

    function endDrag(ev) {
      if (!drag) return;
      if (drag.moved) suppressClick = true;
      drag = null;
      handle.classList.remove('is-dragging');
      if (handle.hasPointerCapture(ev.pointerId)) {
        handle.releasePointerCapture(ev.pointerId);
      }
    }

    handle.addEventListener('pointerup', endDrag);
    handle.addEventListener('pointercancel', endDrag);
  }

  window.initNavShell = bindNavShell;

  function autoInit() {
    bindNavShell('nav-pane', 'nav-handle');
    bindNavShell('landing-nav-pane', 'landing-nav-handle');
  }

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', autoInit);
  } else {
    autoInit();
  }
})();
