"use client";

import { useEffect } from "react";
import { useRouter } from "next/navigation";

import type { FlightSearchFormV3Props } from "@/components/flights/v3/FlightSearchFormV3";
import {
  useBusinessSession,
  useBusinessSessionReady,
} from "@/components/employee-requests/use-session";
import { ADMIN_HOME } from "@/constants/business-routes";
import { EmployeeHome } from "./EmployeeHome";

/**
 * What `/` is, per role (LEIS-1014).
 *
 * Replaces `RootRedirect`, which sent an employee to `/srp/flights` and an
 * admin to `/admin/flight-approvals` because neither home page existed. Now the
 * employee home IS this route — rendered, not redirected to — and only the
 * admin is sent on, to `/admin`.
 *
 * ── Why the admin is redirected rather than rendered here ───────────────
 *
 * D0 needs `app/admin/layout.tsx`'s five stylesheets (`flight-approval.css`
 * and the rest) for the sections LEIS-1019/1020/1021 add. Rendering it at `/`
 * would mean loading those on the employee's page too, or a second copy of the
 * layout. One route, one stylesheet set.
 *
 * ── Why the gate is `useBusinessSessionReady` and not `session === null` ─
 *
 * The server cannot read localStorage, so the first client render always sees
 * "no session". Redirecting on that alone bounces a signed-in employee to the
 * login page before the stored token has been read — a bug this repo has
 * already fixed once (commit 0238983, "don't redirect a signed-in employee to
 * sign-in during hydration"). `useBusinessSessionReady()` is false on the
 * server snapshot and true on the client, which is exactly that distinction.
 */
export function HomeRouter({ flightFormProps }: { flightFormProps?: FlightSearchFormV3Props }) {
  const router = useRouter();
  const ready = useBusinessSessionReady();
  const session = useBusinessSession();

  useEffect(() => {
    if (!ready) return;
    if (!session) {
      router.replace("/employee-login");
      return;
    }
    if (session.role === "ADMIN") router.replace(ADMIN_HOME);
  }, [ready, session, router]);

  // Nothing until the answer is in, and nothing for the two cases that are
  // leaving anyway. A spinner here would flash on every load for the one case
  // that resolves synchronously.
  if (!ready || !session || session.role === "ADMIN") return null;

  return <EmployeeHome flightFormProps={flightFormProps} />;
}
