"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 (
    <div className="inline-flex items-center gap-1 rounded-md border border-zinc-800 bg-zinc-950/60 p-1">
      {PLATFORMS.map((p) => {
        const active = p === props.currentPlatform;
        return (
          <Link
            key={p}
            href={buildHref(p)}
            className={`px-3 py-1.5 text-xs font-medium rounded transition-colors ${
              active
                ? "bg-zinc-800 text-zinc-50"
                : "text-zinc-400 hover:text-zinc-200 hover:bg-zinc-900/60"
            }`}
          >
            {p}
          </Link>
        );
      })}
    </div>
  );
}