"use client";

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

/**
 * Route guard.
 *
 * The app has TWO auth realms:
 *   · client portal  → routes under /client/... , token "clientPortalToken",
 *     login at /client/login
 *   · staff/internal → everything else, token "access_token" / "token",
 *     login at /login
 *
 * Previously this only checked "token" and always sent you to /login, so a
 * logged-in CLIENT (who has clientPortalToken, not "token") got bounced to
 * the staff login. Now it picks the right token + login page based on the
 * current path.
 */
export default function PrivateRoute({ children }: { children: React.ReactNode }) {
  const [checked, setChecked] = useState(false);
  const router = useRouter();
  const pathname = usePathname();

  useEffect(() => {
    const isClientArea = pathname?.startsWith("/client");

    if (isClientArea) {
      // client portal realm
      const clientToken = localStorage.getItem("clientPortalToken");
      if (!clientToken) {
        router.replace("/client/login");
        return;
      }
      setChecked(true);
      return;
    }

    // staff / internal realm
    const staffToken =
      localStorage.getItem("access_token") || localStorage.getItem("token");
    if (!staffToken) {
      router.replace("/login");
      return;
    }
    setChecked(true);
  }, [router, pathname]);

  if (!checked) return null;

  return <>{children}</>;
}