"use client";

import { useSession } from "next-auth/react";
import { useRouter, useSearchParams } from "next/navigation";
import { useEffect, Suspense } from "react";
import NextAuthComponent from "@/app/components/NextAuthComponent";

import "../styles/new-site.css";

function deriveWorkspace(email: string): string {
  return (
    email
      .split("@")[0]
      .toLowerCase()
      .replace(/[^a-z0-9]+/g, "-") + "-account"
  );
}

function AuthPageInner() {
  const { data: session, status } = useSession();
  const router = useRouter();
  const searchParams = useSearchParams();

  useEffect(() => {
    if (status === "authenticated" && session?.user?.email) {
      const workspace = deriveWorkspace(session.user.email);
      router.push(`/${workspace}/projects`);
    }
  }, [status, session, router, searchParams]);

  if (status === "loading") {
    return (
      <div
        className="new-site-wrapper"
        style={{
          display: "flex",
          alignItems: "center",
          justifyContent: "center",
          minHeight: "100vh",
        }}
      >
        <div
          style={{
            display: "flex",
            flexDirection: "column",
            alignItems: "center",
            gap: "16px",
          }}
        >
          <div
            style={{
              width: "24px",
              height: "24px",
              borderRadius: "50%",
              border: "2px solid oklch(0.20 0.009 60)",
              borderTopColor: "var(--accent)",
              animation: "spin .9s linear infinite",
            }}
          />
          <style>{`
            @keyframes spin { to { transform: rotate(360deg); } }
          `}</style>
          <div
            style={{
              color: "var(--fg-mute)",
              fontFamily: "var(--font-mono)",
              fontSize: "11px",
              letterSpacing: "0.1em",
              textTransform: "uppercase",
            }}
          >
            Checking session
          </div>
        </div>
      </div>
    );
  }

  return (
    <div
      className="new-site-wrapper"
      style={{
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        minHeight: "100vh",
      }}
    >
      <NextAuthComponent />
    </div>
  );
}

export default function AuthPage() {
  return (
    <Suspense>
      <AuthPageInner />
    </Suspense>
  );
}
