import { useEffect, useRef } from 'react';
import { useReactFlow } from '@xyflow/react';

interface UseViewportControllerProps {
  sidebarOpen: boolean;
  nodeCount: number;
}

/**
 * Hook for handling viewport re-centering when sidebar opens/closes.
 * Adjusts the viewport x-offset to keep the canvas centered.
 *
 * Must be used inside ReactFlow context.
 */
export function useViewportController({
  sidebarOpen,
  nodeCount,
}: UseViewportControllerProps): void {
  const { getViewport, setViewport } = useReactFlow();
  const prevSidebarOpen = useRef(sidebarOpen);

  useEffect(() => {
    if (prevSidebarOpen.current === sidebarOpen) return;
    prevSidebarOpen.current = sidebarOpen;

    if (nodeCount === 0) return;

    const currentViewport = getViewport();
    const sidebarWidth = 576;
    const xOffset = sidebarOpen ? -sidebarWidth / 2 : sidebarWidth / 2;

    const timeoutId = setTimeout(() => {
      setViewport(
        { x: currentViewport.x + xOffset, y: currentViewport.y, zoom: currentViewport.zoom },
        { duration: 300 },
      );
    }, 50);

    return () => clearTimeout(timeoutId);
  }, [sidebarOpen, nodeCount, getViewport, setViewport]);
}

/**
 * Component wrapper for useViewportController.
 * Renders null but handles viewport adjustments.
 */
export function ViewportController({ sidebarOpen, nodeCount }: UseViewportControllerProps): null {
  useViewportController({ sidebarOpen, nodeCount });
  return null;
}
