"use client";

import { AuthGuard } from "@/components/AuthGuard";
import { useMe } from "@/hooks/useMe";
import { useRouter } from "next/navigation";
import { useEffect } from "react";
import { LoadingState, ErrorState } from "@/components/ds";
import { CommunicationPortalShell } from "@/modules/communication/components/CommunicationPortalShell";

function PortalGate({ children }: { 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 <CommunicationPortalShell>{children}</CommunicationPortalShell>;
}

export function CommunicationRootLayout({ children }: { children: React.ReactNode }) {
  return (
    <AuthGuard>
      <PortalGate>{children}</PortalGate>
    </AuthGuard>
  );
}
