From 34481422428beb3d95fc0c134eea6713c48ffe4e Mon Sep 17 00:00:00 2001 From: Mohammed Abad Date: Mon, 4 May 2026 08:33:27 +0100 Subject: [PATCH] feat(frontend): add Spotlight-style command palette with recent tracking MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Add CommandPalette component with keyboard navigation (arrows, Enter, Shift+Enter, Esc) - Add useCommandPaletteStore Zustand store with localStorage-persisted recently viewed - Show two distinct sections: Library results and TMDB Results (no duplicates) - Exclude library entries from TMDB Results section by TMDB ID index - Add "View all" links: Library section → /library, TMDB section → /search - Persist non-library TMDB entries in localStorage for recently viewed support - Register global Ctrl+P / Cmd+P / slash shortcuts in AppLayout - Track entry visits in EntryDetailsPage for recently viewed - Track TMDB preview visits in TmdbPreviewPage for recently viewed - Updated related docs files Co-authored-by: Copilot --- docs-vault/Components.md | 55 +- docs-vault/Frontend.md | 2 +- docs-vault/Navigation.md | 17 + docs-vault/Stores.md | 41 ++ .../src/components/CommandPalette.tsx | 494 ++++++++++++++++++ .../src/components/layout/AppLayout.tsx | 29 + react_frontend/src/pages/EntryDetailsPage.tsx | 18 +- react_frontend/src/pages/TmdbPreviewPage.tsx | 17 + .../src/stores/useCommandPaletteStore.ts | 40 ++ 9 files changed, 710 insertions(+), 3 deletions(-) create mode 100644 react_frontend/src/components/CommandPalette.tsx create mode 100644 react_frontend/src/stores/useCommandPaletteStore.ts diff --git a/docs-vault/Components.md b/docs-vault/Components.md index 6cb62a4..1dc2f08 100644 --- a/docs-vault/Components.md +++ b/docs-vault/Components.md @@ -16,8 +16,10 @@ All in `react_frontend/src/components/`. Organized by domain. | Component | File | Description | |---|---|---| -| `AppLayout` | `layout/AppLayout.tsx` | Root layout with Sidebar + main area | +| `AppLayout` | `layout/AppLayout.tsx` | Root layout with Sidebar + main area; registers global `Ctrl+P` / `/` shortcut for the command palette | | `Sidebar` | `layout/Sidebar.tsx` | Left navigation sidebar | +| `TitleBar` | `layout/TitleBar.tsx` | Custom frameless title bar (Electron only) | +| `CommandPalette` | `CommandPalette.tsx` | Spotlight-style command palette — see [[Search#Command Palette]] | ## Entry Components @@ -74,6 +76,57 @@ See [[Statistics]] for data details. `HomeSkeleton`, `LibrarySkeleton`, `WatchlistSkeleton`, `DashboardSkeleton`, `CollectionsSkeleton`, `CollectionDetailsSkeleton`, `MediaSkeleton`, `CalendarSkeleton`, `EntryDetailsSkeleton`, `SeasonSkeleton`, `EpisodeSkeleton`, `PeopleSkeleton`, `PersonDetailsSkeleton`, `SettingsSkeleton` +## Command Palette + +> [!info] File: `components/CommandPalette.tsx` + +Spotlight / Raycast-style command palette rendered at root level inside `AppLayout`. + +### Trigger + +| Shortcut | Condition | +|---|---| +| `Ctrl+P` / `Cmd+P` | Always | +| `/` | When focus is not on an input or textarea | + +### Sections (when searching) + +| Section | Source | Behaviour | +|---|---|---| +| Quick Actions / Commands | Static list | Navigation commands (Library, Watchlist, Stats, Calendar, People, Settings, Favorites) | +| Library | [[Stores\|useLibraryStore]] | Client-side fuzzy search — results appear instantly | +| TMDB Results | `tmdbApi.search()` (debounced 250 ms) | Entries already in library are **fully excluded** | + +**View all links:** +- Library → `/library?search=` +- TMDB Results → `/search?q=` + +### Recently Viewed (empty query) + +Shown when the search input is empty. Populated by: +- `EntryDetailsPage` on mount → saves library entry with `id: "lib-{id}"` +- `TmdbPreviewPage` on mount → saves TMDB-only entry with `id: "tmdb-{tmdbId}"` + +Persisted to `localStorage` via [[Stores\|useCommandPaletteStore]]. + +### Keyboard Navigation + +| Key | Action | +|---|---| +| `↑` / `↓` | Move selection | +| `Enter` | Open selected item | +| `Shift+Enter` | Quick-add to library (TMDB items only) | +| `Esc` | Close palette | + +### Selection Behaviour + +- **Command** → navigate to route +- **Library item** → navigate to `/entry/:id` +- **TMDB item (Enter)** → navigate to `/entry/tmdb/:type/:tmdbId` (preview) +- **TMDB item (Shift+Enter)** → `useCreateEntry` mutation, then navigate to new entry + +--- + ## UI Primitives (shadcn/ui) Base components from shadcn/ui in `components/ui/`: diff --git a/docs-vault/Frontend.md b/docs-vault/Frontend.md index 3905796..e56b93b 100644 --- a/docs-vault/Frontend.md +++ b/docs-vault/Frontend.md @@ -81,7 +81,7 @@ react_frontend/src/ │ ├── normalizers.ts → [[Normalizers]] │ └── utils.ts → cn() helper ├── pages/ → [[Pages]] (17 route pages) -├── stores/ → [[Stores]] (2 Zustand stores) +├── stores/ → [[Stores]] (3 Zustand stores) └── types/ → [[Types]] (TypeScript interfaces) ``` diff --git a/docs-vault/Navigation.md b/docs-vault/Navigation.md index 0ce8d44..c152b24 100644 --- a/docs-vault/Navigation.md +++ b/docs-vault/Navigation.md @@ -74,7 +74,24 @@ Detail pages use `mx-auto max-w-4xl` for consistent max width: /entry/:id/season/:seasonId/episode/:episodeId → EpisodePage (episode detail) ``` +## Command Palette + +A global Spotlight-style command palette (`Ctrl+P` / `/`) is available on every page. See [[Components#Command Palette]] for full details. + +### Quick navigation commands + +| Command | Destination | +|---|---| +| Go to Library | `/library` | +| Go to Watchlist | `/watchlist` | +| Go to Statistics | `/dashboard` | +| Go to Calendar | `/calendar` | +| Go to People | `/people` | +| Go to Settings | `/settings` | +| Go to Favorites | `/library?filter=favorites` | + ## See Also - [[Routing]] — All routes - [[Pages]] — Page components +- [[Components#Command Palette]] — Palette implementation details diff --git a/docs-vault/Stores.md b/docs-vault/Stores.md index 1f236bc..3c279fd 100644 --- a/docs-vault/Stores.md +++ b/docs-vault/Stores.md @@ -99,6 +99,47 @@ Uses Zustand `persist` middleware: --- +## useCommandPaletteStore + +> [!info] File: `stores/useCommandPaletteStore.ts` + +Manages [[Components#Command Palette|CommandPalette]] open/close state and recently viewed history. + +### State + +| Field | Type | Description | +|---|---|---| +| `isOpen` | `boolean` | Whether the palette is currently visible | +| `recentlyViewed` | `RecentItem[]` | Up to 10 recently visited entries (library + TMDB-only) | + +### RecentItem Shape + +```typescript +interface RecentItem { + id: string; // "lib-{id}" or "tmdb-{tmdbId}" + title: string; + type: 'movie' | 'tv'; + poster_path: string | null; + libraryId?: number; // set for library entries + tmdbId?: number; // set for TMDB or library entries +} +``` + +### Actions + +| Action | Description | +|---|---| +| `open()` | Open the palette | +| `close()` | Close the palette | +| `toggle()` | Toggle open/close | +| `addRecentlyViewed(item)` | Prepend to recents list (deduped by `id`, capped at 10) | + +### Persistence + +`recentlyViewed` is read from and written to `localStorage` key `showy-recent-viewed` on every `addRecentlyViewed` call (no Zustand persist middleware — manual). + +--- + ## useLibraryFiltersStore > [!info] File: `stores/useLibraryFiltersStore.ts` diff --git a/react_frontend/src/components/CommandPalette.tsx b/react_frontend/src/components/CommandPalette.tsx new file mode 100644 index 0000000..1a55978 --- /dev/null +++ b/react_frontend/src/components/CommandPalette.tsx @@ -0,0 +1,494 @@ +import { useState, useEffect, useRef, useCallback, useMemo } from 'react'; +import { useNavigate } from 'react-router-dom'; +import { useQuery } from '@tanstack/react-query'; +import { + Search, + Film, + Tv, + Library, + Star, + BarChart3, + Settings, + BookOpen, + Calendar, + Users, + ArrowUp, + ArrowDown, + CornerDownLeft, + ArrowRight, +} from 'lucide-react'; +import { tmdbApi } from '@/api/tmdb'; +import { useLibraryStore } from '@/stores/useLibraryStore'; +import { useCommandPaletteStore } from '@/stores/useCommandPaletteStore'; +import { useCreateEntry } from '@/hooks/useEntries'; +import { getTmdbImageUrl } from '@/lib/api'; +import { cn } from '@/lib/utils'; +import type { TmdbEntry } from '@/types'; + +interface CommandItem { + id: string; + type: 'command' | 'library' | 'tmdb'; + title: string; + subtitle?: string; + year?: string; + mediaType?: 'movie' | 'tv'; + posterPath?: string | null; + icon?: React.ReactNode; + inLibrary?: boolean; + libraryId?: number; + tmdbId?: number; + rating?: number | null; +} + +const NAVIGATION_COMMANDS: CommandItem[] = [ + { id: 'cmd-library', type: 'command', title: 'Go to Library', icon: }, + { id: 'cmd-watchlist', type: 'command', title: 'Go to Watchlist', icon: }, + { id: 'cmd-stats', type: 'command', title: 'Go to Statistics', icon: }, + { id: 'cmd-calendar', type: 'command', title: 'Go to Calendar', icon: }, + { id: 'cmd-people', type: 'command', title: 'Go to People', icon: }, + { id: 'cmd-settings', type: 'command', title: 'Go to Settings', icon: }, + { id: 'cmd-favorites', type: 'command', title: 'Go to Favorites', icon: }, +]; + +const COMMAND_ROUTES: Record = { + 'cmd-library': '/library', + 'cmd-watchlist': '/watchlist', + 'cmd-stats': '/dashboard', + 'cmd-calendar': '/calendar', + 'cmd-people': '/people', + 'cmd-settings': '/settings', + 'cmd-favorites': '/library?filter=favorites', +}; + +export function CommandPalette() { + const { isOpen, close, recentlyViewed } = useCommandPaletteStore(); + const navigate = useNavigate(); + const createEntry = useCreateEntry(); + const libraryEntries = useLibraryStore((s) => s.entries); + const inputRef = useRef(null); + const listRef = useRef(null); + + const [query, setQuery] = useState(''); + const [debouncedQuery, setDebouncedQuery] = useState(''); + const [selectedIndex, setSelectedIndex] = useState(0); + + // Debounce search query + useEffect(() => { + const timer = setTimeout(() => setDebouncedQuery(query), 250); + return () => clearTimeout(timer); + }, [query]); + + // Focus input when opened + useEffect(() => { + if (isOpen) { + setQuery(''); + setDebouncedQuery(''); + setSelectedIndex(0); + setTimeout(() => inputRef.current?.focus(), 50); + } + }, [isOpen]); + + // TMDB search + const { data: tmdbResults, isFetching: tmdbLoading } = useQuery({ + queryKey: ['command-palette', 'tmdb', debouncedQuery], + queryFn: () => tmdbApi.search(debouncedQuery, 1), + enabled: debouncedQuery.length > 1, + staleTime: 60 * 1000, + }); + + // Build library TMDB ID index for fast lookups + const libraryTmdbIndex = useMemo(() => { + const index = new Map(); + libraryEntries.forEach((entry) => { + if (entry.entryIds?.tmdb_id) { + index.set(entry.entryIds.tmdb_id, { + id: entry.id, + title: entry.title, + is_tvseries: entry.is_tvseries, + poster_path: entry.poster_path, + rating: entry.entryRatings?.user_rating ?? null, + }); + } + }); + return index; + }, [libraryEntries]); + + // Local library search + const localResults = useMemo((): CommandItem[] => { + if (!query.trim()) return []; + const lower = query.toLowerCase(); + const results: CommandItem[] = []; + libraryEntries.forEach((entry) => { + if (entry.title.toLowerCase().includes(lower)) { + results.push({ + id: `lib-${entry.id}`, + type: 'library', + title: entry.title, + year: entry.release_date?.slice(0, 4), + mediaType: entry.is_tvseries ? 'tv' : 'movie', + posterPath: entry.poster_path, + inLibrary: true, + libraryId: entry.id, + tmdbId: entry.entryIds?.tmdb_id ?? undefined, + rating: entry.entryRatings?.user_rating ?? null, + }); + } + }); + return results.slice(0, 5); + }, [query, libraryEntries]); + + // TMDB results — fully exclude entries already in library + const tmdbItems = useMemo((): CommandItem[] => { + if (!tmdbResults?.results) return []; + + return tmdbResults.results + .filter((r: TmdbEntry) => !libraryTmdbIndex.has(r.id)) + .slice(0, 8) + .map((r: TmdbEntry) => { + const mediaType = r.media_type === 'tv' || r.name ? 'tv' : 'movie'; + const title = r.title || r.name || 'Unknown'; + const year = (r.release_date || r.first_air_date)?.slice(0, 4); + + return { + id: `tmdb-${r.id}`, + type: 'tmdb' as const, + title, + year, + mediaType, + posterPath: r.poster_path, + inLibrary: false, + tmdbId: r.id, + rating: r.vote_average ? Math.round(r.vote_average * 10) / 10 : null, + }; + }); + }, [tmdbResults, libraryTmdbIndex]); + + // Filtered commands + const filteredCommands = useMemo((): CommandItem[] => { + if (!query.trim()) return NAVIGATION_COMMANDS; + const lower = query.toLowerCase(); + return NAVIGATION_COMMANDS.filter((c) => c.title.toLowerCase().includes(lower)); + }, [query]); + + // Recently viewed items (shown when no query) + const recentItems = useMemo((): CommandItem[] => { + if (query.trim()) return []; + return recentlyViewed.map((r) => ({ + id: `recent-${r.id}`, + type: (r.libraryId ? 'library' : 'tmdb') as 'library' | 'tmdb', + title: r.title, + mediaType: r.type, + posterPath: r.poster_path, + inLibrary: !!r.libraryId, + libraryId: r.libraryId, + tmdbId: r.tmdbId, + })); + }, [query, recentlyViewed]); + + // All items combined + const allItems = useMemo(() => { + return [...filteredCommands, ...localResults, ...tmdbItems, ...(query ? [] : recentItems)]; + }, [filteredCommands, localResults, tmdbItems, recentItems, query]); + + // Keep selected index in bounds + useEffect(() => { + if (selectedIndex >= allItems.length) { + setSelectedIndex(Math.max(0, allItems.length - 1)); + } + }, [allItems.length, selectedIndex]); + + // Scroll selected item into view + useEffect(() => { + const el = listRef.current?.querySelector(`[data-index="${selectedIndex}"]`); + el?.scrollIntoView({ block: 'nearest' }); + }, [selectedIndex]); + + const handleSelect = useCallback( + (item: CommandItem, quickAdd = false) => { + if (item.type === 'command') { + const route = COMMAND_ROUTES[item.id]; + if (route) navigate(route); + close(); + return; + } + + if (item.inLibrary && item.libraryId) { + navigate(`/entry/${item.libraryId}`); + close(); + return; + } + + if (quickAdd && item.tmdbId && item.mediaType) { + createEntry.mutate( + { tmdb_id: item.tmdbId, is_tvserie: item.mediaType === 'tv' }, + { + onSuccess: (entry) => { + navigate(`/entry/${entry.id}`); + close(); + }, + } + ); + return; + } + + // Open TMDB preview + if (item.tmdbId && item.mediaType) { + navigate(`/entry/tmdb/${item.mediaType}/${item.tmdbId}`); + close(); + } + }, + [navigate, close, createEntry] + ); + + const handleKeyDown = useCallback( + (e: React.KeyboardEvent) => { + switch (e.key) { + case 'ArrowDown': + e.preventDefault(); + setSelectedIndex((i) => Math.min(i + 1, allItems.length - 1)); + break; + case 'ArrowUp': + e.preventDefault(); + setSelectedIndex((i) => Math.max(i - 1, 0)); + break; + case 'Enter': { + e.preventDefault(); + const item = allItems[selectedIndex]; + if (item) handleSelect(item, e.shiftKey); + break; + } + case 'Escape': + e.preventDefault(); + close(); + break; + } + }, + [allItems, selectedIndex, handleSelect, close] + ); + + if (!isOpen) return null; + + return ( +
+ {/* Backdrop */} +
+ + {/* Palette */} +
e.stopPropagation()} + onKeyDown={handleKeyDown} + > + {/* Search input */} +
+ + { + setQuery(e.target.value); + setSelectedIndex(0); + }} + placeholder="Search movies, shows, or type a command..." + className="flex-1 bg-transparent text-base outline-none placeholder:text-muted-foreground" + /> + {tmdbLoading && ( +
+ )} +
+ + {/* Results list */} +
+ {/* Commands section */} + {filteredCommands.length > 0 && ( +
+
+ {query ? 'Commands' : 'Quick Actions'} +
+ {filteredCommands.map((item, i) => { + const idx = i; + return ( + handleSelect(item)} + /> + ); + })} +
+ )} + + {/* Recently viewed (no query) */} + {!query && recentItems.length > 0 && ( +
+
+ Recently Viewed +
+ {recentItems.map((item, i) => { + const idx = filteredCommands.length + i; + return ( + handleSelect(item)} + /> + ); + })} +
+ )} + + {/* Library results */} + {localResults.length > 0 && ( +
+
+ Library + +
+ {localResults.map((item, i) => { + const idx = filteredCommands.length + i; + return ( + handleSelect(item)} + /> + ); + })} +
+ )} + + {/* TMDB results */} + {tmdbItems.length > 0 && ( +
+
+ TMDB Results + +
+ {tmdbItems.map((item, i) => { + const idx = filteredCommands.length + localResults.length + i; + return ( + handleSelect(item)} + /> + ); + })} +
+ )} + + {/* Empty state */} + {query && allItems.length === 0 && !tmdbLoading && ( +
+ No results found for "{query}" +
+ )} +
+ + {/* Bottom hint bar */} +
+ + Open + + + ⇧ + Quick Add + + + + Navigate + + + Esc Close + +
+
+
+ ); +} + +function ResultRow({ + item, + isSelected, + dataIndex, + onClick, +}: { + item: CommandItem; + isSelected: boolean; + dataIndex: number; + onClick: () => void; +}) { + return ( +
+ {/* Poster or icon */} + {item.type === 'command' ? ( +
+ {item.icon} +
+ ) : item.posterPath ? ( + + ) : ( +
+ {item.mediaType === 'tv' ? : } +
+ )} + + {/* Content */} +
+
+ {item.title} +
+ {(item.year || item.mediaType) && ( +
+ {item.year && {item.year}} + {item.mediaType && ( + {item.mediaType === 'tv' ? 'TV Series' : 'Movie'} + )} + {item.rating != null && item.type !== 'command' && ( + + + {item.rating} + + )} +
+ )} +
+
+ ); +} diff --git a/react_frontend/src/components/layout/AppLayout.tsx b/react_frontend/src/components/layout/AppLayout.tsx index f07c500..32e79e0 100644 --- a/react_frontend/src/components/layout/AppLayout.tsx +++ b/react_frontend/src/components/layout/AppLayout.tsx @@ -10,6 +10,8 @@ import { } from '@/components/ui/sheet'; import { Sidebar, MobileSidebarContent } from './Sidebar'; import { TitleBar } from './TitleBar'; +import { CommandPalette } from '@/components/CommandPalette'; +import { useCommandPaletteStore } from '@/stores/useCommandPaletteStore'; const isElectron = import.meta.env.VITE_ELECTRON === 'true' || !!window.electron?.isElectron; @@ -17,14 +19,41 @@ export function AppLayout() { const [mobileOpen, setMobileOpen] = useState(false); const mainRef = useRef(null); const { pathname } = useLocation(); + const openPalette = useCommandPaletteStore((s) => s.open); useEffect(() => { mainRef.current?.scrollTo(0, 0); }, [pathname]); + // Global keyboard shortcut: Ctrl+P or "/" when not in input + useEffect(() => { + function handleKeyDown(e: KeyboardEvent) { + if ((e.ctrlKey || e.metaKey) && e.key === 'p') { + e.preventDefault(); + openPalette(); + return; + } + if ( + e.key === '/' && + !e.ctrlKey && + !e.metaKey && + !e.altKey && + !(e.target instanceof HTMLInputElement) && + !(e.target instanceof HTMLTextAreaElement) && + !(e.target as HTMLElement)?.isContentEditable + ) { + e.preventDefault(); + openPalette(); + } + } + document.addEventListener('keydown', handleKeyDown); + return () => document.removeEventListener('keydown', handleKeyDown); + }, [openPalette]); + return (
{isElectron && } +
{/* Desktop sidebar */} diff --git a/react_frontend/src/pages/EntryDetailsPage.tsx b/react_frontend/src/pages/EntryDetailsPage.tsx index 2d7452d..7835fca 100644 --- a/react_frontend/src/pages/EntryDetailsPage.tsx +++ b/react_frontend/src/pages/EntryDetailsPage.tsx @@ -1,9 +1,10 @@ -import { useState } from 'react'; +import { useState, useEffect } from 'react'; import { useParams, Link, useNavigate } from 'react-router-dom'; import { useEntry, useEntrySeasons, useRefreshEntry } from '@/hooks/useEntries'; import { useEntrySeenByEntry, useDeleteEntrySeen } from '@/hooks/useEntrySeen'; import { useCollections } from '@/hooks/useCollections'; import { useLibraryStore } from '@/stores/useLibraryStore'; +import { useCommandPaletteStore } from '@/stores/useCommandPaletteStore'; import { Badge } from '@/components/ui/badge'; import { Button } from '@/components/ui/button'; import { Separator } from '@/components/ui/separator'; @@ -83,6 +84,21 @@ export function EntryDetailsPage() { const [showWatchHistoryDialog, setShowWatchHistoryDialog] = useState(false); const [showDeleteConfirm, setShowDeleteConfirm] = useState(false); + // Track recently viewed for command palette + const addRecentlyViewed = useCommandPaletteStore((s) => s.addRecentlyViewed); + useEffect(() => { + if (displayEntry) { + addRecentlyViewed({ + id: `lib-${entryId}`, + title: displayEntry.title, + type: displayEntry.is_tvseries ? 'tv' : 'movie', + poster_path: displayEntry.poster_path, + libraryId: entryId, + tmdbId: displayEntry.entryIds?.tmdb_id ?? undefined, + }); + } + }, [entryId, displayEntry?.title]); + if (isLoading || !displayEntry) { return ; } diff --git a/react_frontend/src/pages/TmdbPreviewPage.tsx b/react_frontend/src/pages/TmdbPreviewPage.tsx index 419165b..e07efcc 100644 --- a/react_frontend/src/pages/TmdbPreviewPage.tsx +++ b/react_frontend/src/pages/TmdbPreviewPage.tsx @@ -1,6 +1,8 @@ import { useParams, useNavigate } from 'react-router-dom'; +import { useEffect } from 'react'; import { useTmdbPreview, useCreateEntry } from '@/hooks/useEntries'; import { useLibraryStore } from '@/stores/useLibraryStore'; +import { useCommandPaletteStore } from '@/stores/useCommandPaletteStore'; import { Badge } from '@/components/ui/badge'; import { Button } from '@/components/ui/button'; import { Separator } from '@/components/ui/separator'; @@ -29,6 +31,21 @@ export function TmdbPreviewPage() { return null; }); + // Track recently viewed for command palette + const addRecentlyViewed = useCommandPaletteStore((s) => s.addRecentlyViewed); + useEffect(() => { + if (preview) { + addRecentlyViewed({ + id: `tmdb-${tmdbIdNum}`, + title: preview.title, + type: mediaType, + poster_path: preview.poster_path, + libraryId: libraryEntry?.id, + tmdbId: tmdbIdNum, + }); + } + }, [tmdbIdNum, preview?.title]); + if (isLoading || !preview) { return ; } diff --git a/react_frontend/src/stores/useCommandPaletteStore.ts b/react_frontend/src/stores/useCommandPaletteStore.ts new file mode 100644 index 0000000..617e6da --- /dev/null +++ b/react_frontend/src/stores/useCommandPaletteStore.ts @@ -0,0 +1,40 @@ +import { create } from 'zustand'; + +interface RecentItem { + id: string; // unique key: "lib-{id}" or "tmdb-{tmdbId}" + title: string; + type: 'movie' | 'tv'; + poster_path: string | null; + libraryId?: number; + tmdbId?: number; +} + +interface CommandPaletteState { + isOpen: boolean; + recentlyViewed: RecentItem[]; + + open: () => void; + close: () => void; + toggle: () => void; + addRecentlyViewed: (item: RecentItem) => void; +} + +export const useCommandPaletteStore = create((set) => ({ + isOpen: false, + recentlyViewed: JSON.parse(localStorage.getItem('showy-recent-viewed') || '[]'), + + open: () => set({ isOpen: true }), + close: () => set({ isOpen: false }), + toggle: () => set((s) => ({ isOpen: !s.isOpen })), + + addRecentlyViewed: (item) => + set((state) => { + const filtered = state.recentlyViewed.filter((r) => r.id !== item.id); + const updated = [item, ...filtered].slice(0, 10); + localStorage.setItem('showy-recent-viewed', JSON.stringify(updated)); + return { recentlyViewed: updated }; + }), +})); + +export type { RecentItem }; +