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

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

export default function LaserToolkitSwitcher({ basePath = "/portal/utilities" }: { basePath?: string }) {
    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(`${basePath}?${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="min-w-0">
        <div className="border-b border-border/60 bg-background/30 p-3">
        <div className="relative sm:hidden">
            <Calculator className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-accent" />
            <select
                aria-label="Select laser calculator"
                value={activeKey}
                onChange={(e) => setTab(e.target.value)}
                className="h-10 w-full appearance-none rounded-lg border-border/70 bg-card pl-10 pr-9 text-sm"
            >
                {TOOLKIT_TABS.map((t) => <option key={t.key} value={t.key}>{t.label}</option>)}
            </select>
            <ChevronDown className="pointer-events-none absolute right-3 top-1/2 h-4 w-4 -translate-y-1/2 opacity-50" />
        </div>
        <div className="hidden flex-wrap gap-1 sm:flex">
        {TOOLKIT_TABS.map(t => (
            <button
            key={t.key}
            onClick={() => setTab(t.key)}
            className={cn(
                "rounded-md border border-transparent px-3 py-1.5 text-xs transition-colors",
                activeKey === t.key
                    ? "border-border/60 bg-card text-foreground shadow-sm"
                    : "text-muted-foreground hover:bg-muted/30 hover:text-foreground"
            )}
            >
            {t.label}
            </button>
        ))}
        </div></div>

        <div className="laser-tool-workspace">
        <ActiveCmp />
        </div>
        </div>
    );
}
