import { create } from 'zustand'; export type SectionKind = 'movie' | 'show'; export type SectionTab = 'discover' | 'library' | 'collections'; export type Route = | { name: 'home' } | { name: 'section'; kind: SectionKind; tab: SectionTab } | { name: 'item'; id: string; title?: string } | { name: 'person'; id: string; title: string; thumb?: string } | { name: 'hub'; key: string; title: string } | { name: 'search'; query?: string } | { name: 'downloads' } | { name: 'settings'; mode: 'app' | 'server'; tab: string }; export interface Entry { id: number; route: Route; scroll: number; /** Per-screen state to restore on Back (e.g. selected season, library offset). */ state: Record; } interface RouterState { entries: Entry[]; index: number; current: Entry; navigate(route: Route, opts?: { replace?: boolean }): void; back(): void; forward(): void; canBack(): boolean; saveScroll(scroll: number): void; setState(patch: Record): void; reset(route: Route): void; } let nextId = 1; const entry = (route: Route): Entry => ({ id: nextId++, route, scroll: 0, state: {} }); const MAX = 60; const sameDestination = (a: Route, b: Route) => JSON.stringify(a) === JSON.stringify(b); export const useRouter = create((set, get) => { const first = entry({ name: 'home' }); return { entries: [first], index: 0, current: first, navigate(route, opts) { const { entries, index } = get(); if (sameDestination(entries[index].route, route)) return; const e = entry(route); let next = entries.slice(0, index + 1); if (opts?.replace) next[next.length - 1] = e; else next.push(e); if (next.length > MAX) next = next.slice(next.length - MAX); set({ entries: next, index: next.length - 1, current: e }); }, back() { const { entries, index } = get(); if (index > 0) set({ index: index - 1, current: entries[index - 1] }); }, forward() { const { entries, index } = get(); if (index < entries.length - 1) set({ index: index + 1, current: entries[index + 1] }); }, canBack: () => get().index > 0, saveScroll(scroll) { get().current.scroll = scroll; }, setState(patch) { const cur = get().current; cur.state = { ...cur.state, ...patch }; }, reset(route) { const e = entry(route); set({ entries: [e], index: 0, current: e }); }, }; }); export const navigate = (route: Route, opts?: { replace?: boolean }) => useRouter.getState().navigate(route, opts); export const goBack = () => useRouter.getState().back(); /** The top-level destination a route belongs to, for the navigation highlight. */ export function topLevel(route: Route): string { switch (route.name) { case 'home': return 'home'; case 'section': return route.kind === 'movie' ? 'movies' : 'shows'; case 'search': return 'search'; case 'downloads': return 'downloads'; case 'settings': return 'settings'; default: return ''; } }