import { computed } from 'vue'
import { useEditorStore } from '../stores/editorStore'
import { computeEdges, computeSceneNodes } from '../services/GraphService'

export function useGraphEditor() {
  const store = useEditorStore()

  const sceneNodes = computed(() => computeSceneNodes(store.gameData))
  const sceneEdges = computed(() => computeEdges(store.gameData))
  const sceneList = computed(() => computeSceneNodes(store.gameData))

  function onAddEdge(source: string, target: string) {
    const scene = store.gameData.scenes[source]
    if (!scene) return
    const newChoices = [...(scene.choices || []), { text: `${source} → ${target}`, targetScene: target }]
    store.gameData = {
      ...store.gameData,
      scenes: { ...store.gameData.scenes, [source]: { ...scene, choices: newChoices } },
    }
    store.markDirty()
  }

  return {
    gameData: store.gameData,
    selectedNodeId: store.selectedNodeId,
    selectedScene: store.selectedScene,
    startSceneId: store.startSceneId,
    sceneNodes,
    sceneEdges,
    sceneList,
    loadJSON: store.loadJSON,
    exportJSON: store.exportJSON,
    updateScene: store.updateScene,
    addChoice: store.addChoice,
    updateChoice: store.updateChoice,
    deleteChoice: store.deleteChoice,
    addScene: store.addScene,
    deleteScene: store.deleteScene,
    onAddEdge,
  }
}
