"use client";

import { useMemo } from "react";
import { useSearchParams, useRouter } from "next/navigation";
import dynamic from "next/dynamic";
import { cn } from "@/lib/utils";

const BuyingGuideList = dynamic(
    () => import("@/components/buying-guide/BuyingGuideList"),
                                { ssr: false }
);
const LaserFinderPanel = dynamic(
    () => import("@/components/buying-guide/LaserFinderPanel"),
                                 { ssr: false }
);
const BuyingGuideProductClient = dynamic(
    () => import("@/components/buying-guide/BuyingGuideProductClient"),
                                         { ssr: false }
);

const TABS = [
    { key: "list", label: "Buying Guide" },
{ key: "finder", label: "Laser Finder" },
];

export default function BuyingGuideSwitcher() {
    const searchParams = useSearchParams();
    const router = useRouter();

    const active = useMemo(() => searchParams.get("tab") || "list", [searchParams]);
    const productId = searchParams.get("product");

    const setTab = (key: string) => {
        const sp = new URLSearchParams(Array.from(searchParams.entries()));
        sp.set("tab", key);
        // When changing tabs, ensure product detail (if open) is cleared
        sp.delete("product");
        router.push(`?${sp.toString()}`, { scroll: false });
    };

    return (
        <div className="space-y-4">
        {/* Tabs */}
        <div className="inline-flex rounded-md border overflow-hidden">
        {TABS.map((t) => (
            <button
            key={t.key}
            onClick={() => setTab(t.key)}
            className={cn(
                "px-3 py-2 text-sm transition-colors",
                active === t.key ? "bg-primary text-primary-foreground" : "hover:bg-muted"
            )}
            >
            {t.label}
            </button>
        ))}
        </div>

        {/* Body */}
        <div className="rounded-md border p-4">
        {productId ? (
            <BuyingGuideProductClient />
        ) : active === "finder" ? (
            <LaserFinderPanel />
        ) : (
            <BuyingGuideList />
        )}
        </div>
        </div>
    );
}
