"use client";

import { Suspense } from "react";
import { useSearchParams } from "next/navigation";

import Loader from "@/components/ui/Loader";
import LoginForm from "@/features/auth/components/LoginForm";
import StoredAccounts from "@/features/auth/components/StoredAccounts";

/**
 * The `/login` route's client half: the search-param read and the Suspense
 * boundary that `useSearchParams` requires.
 *
 * Split out of `app/(auth)/login/page.tsx` so that file can be a Server
 * Component and export a `metadata` title — a Client Component cannot. This is
 * the same server-shell / client-child split the other 59 pages already use.
 *
 * `useSearchParams` is kept here rather than moved to the page's `searchParams`
 * prop deliberately. Reading `searchParams` on the server would make the route
 * dynamic, and `/login` is prerendered static today; the params are only ever
 * used to seed a client form, so there is nothing to gain by rendering them on
 * the server and a round trip to lose.
 */
function LoginRouteContent() {
  const searchParams = useSearchParams();

  const userType = searchParams.get("user_type") || null;
  const requestedReturnTo = searchParams.get("returnTo");
  /* Only a same-origin path. `//evil.test` is a protocol-relative URL that a
     browser treats as absolute, so the second test is not redundant. */
  const returnTo =
    requestedReturnTo?.startsWith("/") && !requestedReturnTo.startsWith("//")
      ? requestedReturnTo
      : "/";

  return (
    <>
      {/* BE-129 — a session that ended leaves the device's other accounts
          in place; this is the only screen that can offer them. */}
      <StoredAccounts />
      <LoginForm userType={userType} returnTo={returnTo} />
    </>
  );
}

export default function LoginRoute() {
  return (
    <Suspense fallback={<Loader />}>
      <LoginRouteContent />
    </Suspense>
  );
}
