"use client";

import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { useRouter } from "next/navigation";
import { useEffect, useState } from "react";
import { LoginScreen } from "@/components/login-screen";
import { resolveBrandDomainFromHost } from "@/lib/site-config";

export function MailLoginShell() {
  const router = useRouter();
  const [brandDomain, setBrandDomain] = useState("");
  const [brandDomainResolved, setBrandDomainResolved] = useState(false);
  const [client] = useState(
    () =>
      new QueryClient({
        defaultOptions: {
          queries: {
            refetchOnWindowFocus: false,
            retry: 1,
            staleTime: 20_000,
          },
        },
    })
  );

  useEffect(() => {
    setBrandDomain(resolveBrandDomainFromHost(window.location.hostname));
    setBrandDomainResolved(true);
  }, []);

  return (
    <QueryClientProvider client={client}>
      {brandDomainResolved ? <LoginScreen onSignedIn={() => router.push("/")} brandDomain={brandDomain} /> : <LoginThemeLoadingShell />}
    </QueryClientProvider>
  );
}

function LoginThemeLoadingShell() {
  return <main className="min-h-[100dvh] bg-[#f7f9fc]" />;
}
