import { useState } from "react"; import { ExternalLink } from "lucide-react"; import { getTmdbImageUrl } from "@/lib/api"; import type { WatchProvider, WatchProviderRegion } from "@/types"; const CATEGORIES: { key: keyof WatchProviderRegion; label: string }[] = [ { key: "flatrate", label: "Stream" }, { key: "free", label: "Free" }, { key: "ads", label: "With ads" }, { key: "rent", label: "Rent" }, { key: "buy", label: "Buy" }, ]; /** Country from the browser locale (en-US → US), falling back to US. */ function defaultRegion(available: string[]): string { const fromLocale = navigator.language?.split("-")[1]?.toUpperCase(); if (fromLocale && available.includes(fromLocale)) return fromLocale; if (available.includes("US")) return "US"; return available[0]; } const regionName = (() => { try { const names = new Intl.DisplayNames(["en"], { type: "region" }); return (code: string) => names.of(code) ?? code; } catch { return (code: string) => code; } })(); export function WatchProvidersCard({ providers, }: { providers: Record | null | undefined; }) { const regions = Object.keys(providers ?? {}).sort((a, b) => regionName(a).localeCompare(regionName(b)), ); const [region, setRegion] = useState(() => regions.length ? defaultRegion(regions) : "", ); if (!providers || regions.length === 0) return null; const info = providers[region] ?? providers[regions[0]]; const groups = CATEGORIES.map((c) => ({ ...c, list: (info[c.key] as WatchProvider[] | null | undefined) ?? [], })).filter((g) => g.list.length > 0); return (

Where to watch

{groups.length === 0 ? (

Not available in {regionName(region)}.

) : (
{groups.map((g) => (

{g.label}

{g.list .slice() .sort( (a, b) => (a.display_priority ?? 99) - (b.display_priority ?? 99), ) .map((p) => ( {p.provider_name} ))}
))}
)} {info.link && ( Data from JustWatch via TMDB )}
); }