"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 { LoyaltyPortalShell } from "@/modules/loyalty/components/LoyaltyPortalShell";
import type { LoyaltyPortalId } from "@/modules/loyalty/constants/portals";
import { useLoyaltyKeyboardShortcuts } from "@/modules/loyalty/hooks/useLoyaltyKeyboardShortcuts";

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

  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 <LoyaltyPortalShell portalId={portalId}>{children}</LoyaltyPortalShell>;
}

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