"use client";

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

import { useSessionContext } from "./session-provider";

export const AuthGuard = ({ children }: { children: React.ReactNode }) => {
  const { ready, session } = useSessionContext();
  const router = useRouter();
  const pathname = usePathname();

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

    if (!session) {
      router.replace(`/login?next=${encodeURIComponent(pathname)}`);
    }
  }, [pathname, ready, router, session]);

  if (!ready || !session) {
    return (
      <div className="flex min-h-screen items-center justify-center p-6">
        <div className="rounded-3xl border border-line bg-panel px-6 py-5 shadow-soft">
          <p className="text-sm font-medium text-muted">Ładowanie sesji...</p>
        </div>
      </div>
    );
  }

  return <>{children}</>;
};
