const STORAGE_KEY = 'pena.sidebarWidth';
const MIN_WIDTH = 180;
const MAX_WIDTH = 520;

function clamp(width) {
  return Math.min(MAX_WIDTH, Math.max(MIN_WIDTH, width));
}

function applyWidth(width) {
  document.documentElement.style.setProperty('--sidebar-width', `${width}px`);
}

export function initSidebarResize() {
  const handle = document.getElementById('sidebar-resizer');
  if (!handle) return;

  const stored = parseInt(localStorage.getItem(STORAGE_KEY), 10);
  if (!Number.isNaN(stored)) applyWidth(clamp(stored));

  let dragging = false;

  const onMove = (e) => {
    if (!dragging) return;
    applyWidth(clamp(e.clientX));
  };

  const onUp = () => {
    if (!dragging) return;
    dragging = false;
    handle.classList.remove('is-dragging');
    document.body.classList.remove('is-resizing-sidebar');
    const width = parseInt(
      getComputedStyle(document.documentElement).getPropertyValue('--sidebar-width'),
      10,
    );
    if (!Number.isNaN(width)) localStorage.setItem(STORAGE_KEY, String(width));
    window.removeEventListener('mousemove', onMove);
    window.removeEventListener('mouseup', onUp);
  };

  handle.addEventListener('mousedown', (e) => {
    e.preventDefault();
    dragging = true;
    handle.classList.add('is-dragging');
    document.body.classList.add('is-resizing-sidebar');
    window.addEventListener('mousemove', onMove);
    window.addEventListener('mouseup', onUp);
  });
}
