// components/portal/LaserToolkitSwitcher.tsx
"use client";

import { useMemo } from "react";
import { useSearchParams, useRouter } from "next/navigation";
import { cn } from "@/lib/utils";
import { TOOLKIT_TABS } from "@/components/utilities/laser-toolkit/registry";

export default function LaserToolkitSwitcher() {
    const sp = useSearchParams();
    const router = useRouter();

    const activeKey = useMemo(() => {
        const def = TOOLKIT_TABS[0]?.key ?? "beam-spot-size";
        const t = (sp.get("lt") || def).toLowerCase();
        return TOOLKIT_TABS.some(x => x.key === t) ? t : def;
    }, [sp]);

    const active = useMemo(
        () => TOOLKIT_TABS.find(x => x.key === activeKey) ?? TOOLKIT_TABS[0],
                           [activeKey]
    );

    function setTab(k: string) {
        const q = new URLSearchParams(sp.toString());
        q.set("lt", k);
        router.replace(`/portal/utilities?${q.toString()}`, { scroll: false });
    }

    if (!active) {
        return <div className="text-sm text-zinc-400">No tools registered.</div>;
    }

    const ActiveCmp = active.component;

    return (
        <div className="space-y-4">
        <div className="flex flex-wrap gap-2">
        {TOOLKIT_TABS.map(t => (
            <button
            key={t.key}
            onClick={() => setTab(t.key)}
            className={cn(
                "rounded-md border px-3 py-1.5 text-sm",
                activeKey === t.key ? "bg-primary text-primary-foreground" : "hover:bg-muted"
            )}
            >
            {t.label}
            </button>
        ))}
        </div>

        <div className="rounded-md border p-4">
        <ActiveCmp />
        </div>
        </div>
    );
}
