import { ref } from 'vue'
import type { AgentNodeData } from './useFlowLayout'

interface FlowBoardAgentStore {
  agents: AgentNodeData[]
  models: Array<{ id: string; alias: string }>
  changeModel: (agentId: string, modelId: string) => void
  selectAgent: (id: string | null) => void
}

const STORAGE_KEY = 'nexus-flow-positions'

function readStoredPositions() {
  if (typeof window === 'undefined') return {}
  try {
    const raw = window.localStorage.getItem(STORAGE_KEY)
    return raw ? JSON.parse(raw) as Record<string, { x: number; y: number }> : {}
  } catch {
    return {}
  }
}

export function useFlowBoardState(agentStore: FlowBoardAgentStore) {
  const agentPositions = ref<Record<string, { x: number; y: number }>>(readStoredPositions())
  const enteringIds = ref<string[]>([])

  function selectAgent(id: string) {
    agentStore.selectAgent(id)
  }

  function closeAgent() {
    agentStore.selectAgent(null)
  }

  function changeModel(agentId: string, modelAlias: string) {
    const model = agentStore.models.find(m => m.alias === modelAlias)
    const modelId = model?.id ?? modelAlias
    agentStore.changeModel(agentId, modelId)
  }

  function resetLayout() {
    agentPositions.value = {}
    if (typeof window !== 'undefined') window.localStorage.removeItem(STORAGE_KEY)
  }

  function updatePositions(positions: Record<string, { x: number; y: number }>) {
    agentPositions.value = { ...positions }
    if (typeof window !== 'undefined') {
      window.localStorage.setItem(STORAGE_KEY, JSON.stringify(agentPositions.value))
    }
  }

  return {
    agentPositions,
    changeModel,
    closeAgent,
    enteringIds,
    resetLayout,
    selectAgent,
    updatePositions,
  }
}
