"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 { CrmPortalShell } from "@/modules/crm/components/CrmPortalShell";
import type { CrmPortalId } from "@/modules/crm/constants/portals";
import { useCrmKeyboardShortcuts } from "@/modules/crm/hooks/useCrmKeyboardShortcuts";

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

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

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

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

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