import { useEffect } from "react";
import { Navigate, useSearchParams } from "react-router-dom";

function trimTrailingSlash(value: string) {
  return value.replace(/\/+$/, "");
}

function getClientAuthExchangeUrl(token: string) {
  const apiUrl = trimTrailingSlash(import.meta.env.VITE_API_URL ?? "");
  return `${apiUrl}/api/v1/client-auth/exchange?token=${encodeURIComponent(token)}`;
}

export function ClientMagicLinkExchangePage() {
  const [searchParams] = useSearchParams();
  const token = searchParams.get("token");

  useEffect(() => {
    if (!token) {
      return;
    }

    window.location.replace(getClientAuthExchangeUrl(token));
  }, [token]);

  if (!token) {
    return <Navigate to="/login" replace />;
  }

  return (
    <div className="flex min-h-screen items-center justify-center bg-background">
      <div className="h-8 w-8 animate-spin rounded-full border-b-2 border-primary" />
    </div>
  );
}

export { getClientAuthExchangeUrl };
