import { defineStore } from 'pinia'

export interface WorkspaceTab {
  screenId: string
  path: string
  title: string
  pinned: boolean
  dirty: boolean
}

const MAX_VISIBLE_TABS = 10

function tabKey(screenId: string, path: string): string {
  return `${screenId}:${path}`
}

export const useWorkspaceStore = defineStore('ks-workspace', {
  state: () => ({ tabs: [] as WorkspaceTab[], activeKey: null as string | null }),
  getters: {
    visibleTabs: state => state.tabs.slice(0, MAX_VISIBLE_TABS),
    overflowTabs: state => state.tabs.slice(MAX_VISIBLE_TABS),
    overflowCount: state => Math.max(state.tabs.length - MAX_VISIBLE_TABS, 0)
  },
  actions: {
    /** 화면 진입 시 호출. 이미 열려 있으면 새 가상 상태를 만들지 않고 activeKey만 갱신한다. */
    open(screenId: string, path: string, title: string) {
      const key = tabKey(screenId, path)
      if (!this.tabs.some(tab => tabKey(tab.screenId, tab.path) === key)) {
        this.tabs.push({ screenId, path, title, pinned: false, dirty: false })
      }
      this.activeKey = key
    },
    /** dirty 여부와 무관하게 실제로 탭을 제거한다. dirty guard 확인은 호출자(KsWorkspaceTabs) 책임. */
    close(tab: WorkspaceTab) {
      const key = tabKey(tab.screenId, tab.path)
      this.tabs = this.tabs.filter(t => tabKey(t.screenId, t.path) !== key)
      if (this.activeKey === key) {
        const last = this.tabs.at(-1)
        this.activeKey = last ? tabKey(last.screenId, last.path) : null
      }
    },
    togglePin(tab: WorkspaceTab) {
      const found = this.tabs.find(t => t.screenId === tab.screenId && t.path === tab.path)
      if (found) found.pinned = !found.pinned
    },
    setDirty(screenId: string, path: string, dirty: boolean) {
      const found = this.tabs.find(t => t.screenId === screenId && t.path === path)
      if (found) found.dirty = dirty
    }
  }
})
