import { useEffect, useRef, useState } from 'react'
import type { TransformedGraph, ForceParams } from './types'

export function useForceLayout(graph: TransformedGraph | null, params: ForceParams) {
  const [positions, setPositions] = useState<Float32Array | null>(null)
  const [settled, setSettled] = useState(false)
  const workerRef = useRef<Worker | null>(null)

  useEffect(() => {
    if (!graph || graph.nodes.length === 0) {
      setPositions(null)
      setSettled(false)
      return
    }

    workerRef.current?.terminate()

    const worker = new Worker(
      new URL('./forceWorker.ts', import.meta.url),
      { type: 'module' },
    )
    workerRef.current = worker

    worker.onmessage = (e) => {
      if (e.data.type === 'positions') {
        setPositions(e.data.positions as Float32Array)
        if (e.data.settled) setSettled(true)
      }
    }

    const edgePairs: [number, number][] = graph.edges.map(e => [e.sourceIndex, e.targetIndex])

    worker.postMessage({
      type: 'init',
      nodeCount: graph.nodes.length,
      edges: edgePairs,
      params,
    })

    return () => {
      worker.postMessage({ type: 'stop' })
      worker.terminate()
      workerRef.current = null
    }
  }, [graph, params])

  return { positions, settled }
}
