"use client";

import { useHospitalityCapabilities } from "@/modules/hospitality/hooks/useHospitalityCapabilities";
import { HospitalityPageLoader } from "@/modules/hospitality/pages/shared";
import { FeatureLock } from "@/modules/commercial/components";
import { useTenantId } from "@/hooks/useTenantId";
import { CapabilityUnavailable } from "@/modules/hospitality/components/CapabilityUnavailable";

/**
 * Dual-layer gate:
 * 1) Hospitality L2 `/capabilities` feature flag (service-owned pack)
 * 2) Commercial Runtime entitlement (FeatureLock)
 *
 * No local commercial catalog / bundle alias map.
 */
export function HospitalityBundleGate({
  feature,
  capabilities,
  children,
}: {
  feature: string;
  capabilities?: { features: Record<string, boolean> };
  children: React.ReactNode;
}) {
  const capsQ = useHospitalityCapabilities();
  const { tenantId } = useTenantId();
  const caps = capabilities ?? capsQ.data;
  const commercialKey = feature.startsWith("hospitality.")
    ? feature
    : `hospitality.${feature}`;

  if (capsQ.isLoading && !capabilities) return <HospitalityPageLoader />;

  const featureFlag = caps?.features?.[feature] ?? caps?.features?.[commercialKey];

  if (featureFlag === false) {
    return (
      <CapabilityUnavailable
        title="ماژول در بسته فعال نیست"
        description="این بخش در بسته (L2) فعال Hospitality شما موجود نیست."
        requiredCapability={feature}
        secondaryHref="/hospitality/bundles"
        secondaryLabel="بسته‌های Hospitality"
      />
    );
  }

  if (!tenantId) return <>{children}</>;

  return (
    <FeatureLock
      featureKey={commercialKey}
      tenantId={tenantId}
      requiredCapability={commercialKey}
      fallback={
        <CapabilityUnavailable
          title="نیاز به entitlement تجاری"
          description="دسترسی تجاری برای این قابلیت تأیید نشد — Commercial Runtime."
          requiredCapability={commercialKey}
        />
      }
    >
      {children}
    </FeatureLock>
  );
}
