const MIN_WIDTH = 340;
const MAX_WIDTH = 500;

let _aside = null;
let _handle = null;
let _onResizeEnd = null;

export function init({ aside, handle, initialWidth = MIN_WIDTH, onResizeEnd }) {
  _aside = aside;
  _handle = handle;
  _onResizeEnd = onResizeEnd;

  setWidth(initialWidth);
  _handle.addEventListener('pointerdown', onPointerDown);
}

function onPointerDown(e) {
  e.preventDefault();
  _handle.setPointerCapture(e.pointerId);
  document.body.classList.add('resizing-sidebar');

  _handle.addEventListener('pointermove', onPointerMove);
  _handle.addEventListener('pointerup', onPointerUp);
  _handle.addEventListener('pointercancel', onPointerUp);
}

function onPointerMove(e) {
  const left = _aside.getBoundingClientRect().left;
  setWidth(e.clientX - left);
}

function onPointerUp(e) {
  if (_handle.hasPointerCapture(e.pointerId)) {
    _handle.releasePointerCapture(e.pointerId);
  }

  document.body.classList.remove('resizing-sidebar');
  _handle.removeEventListener('pointermove', onPointerMove);
  _handle.removeEventListener('pointerup', onPointerUp);
  _handle.removeEventListener('pointercancel', onPointerUp);
  _onResizeEnd?.(getWidth());
}

function setWidth(width) {
  _aside.style.width = `${clampWidth(width)}px`;
}

function getWidth() {
  return Math.round(_aside.getBoundingClientRect().width);
}

function clampWidth(width) {
  return Math.max(MIN_WIDTH, Math.min(MAX_WIDTH, Number(width) || MIN_WIDTH));
}
