window.cfxSplitter = (() => {
  let nativeCursor = 'default';
  let _dotNetRef = null;

  function setNativeCursor(cursor, force) {
    if (!force && cursor === nativeCursor) return;
    nativeCursor = cursor;
    if (_dotNetRef) {
      _dotNetRef.invokeMethodAsync('SetNativeCursor', cursor).catch(() => {});
    }
  }

  function splitterCursor(type) {
    return type === 'bottom' ? 'ns-resize' : 'ew-resize';
  }

  function attach(dotNetRef, hostSelector) {
    _dotNetRef = dotNetRef;
    const host = document.querySelector(hostSelector);
    if (!host) return;

    let dragging = null;

    function onPointerMove(e) {
      if (!dragging) return;
      const { type } = dragging;
      const rect = host.getBoundingClientRect();

      if (type === 'left') {
        const px = e.clientX - rect.left;
        dotNetRef.invokeMethodAsync('SetLeftWidth', px);
      } else if (type === 'right') {
        const px = rect.right - e.clientX;
        dotNetRef.invokeMethodAsync('SetRightWidth', px);
      } else if (type === 'bottom') {
        const px = rect.bottom - e.clientY;
        dotNetRef.invokeMethodAsync('SetBottomHeight', px);
      }
    }

    function stop() {
      if (!dragging) return;
      dragging = null;
      document.body.classList.remove('cfx-noselect', 'cfx-drag-col', 'cfx-drag-row');
      setNativeCursor('default');
      window.removeEventListener('pointermove', onPointerMove, true);
      window.removeEventListener('pointerup', stop, true);
      window.removeEventListener('pointercancel', stop, true);
    }

    host.addEventListener('pointerover', (e) => {
      if (dragging) return;
      const el = e.target;
      if (!(el instanceof HTMLElement)) return;
      const splitter = el.closest('[data-cfx-splitter]');
      if (splitter) {
        setNativeCursor(splitterCursor(splitter.getAttribute('data-cfx-splitter')), true);
      }
    });

    host.addEventListener('pointerout', (e) => {
      if (dragging) return;
      const el = e.target;
      if (!(el instanceof HTMLElement)) return;
      if (el.closest('[data-cfx-splitter]')) {
        setNativeCursor('default', true);
      }
    });

    host.addEventListener('pointerdown', (e) => {
      const el = e.target;
      if (!(el instanceof HTMLElement)) return;
      const splitter = el.closest('[data-cfx-splitter]');
      if (!splitter) return;

      const type = splitter.getAttribute('data-cfx-splitter');
      if (!type) return;

      dragging = { type };
      document.body.classList.add('cfx-noselect');
      document.body.classList.add(type === 'bottom' ? 'cfx-drag-row' : 'cfx-drag-col');
      setNativeCursor(splitterCursor(type));
      window.addEventListener('pointermove', onPointerMove, true);
      window.addEventListener('pointerup', stop, true);
      window.addEventListener('pointercancel', stop, true);
      e.preventDefault();
      e.stopPropagation();
    });
  }

  return { attach };
})();
