import { useState, useMemo, useCallback } from 'react'
import type { TransformedGraph, HoverState, GraphNode3D } from './types'

export function useGraphInteraction(graph: TransformedGraph | null) {
  const [hovered, setHovered] = useState<HoverState | null>(null)
  const [selected, setSelected] = useState<number | null>(null)

  // Build adjacency for neighbor highlighting
  const adjacency = useMemo(() => {
    if (!graph) return new Map<number, Set<number>>()
    const adj = new Map<number, Set<number>>()
    for (const e of graph.edges) {
      if (!adj.has(e.sourceIndex)) adj.set(e.sourceIndex, new Set())
      if (!adj.has(e.targetIndex)) adj.set(e.targetIndex, new Set())
      adj.get(e.sourceIndex)!.add(e.targetIndex)
      adj.get(e.targetIndex)!.add(e.sourceIndex)
    }
    return adj
  }, [graph])

  const highlightSet = useMemo(() => {
    const idx = hovered?.nodeIndex ?? selected
    if (idx == null) return null
    const set = new Set<number>([idx])
    const neighbors = adjacency.get(idx)
    if (neighbors) neighbors.forEach(n => set.add(n))
    return set
  }, [hovered, selected, adjacency])

  const onHover = useCallback((index: number | null, node: GraphNode3D | null, position: [number, number, number] | null) => {
    if (index == null || node == null || position == null) {
      setHovered(null)
    } else {
      setHovered({ nodeIndex: index, node, position })
    }
  }, [])

  const onClick = useCallback((index: number | null) => {
    setSelected(prev => prev === index ? null : index)
  }, [])

  return { hovered, selected, highlightSet, onHover, onClick }
}
