import { reactive } from 'vue'
import type { ProjectRecord, TaskRecord, IdeaRecord, WorkflowRecord, WorkflowEventPayload } from '../../api/types'

/** 待审批请求(由 human_approval_request 事件填充) */
export interface PendingApproval {
  execution_id: string
  node_id: string
  title: string
  description: string
  options: string[]
  /** F-260615-01: single(缺省)/multiple */
  select_type?: 'single' | 'multiple'
}

// ── 全局响应式状态(单例,四子 store 共享同一份) ──
export const state = reactive({
  projects: [] as ProjectRecord[],
  deletedProjects: [] as ProjectRecord[],
  tasks: [] as TaskRecord[],
  // 统计缓存,与 tasks 数组解耦,供 Dashboard,不被 Tasks 分页/筛选污染(P1-b A0)
  activeTaskCount: 0 as number,
  projectTaskCounts: {} as Record<string, number>,
  ideas: [] as IdeaRecord[],
  workflowExecutions: [] as WorkflowRecord[],
  liveEvents: [] as Array<WorkflowEventPayload & { _ts: number }>,
  pendingApproval: null as PendingApproval | null,
  loading: false,
  error: null as string | null,
})

/** 清除错误状态(供 toast 显示后重置,允许连续同值错误再次触发 watch) */
export function clearError() { state.error = null }

/** 工作流事件监听 unlisten 句柄(单例,workflow 子 store 读写) */
export let _eventUnlisten: (() => void) | null = null

/** 内部重置 unlisten 句柄(workflow 子 store stopEventListener/startEventListener 用) */
export function setEventUnlisten(fn: (() => void) | null) {
  _eventUnlisten = fn
}
