"use client";

import { useCallback } from "react";

import { cn } from "@/lib/utils";

interface ResizableStudioPanelProps {
  width: number;
  onWidthChange: (width: number) => void;
  side: "left" | "right";
  children: React.ReactNode;
  className?: string;
}

export function ResizableStudioPanel({
  width,
  onWidthChange,
  side,
  children,
  className,
}: ResizableStudioPanelProps) {
  const minWidth = side === "left" ? 180 : 200;
  const maxWidth = side === "left" ? 400 : 420;

  const startDrag = useCallback(
    (e: React.MouseEvent) => {
      e.preventDefault();
      const startX = e.clientX;
      const startWidth = width;

      const onMouseMove = (ev: MouseEvent) => {
        // Right panel: drag left = wider, drag right = narrower
        // Left panel: drag right = wider, drag left = narrower
        const delta =
          side === "right"
            ? startX - ev.clientX
            : ev.clientX - startX;
        const next = Math.min(maxWidth, Math.max(minWidth, startWidth + delta));
        onWidthChange(next);
      };

      const onMouseUp = () => {
        window.removeEventListener("mousemove", onMouseMove);
        window.removeEventListener("mouseup", onMouseUp);
      };

      window.addEventListener("mousemove", onMouseMove);
      window.addEventListener("mouseup", onMouseUp);
    },
    [width, side, minWidth, maxWidth, onWidthChange]
  );

  return (
    <div
      style={{ width }}
      className={cn(
        "relative flex shrink-0 flex-col overflow-hidden border-gray-200 bg-white",
        side === "left" ? "border-r" : "border-l",
        className
      )}
    >
      {/* Drag handle — left edge for right panel, right edge for left panel */}
      <div
        aria-hidden
        onMouseDown={startDrag}
        className={cn(
          "absolute top-0 z-20 h-full w-1.5 cursor-col-resize transition-colors hover:bg-blue-400/30 active:bg-blue-500/40",
          side === "right" ? "left-0" : "right-0"
        )}
      />
      {children}
    </div>
  );
}
