export function initCellResize(
  el: HTMLElement,
  ev: PointerEvent,
  downXRef: { value: number },
  startWRef: { value: number }
) {
  ev.preventDefault();
  ev.stopPropagation();

  const cStart = Number(el.dataset.cStart);
  if (!cStart) return null;

  const span = Number(el.getAttribute('colspan')) || 1;
  const col = Math.max(0, cStart + span - 1 - 1);

  downXRef.value = ev.clientX;
  startWRef.value = el.getBoundingClientRect().width;

  const target = ev.currentTarget as HTMLElement;
  target.setPointerCapture(ev.pointerId);

  el.dispatchEvent(
    new CustomEvent('nile-column-resize', {
      detail: { col, widthPx: startWRef.value },
      bubbles: true,
      composed: true,
    })
  );

  el.dispatchEvent(
    new CustomEvent('nile-resize-start', { bubbles: true, composed: true })
  );

  return { target, col };
}

export function cellResizeMove(
  el: HTMLElement,
  col: number,
  startW: number,
  downX: number,
  e: PointerEvent
) {
  const widthPx = Math.max(40, Math.round(startW + (e.clientX - downX)));
  el.dispatchEvent(
    new CustomEvent('nile-column-resize', {
      detail: { col, widthPx },
      bubbles: true,
      composed: true,
    })
  );
}

export function cellResizeDone(
  el: HTMLElement,
  col: number,
  ev: PointerEvent,
  target: HTMLElement,
  move: (e: PointerEvent) => void
) {
  target.releasePointerCapture(ev.pointerId);
  target.removeEventListener('pointermove', move);
  el.dispatchEvent(
    new CustomEvent('nile-resize-end', { bubbles: true, composed: true, detail: { col: col } })
  );
}
