import { createContext, useContext, useCallback, useState, ReactNode } from 'react'

interface TabsCtx {
  kept:        ReadonlySet<string>
  keepRoute:   (r: string) => void
  forgetRoute: (r: string) => void
}

const Ctx = createContext<TabsCtx>({
  kept: new Set(),
  keepRoute:   () => {},
  forgetRoute: () => {},
})

export function TabsProvider({ children }: { children: ReactNode }) {
  const [kept, setKept] = useState<Set<string>>(new Set())

  const keepRoute = useCallback((r: string) =>
    setKept(p => p.has(r) ? p : new Set([...p, r])), [])

  const forgetRoute = useCallback((r: string) =>
    setKept(p => { const n = new Set(p); n.delete(r); return n }), [])

  return <Ctx.Provider value={{ kept, keepRoute, forgetRoute }}>{children}</Ctx.Provider>
}

export const useTabs = () => useContext(Ctx)
