import { defineStore } from 'pinia'
import { ref } from 'vue'

export interface TabItem {
  /** Unique key — route path for static routes, fullPath for dynamic */
  key: string
  title: string
  /** Full route path (used for navigation) */
  path: string
  closable: boolean
}

export const useTabsStore = defineStore('tabs', () => {
  const tabs = ref<TabItem[]>([
    { key: '/search', title: '文档检索', path: '/search', closable: false },
  ])
  const activeKey = ref('/search')

  function addTab(tab: { key: string; title: string; path: string; closable?: boolean }) {
    const existing = tabs.value.find(t => t.key === tab.key)
    if (existing) {
      // Update path (e.g. query params changed) and title
      existing.path = tab.path
      if (tab.title) existing.title = tab.title
    } else {
      tabs.value.push({
        key: tab.key,
        title: tab.title,
        path: tab.path,
        closable: tab.closable ?? true,
      })
    }
    activeKey.value = tab.key
  }

  /** Remove a tab. Returns the new activeKey for navigation. */
  function removeTab(targetKey: string): string | undefined {
    const idx = tabs.value.findIndex(t => t.key === targetKey)
    if (idx === -1) return undefined
    if (!tabs.value[idx].closable) return undefined

    tabs.value.splice(idx, 1)

    if (activeKey.value === targetKey) {
      const newIdx = Math.min(idx, tabs.value.length - 1)
      activeKey.value = tabs.value[newIdx]?.key || '/search'
    }
    return activeKey.value
  }

  function updateTabTitle(key: string, title: string) {
    const tab = tabs.value.find(t => t.key === key)
    if (tab) tab.title = title
  }

  return { tabs, activeKey, addTab, removeTab, updateTabTitle }
})
