"use client";

import { AuthGuard } from "@/components/AuthGuard";
import { useMe } from "@/hooks/useMe";
import { useRouter, usePathname } from "next/navigation";
import { useEffect } from "react";
import { LoadingState, ErrorState } from "@/components/ds";
import { SportsCenterPortalShell } from "@/modules/sports-center/components/SportsCenterPortalShell";
import {
  detectPortal,
  type SportsCenterPortalId,
} from "@/modules/sports-center/constants/portals";

function PortalGate({
  portalId,
  children,
}: {
  portalId: SportsCenterPortalId;
  children: React.ReactNode;
}) {
  const { me, loading, error, reload } = useMe();
  const router = useRouter();

  useEffect(() => {
    if (loading) return;
    if (me?.onboarding_required) router.replace("/onboarding");
  }, [me, loading, router]);

  if (loading) return <LoadingState label="در حال آماده‌سازی مرکز ورزشی…" />;
  if (error) return <ErrorState message={error} onRetry={reload} />;
  if (!me?.current_tenant_id) {
    return <ErrorState message="برای استفاده از مرکز ورزشی workspace فعال لازم است." />;
  }

  return <SportsCenterPortalShell portalId={portalId}>{children}</SportsCenterPortalShell>;
}

export function createPortalLayout(portalId: SportsCenterPortalId) {
  return function PortalLayout({ children }: { children: React.ReactNode }) {
    return (
      <AuthGuard>
        <PortalGate portalId={portalId}>{children}</PortalGate>
      </AuthGuard>
    );
  };
}

/** Root layout — hub bypasses sidebar shell. */
export function SportsCenterRootLayout({ children }: { children: React.ReactNode }) {
  const pathname = usePathname();
  const isHub = pathname === "/sports-center/hub";

  if (isHub) {
    return <AuthGuard>{children}</AuthGuard>;
  }

  const portalId = detectPortal(pathname);
  return (
    <AuthGuard>
      <PortalGate portalId={portalId}>{children}</PortalGate>
    </AuthGuard>
  );
}
