import { computed, ref } from 'vue'
import type { ReflectionObject, ReflectionKind } from '@/api/reflection'

/**
 * 编辑器内的多选集合 + 类型过滤工具。
 * 选中集是 `(kind, id)` 二元组集合：用 `${kind}:${id}` 作 key 去重。
 *
 * 与 SimpleLite 后端的同步：单选时把 selection 同步给 ReflectionApi（高亮 3D 场景），
 * 多选不同步（高亮不展开是因为反射 API 当前只支持单选；如需多选高亮以后再扩展）。
 */

export interface SelectionItem extends ReflectionObject {
  kind: ReflectionKind
}

function keyOf(kind: string, id: number) {
  return `${kind}:${id}`
}

export function useSelection() {
  const items = ref<SelectionItem[]>([])
  const lastClickedKey = ref<string | null>(null)

  const ids = computed(() => items.value.map((x) => x.id))
  const count = computed(() => items.value.length)

  function has(kind: string, id: number) {
    const k = keyOf(kind, id)
    return items.value.some((x) => keyOf(x.kind, x.id) === k)
  }

  function add(item: SelectionItem) {
    if (has(item.kind, item.id)) return
    items.value = [...items.value, item]
    lastClickedKey.value = keyOf(item.kind, item.id)
  }

  function remove(kind: string, id: number) {
    const k = keyOf(kind, id)
    items.value = items.value.filter((x) => keyOf(x.kind, x.id) !== k)
    if (lastClickedKey.value === k) lastClickedKey.value = null
  }

  function toggle(item: SelectionItem) {
    if (has(item.kind, item.id)) remove(item.kind, item.id)
    else add(item)
  }

  function set(list: SelectionItem[]) {
    items.value = list
    lastClickedKey.value = list.length > 0 ? keyOf(list[list.length - 1]!.kind, list[list.length - 1]!.id) : null
  }

  function clear() {
    items.value = []
    lastClickedKey.value = null
  }

  /** 按类型过滤当前选中：用于「按类型选」工具，例如只保留 site 子集。 */
  function filterByKind(kind: string) {
    items.value = items.value.filter((x) => x.kind === kind)
  }

  /** 单选 - 替换；适合 single-pick 工具点击时使用。 */
  function selectSingle(item: SelectionItem) {
    items.value = [item]
    lastClickedKey.value = keyOf(item.kind, item.id)
  }

  return {
    items,
    ids,
    count,
    lastClickedKey,
    has,
    add,
    remove,
    toggle,
    set,
    clear,
    filterByKind,
    selectSingle
  }
}
