import { Suspense } from "react";
import type { Metadata } from "next";
import Image from "next/image";
import { LoaderCircle } from "lucide-react";
import { ThemeToggle } from "@/components/layout/theme";
import { OtpLinkVerification } from "@/features/auth/otp-link-verification";
import { authDestination, type SafeAuthSession } from "@/features/auth/auth-client";
import { isCsmsApiConfigured } from "@/lib/auth/server-config";
import { getServerSession } from "@/lib/auth/server-session";

export const metadata: Metadata = { title: "Verify Sign In", referrer: "no-referrer", robots: { index: false, follow: false } };
export const dynamic = "force-dynamic";

export default async function OtpVerifyPage() {
  const apiEnabled = isCsmsApiConfigured();
  let session: SafeAuthSession | null = null;
  let sessionCheckFailed = false;
  if (apiEnabled) {
    try { session = await getServerSession(); }
    catch { sessionCheckFailed = true; }
  }
  return <main className="relative flex min-h-dvh items-center justify-center px-5 py-10 sm:px-6">
    <section className="auth-panel w-full max-w-md rounded-2xl border border-input/70 bg-card/80 p-6 backdrop-blur-xl sm:p-8" aria-label="Email sign-in verification">
      <Image src="/branding/tiar-icon.svg" alt="Tiar" width={48} height={48} priority className="mb-6" />
      <Suspense fallback={<p role="status" className="flex items-center gap-2 text-sm text-auth-muted"><LoaderCircle aria-hidden="true" className="size-4 animate-spin motion-reduce:animate-none" />Opening your verification link…</p>}>
        <OtpLinkVerification apiEnabled={apiEnabled} signedInEmail={session?.email} signedInDestination={session ? authDestination(session) : undefined} sessionCheckFailed={sessionCheckFailed} />
      </Suspense>
    </section>
    <div className="fixed bottom-6 right-6 hidden sm:block"><ThemeToggle /></div>
  </main>;
}
