import type { TabItem, MenuItem } from '../types.uts'

export function makeTabFromPath(menuList: MenuItem[], path: string): TabItem {
  // path 可能带 query；用于 tab 的 id 也要稳定
  const pure = path.split('?')[0]

  // 先找子页面
  for (const m of menuList) {
    const groups = m.groups || []
    for (const g of groups) {
      for (const c of g.children) {
        if (c.path.split('?')[0] === pure) {
          return { id: c.id, title: c.title, path: c.path }
        }
      }
    }
    if (m.path.split('?')[0] === pure) {
      return { id: m.id, title: m.title, path: m.path }
    }
  }
  // 找不到就兜底
  return { id: pure, title: '页面', path }
}

export function upsertTab(tabs: TabItem[], tab: TabItem): TabItem[] {
  const idx = tabs.findIndex(t => t.id === tab.id)
  if (idx >= 0) return tabs
  return [...tabs, tab]
}

export function removeTab(tabs: TabItem[], tabId: string): TabItem[] {
  return tabs.filter(t => t.id !== tabId)
}
