"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 { HospitalityPortalShell } from "@/modules/hospitality/components/HospitalityPortalShell";

export type HospitalityPortalId = "management";

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 <HospitalityPortalShell>{children}</HospitalityPortalShell>;
}

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

/** Root layout wrapper — hub renders without shell sidebar. */
export function HospitalityRootLayout({ children }: { children: React.ReactNode }) {
  const pathname = usePathname();
  const isHub = pathname === "/hospitality/hub";

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

  return (
    <AuthGuard>
      <PortalGate>{children}</PortalGate>
    </AuthGuard>
  );
}
