import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
import { createContext, useState, useRef, useLayoutEffect, useCallback, useMemo } from 'react';
import { cn } from '../../../../lib/utils.mjs';
import { GripVertical } from 'lucide-react';
import { useDrag } from '../../../../../../../node_modules/.pnpm/@use-gesture_react@10.3.1_react@19.2.0/node_modules/@use-gesture/react/dist/use-gesture-react.esm.mjs';

const RESPONSIVE_DEFAULT_SIZE = 800;
const ResizableWrapper = ({
  children,
  isResizable,
  onDraggingChange,
  onSizeChange
}) => {
  const [dragging, setDragging] = useState(false);
  const [responsiveSize, setResponsiveSize] = useState(null);
  const initialSizeRef = useRef({ width: 0, height: 0 });
  useLayoutEffect(() => {
    if (isResizable) {
      const initialWidth = RESPONSIVE_DEFAULT_SIZE;
      const initialHeight = RESPONSIVE_DEFAULT_SIZE;
      setResponsiveSize({ width: initialWidth, height: initialHeight });
      onSizeChange?.(initialWidth, initialHeight);
    }
  }, [isResizable, onSizeChange]);
  const handleSetDragging = useCallback(
    (value) => {
      setDragging(value);
      onDraggingChange?.(value);
    },
    [onDraggingChange]
  );
  const horizontalDragConfig = useMemo(() => {
    return {
      axis: "x",
      from: () => [0, 0],
      filterTaps: true
    };
  }, []);
  const verticalDragConfig = useMemo(() => {
    return {
      axis: "y",
      from: () => [0, 0],
      filterTaps: true
    };
  }, []);
  const bindHorizontalResizer = useDrag(({ down, movement: [mx], first, last }) => {
    if (first) {
      initialSizeRef.current = {
        width: responsiveSize?.width || RESPONSIVE_DEFAULT_SIZE,
        height: responsiveSize?.height || RESPONSIVE_DEFAULT_SIZE
      };
      handleSetDragging(true);
    }
    if (down) {
      const newWidth = Math.max(320, initialSizeRef.current.width + mx);
      const newHeight = initialSizeRef.current.height;
      setResponsiveSize({ width: newWidth, height: newHeight });
      onSizeChange?.(newWidth, newHeight);
    }
    if (last) {
      setTimeout(() => {
        handleSetDragging(false);
      }, 0);
    }
  }, horizontalDragConfig);
  const bindVerticalResizer = useDrag(({ down, movement: [, my], first, last }) => {
    if (first) {
      initialSizeRef.current = {
        width: responsiveSize?.width || RESPONSIVE_DEFAULT_SIZE,
        height: responsiveSize?.height || RESPONSIVE_DEFAULT_SIZE
      };
      handleSetDragging(true);
    }
    if (down) {
      const newWidth = initialSizeRef.current.width;
      const newHeight = Math.max(200, initialSizeRef.current.height + my);
      setResponsiveSize({ width: newWidth, height: newHeight });
      onSizeChange?.(newWidth, newHeight);
    }
    if (last) {
      setTimeout(() => {
        handleSetDragging(false);
      }, 0);
    }
  }, verticalDragConfig);
  const bindHorizontalResizerValues = useMemo(() => {
    return typeof bindHorizontalResizer === "function" ? bindHorizontalResizer() : {};
  }, [bindHorizontalResizer]);
  const bindVerticalResizerValues = useMemo(() => {
    return typeof bindVerticalResizer === "function" ? bindVerticalResizer() : {};
  }, [bindVerticalResizer]);
  const responsiveStyle = useMemo(() => {
    if (isResizable && responsiveSize) {
      return {
        width: `${responsiveSize.width}px`,
        height: `${responsiveSize.height}px`
      };
    }
    return { width: "100%" };
  }, [isResizable, responsiveSize]);
  const contextValue = useMemo(() => ({
    dragging,
    setDragging: handleSetDragging
  }), [dragging, handleSetDragging]);
  return /* @__PURE__ */ jsx(
    DragHandleContext.Provider,
    {
      value: contextValue,
      children: /* @__PURE__ */ jsxs("div", { className: "relative", style: responsiveStyle, children: [
        isResizable && /* @__PURE__ */ jsxs(Fragment, { children: [
          /* @__PURE__ */ jsx(
            Resizer,
            {
              ...bindHorizontalResizerValues,
              className: "absolute top-1/2 right-[-20px] -translate-y-1/2",
              children: /* @__PURE__ */ jsx(GripVertical, { className: "w-4 h-4" })
            }
          ),
          /* @__PURE__ */ jsx(
            Resizer,
            {
              ...bindVerticalResizerValues,
              className: "absolute bottom-[-20px] left-1/2 -translate-x-1/2 cursor-ns-resize",
              children: /* @__PURE__ */ jsx(GripVertical, { className: "w-4 h-4 rotate-90" })
            }
          )
        ] }),
        children
      ] })
    }
  );
};
const DragHandleContext = createContext({ dragging: false, setDragging: () => {
} });
const Resizer = ({
  className,
  children,
  ...props
}) => {
  const handleMouseDown = useCallback((e) => {
    e.stopPropagation();
    e.preventDefault();
  }, []);
  const handleTouchStart = useCallback(
    (e) => {
      e.stopPropagation();
    },
    []
  );
  return /* @__PURE__ */ jsx(
    "div",
    {
      "data-testid": "resizer",
      onMouseDown: handleMouseDown,
      onTouchStart: handleTouchStart,
      className: cn(
        "flex items-center justify-center w-4 h-4 rounded-sm border bg-border hover:bg-muted touch-none z-[1001]",
        // Default cursor is ew-resize, but can be overridden by className
        !className?.includes("cursor-") && "cursor-ew-resize",
        className
      ),
      ...props,
      children
    }
  );
};

export { DragHandleContext, ResizableWrapper };
