/**
 * Custom hook that synchronizes selected node/edge objects when the underlying
 * nodes or edges arrays change. Ensures the PropertyPanel always shows the
 * current state of the selected element.
 */
import { useEffect } from 'react';
import { useStore } from '../store/store';

export function useSelectionSync() {
  const nodes = useStore(state => state.nodes);
  const edges = useStore(state => state.edges);
  const selectedNode = useStore(state => state.selectedNode);
  const selectedEdge = useStore(state => state.selectedEdge);
  const setSelectedNode = useStore(state => state.setSelectedNode);
  const setSelectedEdge = useStore(state => state.setSelectedEdge);

  useEffect(() => {
    if (selectedNode) {
      const updatedNode = nodes.find(n => n.id === selectedNode.id);
      if (updatedNode && updatedNode !== selectedNode) {
        setSelectedNode(updatedNode);
      }
    }
    if (selectedEdge) {
      const updatedEdge = edges.find(e => e.id === selectedEdge.id);
      if (updatedEdge && updatedEdge !== selectedEdge) {
        setSelectedEdge(updatedEdge);
      }
    }
  }, [nodes, edges, selectedNode, selectedEdge, setSelectedNode, setSelectedEdge]);
}
