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

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

// Use existing canonical pages; dynamic imports in a client component are OK
const FiberPanel     = dynamic(() => import("@/app/settings/fiber/page"), { ssr: false });
const UVPanel        = dynamic(() => import("@/app/settings/uv/page"), { ssr: false });
const CO2GalvoPanel  = dynamic(() => import("@/app/settings/co2-galvo/page"), { ssr: false });
const CO2GantryPanel = dynamic(() => import("@/app/settings/co2-gantry/page"), { ssr: false });

const TABS = [
    { key: "fiber",      label: "Fiber" },
{ key: "uv",         label: "UV" },
{ key: "co2-gantry", label: "CO₂ Gantry" },
{ key: "co2-galvo",  label: "CO₂ Galvo" },
{ key: "add",        label: "Add Setting" }, // new
];

function Panel({ tab }: { tab: string }) {
    switch (tab) {
        case "fiber":      return <FiberPanel />;
        case "uv":         return <UVPanel />;
        case "co2-galvo":  return <CO2GalvoPanel />;
        case "co2-gantry": return <CO2GantryPanel />;
        case "add":
            return (
                <div className="rounded-md border p-4 space-y-3">
                <h3 className="font-semibold">Add Setting</h3>
                <div className="text-sm opacity-70">
                Submission form will be embedded here. We’ll retrofit your existing public submission to require auth and record owner.
                </div>
                <ul className="text-sm list-disc pl-5 opacity-70">
                <li>Route: <code>POST /api/my/settings/:type</code> (fiber|uv|co2-gantry|co2-galvo)</li>
                <li>Server adds <code>owner</code> using <code>/users/me</code> via bearer</li>
                <li>On success: toast + refresh current view tab</li>
                </ul>
                </div>
            );
        default:
            return <FiberPanel />;
    }
}

export default function SettingsSwitcher() {
    const router = useRouter();
    const sp = useSearchParams();
    const active = sp.get("t") || "fiber";

    function setTab(nextKey: string) {
        const q = new URLSearchParams(sp.toString());
        q.set("t", nextKey);
        router.replace(`/portal/laser-settings?${q.toString()}`, { scroll: false });
    }

    return (
        <div>
        <div className="mb-4 flex flex-wrap items-center gap-2">
        {TABS.map(({ key, label }) => (
            <button
            key={key}
            onClick={() => setTab(key)}
            className={cn(
                "rounded-md border px-3 py-1.5 text-sm transition",
                active === key ? "bg-primary text-primary-foreground" : "hover:bg-muted"
            )}
            >
            {label}
            </button>
        ))}
        </div>

        <div className="rounded-md border p-4">
        <Panel tab={active} />
        </div>
        </div>
    );
}
