import { useCallback, useEffect, useRef, useState } from "react"; import { useTranslation } from "react-i18next"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { ArrowLeft, Check, ExternalLink, Loader2, Plus, RefreshCw } from "lucide-react"; import Avatar from "./Avatar"; import Feed from "./Feed"; import { useConfirm } from "./ConfirmProvider"; import { notify } from "../lib/notifications"; import { api, type FeedFilters, type Me } from "../lib/api"; import { channelYouTubeUrl, formatViews } from "../lib/format"; // A dedicated channel page: an "About"-style header (banner, avatar, stats, subscribe) over the // channel's videos (the catalog filtered to this channel). For an un-subscribed channel it // auto-ingests recent uploads in the background ("explore") so they're browsable immediately, // and offers "load more" to page deeper — without permanently polluting everyone's library // (the backend keeps explored videos private to this user until they subscribe). export default function ChannelPage({ channelId, initialName, me, view, onBack, onOpenChannel, }: { channelId: string; initialName?: string; me: Me; view: "grid" | "list"; onBack: () => void; onOpenChannel: (id: string, name?: string) => void; }) { const { t, i18n } = useTranslation(); const qc = useQueryClient(); const confirm = useConfirm(); const [tab, setTab] = useState<"videos" | "about">("videos"); const detail = useQuery({ queryKey: ["channel", channelId], queryFn: () => api.channelDetail(channelId), }); const ch = detail.data; // Background auto-ingest ("explore") of an un-subscribed channel's uploads. const [nextToken, setNextToken] = useState(undefined); const [exploring, setExploring] = useState(false); const autoTried = useRef(null); const runExplore = useCallback( (token?: string | null) => { setExploring(true); return api .exploreChannel(channelId, token ?? undefined) .then((r) => { setNextToken(r.next_page_token); qc.invalidateQueries({ queryKey: ["feed"] }); // Refetch the detail so `explored` flips true → the "Exploring" badge shows on the // first visit (the GET that drove this render predated the explore that just ran). qc.invalidateQueries({ queryKey: ["channel", channelId] }); }) .finally(() => setExploring(false)); }, [channelId, qc] ); // First visit of an un-subscribed channel → ingest its recent uploads. Skipped for the demo // account (explore spends shared quota) and when videos are already present (a revisit, or a // subscribed channel whose uploads the scheduler backfills). useEffect(() => { if (!ch || me.is_demo) return; if (autoTried.current === channelId) return; if (ch.subscribed) return; if (ch.explored && ch.stored_videos > 0) return; autoTried.current = channelId; runExplore().catch(() => {}); }, [ch, channelId, me.is_demo, runExplore]); const subscribe = useMutation({ mutationFn: () => api.subscribeChannel(channelId), onSuccess: () => { qc.invalidateQueries({ queryKey: ["channel", channelId] }); qc.invalidateQueries({ queryKey: ["feed"] }); qc.invalidateQueries({ queryKey: ["channels"] }); notify({ level: "info", message: t("channel.subscribed", { name: ch?.title ?? "" }) }); }, }); const unsubscribe = useMutation({ mutationFn: () => api.unsubscribeChannel(channelId), onSuccess: () => { qc.invalidateQueries({ queryKey: ["channel", channelId] }); qc.invalidateQueries({ queryKey: ["feed"] }); qc.invalidateQueries({ queryKey: ["channels"] }); }, }); const onUnsubscribe = async () => { const ok = await confirm({ title: t("channel.unsubTitle"), message: t("channel.unsubBody", { name: ch?.title ?? channelId }), confirmLabel: t("channel.unsubscribe"), danger: true, }); if (ok) unsubscribe.mutate(); }; // Channel-scoped feed: the whole catalog filtered to this channel (scope=all + source=all so // the explored, per-user-private videos show — the backend gates them to this explorer). const [filters, setFilters] = useState(() => ({ tags: [], tagMode: "or", q: "", sort: "newest", scope: "all", librarySource: "all", includeNormal: true, includeShorts: false, includeLive: true, show: "all", channelId, channelName: initialName, })); const name = ch?.title ?? initialName ?? channelId; const ytUrl = channelYouTubeUrl(channelId, ch?.handle); const joined = ch?.published_at ? new Date(ch.published_at).toLocaleDateString(i18n.language, { year: "numeric", month: "short" }) : null; // Handle + stats on one compact meta line under the name (saves the separate stats row). const metaParts = [ ch?.handle ? `@${ch.handle.replace(/^@/, "")}` : null, ch?.subscriber_count != null ? t("channel.subscribers", { formatted: formatViews(ch.subscriber_count) }) : null, ch?.video_count != null ? t("channel.videoCount", { count: ch.video_count }) : null, ch?.total_view_count != null ? t("channel.totalViews", { formatted: formatViews(ch.total_view_count) }) : null, joined ? t("channel.joined", { date: joined }) : null, ].filter(Boolean) as string[]; const tabClass = (active: boolean) => active ? "pb-2 text-sm font-medium border-b-2 border-fg text-fg" : "pb-2 text-sm text-muted hover:text-fg border-b-2 border-transparent"; return (
{/* Banner + back */}
{ch?.banner_url ? ( // Match YouTube's banner: the stored bannerExternalUrl is the full 16:9 template at a // low default size, so request a crisp wide version (=w1707) and object-cover the // desktop "safe area" — the centre 2560×423 (~6:1) band — at full width.
) : (
)}
{/* Identity + actions. relative+z-10 so the avatar that overlaps up into the banner paints ABOVE it (the banner's positioned container would otherwise cover it). */}

{name}

{ch?.explored && !ch?.subscribed && ( {t("channel.exploringBadge")} )}
{metaParts.map((part, i) => ( {i > 0 && ·} {part} ))}
{!me.is_demo && (ch?.subscribed ? ( ) : ( ))}
{exploring && (
{t("channel.loadingVideos")}
)} {/* Tabs */}
{/* Tab content */} {tab === "videos" ? ( <> {}} ytSearch={null} onYtSearch={() => {}} onExitYtSearch={() => {}} onOpenChannel={onOpenChannel} channelScoped /> {!ch?.subscribed && nextToken && (
)} ) : (
{ch?.description ? (

{ch.description}

) : (

{t("channel.noDescription")}

)} {ch?.external_links && ch.external_links.length > 0 && (
{ch.external_links.map((l, i) => ( {l.title || l.url} ))}
)}
)}
); }