// app/beta/confirm/page.tsx
"use client";

import { useEffect, useRef, useState, Suspense } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { useAuth } from "@/context/AuthContext";

const API_BASE_URL =
  process.env.NEXT_PUBLIC_API_BASE_URL ?? "http://localhost:8080";

function BetaConfirmPageContent() {
  const params = useSearchParams();
  const token = params.get("token");
  const router = useRouter();
  const { setSession } = useAuth();
  const ran = useRef(false);

  const [message, setMessage] = useState("Confirming your email…");
  const [status, setStatus] = useState<"loading" | "success" | "error">(
    "loading"
  );

  useEffect(() => {
    if (!token) {
      setStatus("error");
      setMessage("Missing token.");
      return;
    }

    if (ran.current) return;
    ran.current = true;

    (async () => {
      try {
        const res = await fetch(`${API_BASE_URL}/api/auth/beta/confirm`, {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ token }),
        });

        if (!res.ok) {
          const text = await res.text().catch(() => "");
          throw new Error(text || "Confirm link invalid/expired");
        }

        const data = await res.json();

        const jwt = data.token ?? data.accessToken;
        if (!jwt) throw new Error("No token returned from server");

        const uuid = data.uuid ?? data.user?.uuid;
        if (!uuid) throw new Error("No uuid returned from server");

        const email = data.email ?? data.user?.email;
        if (!email) throw new Error("No email returned from server");

        setSession(jwt, {
          uuid,
          email,
          displayName: data.displayName ?? data.user?.displayName ?? null,
          role: data.role ?? data.user?.role ?? "USER",
        });

        setStatus("success");
        setMessage("Confirmed. Signing you in…");
        router.replace("/account?welcome=1");
      } catch (e: any) {
        setStatus("error");
        setMessage(
          e?.message ||
            "That link is invalid or expired. Please request a new one."
        );
      }
    })();
  }, [token, router, setSession]);

  return (
    <main className="min-h-screen flex items-center justify-center bg-black text-white px-6">
      <div className="max-w-md w-full rounded-xl border border-white/10 bg-white/5 p-6 text-center">
        <h1 className="text-lg font-semibold">Battl Builders</h1>
        <p className="mt-2 text-sm text-zinc-300">{message}</p>

        {status === "error" && (
          <p className="mt-4 text-xs text-zinc-400">
            Go back and request a fresh sign-in link.
          </p>
        )}
      </div>
    </main>
  );
}

export default function BetaConfirmPage() {
  return (
    <Suspense fallback={
      <main className="min-h-screen flex items-center justify-center bg-black text-white px-6">
        <div className="max-w-md w-full rounded-xl border border-white/10 bg-white/5 p-6 text-center">
          <h1 className="text-lg font-semibold">Battl Builders</h1>
          <p className="mt-2 text-sm text-zinc-300">Loading…</p>
        </div>
      </main>
    }>
      <BetaConfirmPageContent />
    </Suspense>
  );
}