import { create } from 'zustand' export interface AppTab { id: string type: 'book' | 'settings' name: string bookId?: string } interface TabState { openTabs: AppTab[] activeTabId: string | null openBookTab: (bookId: string, name: string) => void openSettingsTab: () => void switchTab: (tabId: string) => void closeTab: (tabId: string) => string | null } export const useTabStore = create((set, get) => ({ openTabs: [], activeTabId: null, openBookTab: (bookId, name) => { const existing = get().openTabs.find((t) => t.type === 'book' && t.bookId === bookId) if (existing) { set({ activeTabId: existing.id }) return } const id = `book-${bookId}` set((s) => ({ openTabs: [...s.openTabs, { id, type: 'book', name, bookId }], activeTabId: id })) }, openSettingsTab: () => { const existing = get().openTabs.find((t) => t.type === 'settings') if (existing) { set({ activeTabId: existing.id }) return } set((s) => ({ openTabs: [...s.openTabs, { id: 'settings', type: 'settings', name: '系统设置' }], activeTabId: 'settings' })) }, switchTab: (tabId) => set({ activeTabId: tabId }), closeTab: (tabId) => { const { openTabs, activeTabId } = get() const idx = openTabs.findIndex((t) => t.id === tabId) if (idx === -1) return activeTabId const nextTabs = openTabs.filter((t) => t.id !== tabId) let nextActive = activeTabId if (activeTabId === tabId) { nextActive = nextTabs[Math.max(0, idx - 1)]?.id ?? null } set({ openTabs: nextTabs, activeTabId: nextActive }) return nextActive } }))