import { defineTrait } from '../define.js';

const EDGE_SIZE = 8;
const EDGES = ['top', 'right', 'bottom', 'left'];

export const resizable = defineTrait({
  name: 'resizable',
  category: 'motion-positioning',
  description: 'Drag edges/corners to resize',
  attributes: ['data-resizable-resizing', 'data-resizable-edge'],
  events: ['resize-end'],
  config: [],
  setup({ host }) {
    let resizing = false;
    let activeEdge = null;
    let startX = 0;
    let startY = 0;
    let startWidth = 0;
    let startHeight = 0;
    let startLeft = 0;
    let startTop = 0;
    const handles = [];

    // Ensure host is positioned
    const pos = getComputedStyle(host).position;
    if (pos === 'static') {
      host.style.position = 'relative';
    }

    for (const edge of EDGES) {
      const handle = document.createElement('div');
      handle.dataset.resizableHandle = edge;
      Object.assign(handle.style, {
        position: 'absolute',
        zIndex: '9999',
        ...(edge === 'top' && { top: '0', left: '0', right: '0', height: `${EDGE_SIZE}px`, cursor: 'ns-resize' }),
        ...(edge === 'bottom' && { bottom: '0', left: '0', right: '0', height: `${EDGE_SIZE}px`, cursor: 'ns-resize' }),
        ...(edge === 'left' && { top: '0', bottom: '0', left: '0', width: `${EDGE_SIZE}px`, cursor: 'ew-resize' }),
        ...(edge === 'right' && { top: '0', bottom: '0', right: '0', width: `${EDGE_SIZE}px`, cursor: 'ew-resize' }),
      });

      handle.addEventListener('pointerdown', (e) => {
        e.stopPropagation();
        resizing = true;
        activeEdge = edge;
        startX = e.clientX;
        startY = e.clientY;
        const rect = host.getBoundingClientRect();
        startWidth = rect.width;
        startHeight = rect.height;
        startLeft = rect.left;
        startTop = rect.top;

        handle.setPointerCapture(e.pointerId);
        host.setAttribute('data-resizable-resizing', '');
        host.setAttribute('data-resizable-edge', edge);
      });

      handle.addEventListener('pointermove', (e) => {
        if (!resizing || activeEdge !== edge) return;
        const dx = e.clientX - startX;
        const dy = e.clientY - startY;

        if (edge === 'right') {
          host.style.width = `${Math.max(0, startWidth + dx)}px`;
        } else if (edge === 'left') {
          host.style.width = `${Math.max(0, startWidth - dx)}px`;
        } else if (edge === 'bottom') {
          host.style.height = `${Math.max(0, startHeight + dy)}px`;
        } else if (edge === 'top') {
          host.style.height = `${Math.max(0, startHeight - dy)}px`;
        }
      });

      handle.addEventListener('pointerup', () => {
        if (!resizing || activeEdge !== edge) return;
        resizing = false;
        activeEdge = null;
        host.removeAttribute('data-resizable-resizing');
        host.removeAttribute('data-resizable-edge');

        const rect = host.getBoundingClientRect();
        host.dispatchEvent(new CustomEvent('resize-end', {
          bubbles: true,
          detail: { width: rect.width, height: rect.height },
        }));
      });

      handles.push(handle);
      host.appendChild(handle);
    }

    return () => {
      for (const handle of handles) {
        handle.remove();
      }
      handles.length = 0;
      host.removeAttribute('data-resizable-resizing');
      host.removeAttribute('data-resizable-edge');
    };
  },
});
