"use client";

import { useMemo } from "react";
import { usePathname, useRouter, useSearchParams } from "next/navigation";

export default function PlatformSwitcher(props: {
  currentPlatform: string;
  partRole: string;
  preserveQuery?: boolean; // keep sort/page/etc (but NOT platform)
}) {
  const { currentPlatform, partRole, preserveQuery = true } = props;

  const router = useRouter();
  const pathname = usePathname();
  const searchParams = useSearchParams();

  const queryString = useMemo(() => {
    if (!preserveQuery) return "";

    // Copy params and DROP legacy platform param so it can’t conflict with the path
    const sp = new URLSearchParams(searchParams?.toString());
    sp.delete("platform");

    const q = sp.toString();
    return q ? `?${q}` : "";
  }, [searchParams, preserveQuery]);

  function go(platform: string) {
    router.replace(
      `/parts/p/${encodeURIComponent(platform)}/${encodeURIComponent(partRole)}${queryString}`
    );
  }

  return (
    <div className="flex items-center gap-2">
      <span className="text-xs uppercase tracking-[0.14em] text-zinc-500">Platform</span>
      <select
        value={currentPlatform}
        onChange={(e) => go(e.target.value)}
        className="rounded-md border border-zinc-700 bg-zinc-950/80 px-2 py-1 text-xs text-zinc-100 outline-none focus:border-amber-400"
      >
        <option value="AR-15">AR-15</option>
        <option value="AR-10">AR-10</option>
        <option value="AR-9">AR-9</option>
        <option value="AK-47">AK-47</option>
      </select>

      {/* debug only */}
      <span className="ml-2 text-[0.7rem] text-zinc-500">{pathname}</span>
    </div>
  );
}