"use client"; import Link from "next/link"; import { usePathname, useSearchParams } from "next/navigation"; const PLATFORMS = ["AR-15", "AR-10", "AR-9"] as const; type Platform = (typeof PLATFORMS)[number]; export default function PlatformSwitcher(props: { currentPlatform: string; partRole: string; /** * If true, preserve *all* existing query params (except platform will be overwritten). * Useful when you want to keep things like ?from=builder or future filters. */ preserveQuery?: boolean; /** * Force route behavior. * - "browse": /parts/[role]?platform=... * - "detail": /parts/p/[platform]/[role] * Default: auto based on current pathname */ mode?: "browse" | "detail"; }) { const pathname = usePathname(); const searchParams = useSearchParams(); const inferredMode: "browse" | "detail" = pathname.startsWith("/parts/p/") ? "detail" : "browse"; const mode = props.mode ?? inferredMode; const buildHref = (nextPlatform: Platform) => { if (mode === "detail") { return `/parts/p/${encodeURIComponent(nextPlatform)}/${encodeURIComponent( props.partRole )}`; } // browse mode => keep on /parts/[role] and just change the query param const qp = props.preserveQuery ? new URLSearchParams(searchParams.toString()) : new URLSearchParams(); qp.set("platform", nextPlatform); return { pathname: `/parts/${encodeURIComponent(props.partRole)}`, query: Object.fromEntries(qp.entries()), } as const; }; return (
{PLATFORMS.map((p) => { const active = p === props.currentPlatform; return ( {p} ); })}
); }