import { useEffect, useRef, useState } from "react"; import { qk } from "../lib/queryKeys"; import { useTranslation } from "react-i18next"; import { plexLang } from "../i18n"; import { useQuery, useQueryClient } from "@tanstack/react-query"; import { Layers, ListMusic, Plus, Search, SlidersHorizontal, X } from "lucide-react"; import { PopoverItem, PopoverSurface, useAnchoredPopover } from "./AnchoredPopover"; import { api, plexFilterCount, type PlexFilters } from "../lib/api"; import { type PanelLayout } from "../lib/panelLayout"; import { type MediaSourceKind } from "../lib/mediaSource"; import { useDebounced } from "../lib/useDebounced"; import { useScrollFade } from "../lib/useScrollFade"; import FilterRail from "./FilterRail"; import { type PanelItem } from "./PanelGroups"; import SegmentedToggle from "./SegmentedToggle"; import FilterChipGroup from "./FilterChipGroup"; import MultiSelectChips from "./MultiSelectChips"; import { usePlexClearFilters } from "./usePlexActiveFilters"; import { usePlex, usePlexActions } from "./PlexProvider"; // The Plex module's left filter column — now the shared floating SidePanel with its filter groups // as reorderable "islands" (same system as the feed rail). Movie libraries get the full metadata // set; shows keep library + sort. State is owned by App (per-account persisted); facets come from // the backend so the panel only offers what the library actually contains. type Props = { layout: PanelLayout; setLayout: (l: PanelLayout) => void; collapsed: boolean; onToggleCollapse: () => void; }; const SHOW_OPTS = ["all", "unwatched", "in_progress", "watched"] as const; const RATING_STEPS = [5, 6, 7, 8, 9]; const ADDED_OPTS = ["24h", "1w", "1m", "6m", "1y"] as const; const DURATION_BUCKETS: { key: string; min: number | null; max: number | null }[] = [ { key: "short", min: null, max: 90 * 60 }, { key: "mid", min: 90 * 60, max: 120 * 60 }, { key: "long", min: 120 * 60, max: null }, ]; // The any/all combine toggle for a multi-value filter (genres, actors) — a thin binding of the shared // SegmentedToggle to the Plex match vocabulary (same look as the feed rail's tag MATCH toggle). function MatchToggle({ mode, onChange, }: { mode: "any" | "all"; onChange: (m: "any" | "all") => void; }) { const { t } = useTranslation(); return ( ); } export default function PlexSidebar({ layout, setLayout, collapsed, onToggleCollapse }: Props) { const { t } = useTranslation(); // Scope / watch-state / sort / expanded filters live in PlexProvider (shared with PlexBrowse and // the header search box); this rail is the primary editor of them. Opening a playlist is a // hand-off to PlexBrowse via the shared `playlistOpen` slot. const { scope, show, filters } = usePlex(); const { setShow, setFilters, setPlaylistOpen: onOpenPlaylist } = usePlexActions(); const playlistsQ = useQuery({ queryKey: qk.plexPlaylists(), queryFn: () => api.plexPlaylists() }); const [newPlaylist, setNewPlaylist] = useState(""); // This rail's media source (the Plex library) — names the abstraction the feed and Plex rails // share; drives the panel layout key. `FilterRail` owns the customize `editing` state now. const source: MediaSourceKind = "plex"; const qc = useQueryClient(); async function createPlaylist() { const title = newPlaylist.trim(); if (!title) return; const pl = await api.plexCreatePlaylist(title); setNewPlaylist(""); qc.invalidateQueries({ queryKey: qk.plexPlaylists() }); onOpenPlaylist(pl.id); } const { collectionTitle: _ct, ...facetKey } = filters; const lang = plexLang(); // HU/EN genre vocabulary — refetch facets on a language switch const facetsQ = useQuery({ queryKey: qk.plexFacets(scope, show, facetKey, lang), queryFn: () => api.plexFacets(scope, filters, show, lang), enabled: !!scope, placeholderData: (prev) => prev, }); const facets = facetsQ.data; const fCount = plexFilterCount(filters); // Scope and sort moved to the header / above-the-grid toolbar (S3); the panel badge now counts only // the filters that still live in this panel (expanded filters + watch-state). const activeCount = fCount + (show !== "all" ? 1 : 0); const anyActive = activeCount > 0; const patch = (p: Partial) => setFilters({ ...filters, ...p }); const clearAll = usePlexClearFilters(); const durBucketKey = DURATION_BUCKETS.find( (b) => (filters.durationMin ?? null) === b.min && (filters.durationMax ?? null) === b.max, )?.key; // Directors + actors have no picker (they're added from the detail/cast surfaces) — this section // just lists them as removable chips. Studios now have their own picker section (below). const peopleActive = filters.directors.length + filters.actors.length > 0; // Group bodies (no title — the PanelGroup card supplies it). Only available groups are pushed, // so facet-gated / scope-gated sections drop out cleanly; PanelGroups orders them by the saved // layout and lets the user reorder / hide / collapse them. const items: PanelItem[] = [ { id: "playlists", title: t("plex.playlist.section"), body: ( <>
setNewPlaylist(e.target.value)} onKeyDown={(e) => e.key === "Enter" && createPlaylist()} placeholder={t("plex.playlist.newPlaceholder")} className="glass-card min-w-0 flex-1 rounded-lg px-2 py-1 text-xs focus:outline-hidden focus:ring-2 focus:ring-accent/40" />
{(playlistsQ.data?.playlists ?? []).length === 0 ? (

{t("plex.playlist.none")}

) : (
{playlistsQ.data!.playlists.map((p) => ( ))}
)} ), }, { id: "watch", title: t("plex.filter.show"), body: ( ({ value: s, label: t(`plex.filter.showOpt.${s}`) }))} value={show} onChange={setShow} /> ), }, ...(peopleActive ? [ { id: "people", title: t("plex.filter.active"), body: (
{filters.directors.map((d) => ( patch({ directors: filters.directors.filter((x) => x !== d) })} /> ))} {filters.actors.length > 1 && (
patch({ actorMode: m })} />
)} {filters.actors.map((a) => ( patch({ actors: filters.actors.filter((x) => x !== a) })} /> ))}
), }, ] : []), { id: "collection", title: t("plex.filter.collection"), body: filters.collection ? (
patch({ collection: null, collectionTitle: null })} />
) : ( patch({ collection: id, collectionTitle: title })} /> ), }, { id: "rating", title: t("plex.filter.rating"), body: ( ({ value: String(r), label: `${r}+` })), ]} onChange={(v) => patch({ ratingMin: v === "" ? null : Number(v) })} /> ), }, ...(facets && facets.genres.length > 0 ? [ { id: "genre", title: t("plex.filter.genre"), body: ( <> {filters.genres.length > 1 && (
patch({ genreMode: m })} />
)} patch({ genres: next })} /> ), }, ] : []), { id: "year", title: t("plex.filter.year"), body: (
patch({ yearMin: v })} /> – patch({ yearMax: v })} />
), }, ...(scope === "movie" ? [ { id: "duration", title: t("plex.filter.duration"), body: ( ({ value: b.key, label: t(`plex.filter.durationOpt.${b.key}`), })), ]} onChange={(key) => { const b = DURATION_BUCKETS.find((x) => x.key === key); patch({ durationMin: b?.min ?? null, durationMax: b?.max ?? null }); }} /> ), }, ] : []), { id: "added", title: t("plex.filter.added"), body: ( ({ value: a, label: t(`plex.filter.addedOpt.${a}`) })), ]} onChange={(v) => patch({ addedWithin: v })} /> ), }, ...(facets && facets.content_ratings.length > 0 ? [ { id: "contentrating", title: t("plex.filter.contentRating"), body: ( patch({ contentRatings: next })} /> ), }, ] : []), ...(facets && facets.studios.length > 0 ? [ { id: "studio", title: t("plex.filter.studio"), body: ( patch({ studios: next })} /> ), }, ] : []), ]; return ( } count={activeCount} collapsed={collapsed} onToggleCollapse={onToggleCollapse} layout={layout} setLayout={setLayout} items={items} actions={ anyActive ? ( ) : undefined } /> ); } // The collection filter as a compact "+ Add" → searchable popover (E5 S7), matching the genre/studio // pickers instead of an always-expanded inline search + list. Single-select: picking a collection sets // the filter and closes; the selected one then shows as a removable chip (handled by the caller). function CollectionPicker({ onPick }: { onPick: (id: string, title: string) => void }) { const { t } = useTranslation(); const [open, setOpen] = useState(false); const [search, setSearch] = useState(""); const searchDeb = useDebounced(search.trim(), 300); const inputRef = useRef(null); const fade = useScrollFade(); const q = useQuery({ queryKey: qk.plexCollections("union", searchDeb), queryFn: () => api.plexCollections(undefined, searchDeb || undefined), enabled: open, // only fetch while the picker is open }); const collections = q.data?.collections ?? []; // Search narrows server-side; cap the client render so a large union (hundreds) stays light. const visibleCollections = collections.slice(0, 50); const hiddenCollections = collections.length - visibleCollections.length; const pop = useAnchoredPopover({ open, onOpenChange: setOpen, mode: "menu", placement: "bottom-start", hostsInput: true, }); useEffect(() => { if (open) inputRef.current?.focus(); else setSearch(""); }, [open]); return ( <>
setSearch(e.target.value)} onKeyDown={(e) => { if (e.key === "Escape") return; // let the popover dismiss handle it e.stopPropagation(); // keep text editing out of the surface's list-nav/typeahead }} placeholder={t("plex.filter.collectionSearch")} className="w-full rounded-lg border border-border bg-surface py-1 pl-7 pr-2 text-sm focus:outline-hidden focus:ring-2 focus:ring-accent/40" />
{collections.length === 0 ? (

{t("plex.filter.collectionEmpty")}

) : ( <> {visibleCollections.map((c) => ( { onPick(c.id, c.title); setOpen(false); }} label={c.title} className="flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm text-muted outline-hidden transition" > {c.title} {c.child_count != null && ( {c.child_count} )} ))} {hiddenCollections > 0 && (

{t("plex.filter.moreRefine", { count: hiddenCollections })}

)} )}
); } function RemovableChip({ label, onRemove }: { label: string; onRemove: () => void }) { return ( {label} ); } function NumberInput({ value, placeholder, onChange, }: { value: number | null; placeholder?: number; onChange: (v: number | null) => void; }) { return ( { const n = e.target.value === "" ? null : Number(e.target.value); onChange(n != null && Number.isFinite(n) ? n : null); }} className="w-20 rounded-lg border border-border bg-surface px-2 py-1 text-sm tabular-nums focus:outline-hidden focus:ring-2 focus:ring-accent/40" /> ); }