"use client";

import { useEffect } from "react";
import { useSearchParams, useRouter } from "next/navigation";
import { Suspense } from "react";

const STORAGE_KEY = "gunbuilder-build-state";

function BuildLoader() {
  const searchParams = useSearchParams();
  const router = useRouter();

  useEffect(() => {
    const encoded = searchParams.get("build");

    if (encoded) {
      try {
        const decoded = JSON.parse(atob(encoded));
        if (decoded && typeof decoded === "object") {
          localStorage.setItem(STORAGE_KEY, JSON.stringify(decoded));
        }
      } catch {
        // Bad payload — just go to builder anyway, it'll load fresh
      }
    }

    router.replace("/builder");
  }, [searchParams, router]);

  return (
    <main className="min-h-screen bg-black text-zinc-50 flex items-center justify-center">
      <p className="text-sm text-zinc-400">Loading build…</p>
    </main>
  );
}

export default function BuildPage() {
  return (
    <Suspense>
      <BuildLoader />
    </Suspense>
  );
}
