import type { ReactNode } from "react";
import { Outlet } from "react-router-dom";
import { useEntitlement } from "../../hooks/useEntitlement";
import { requiredTierFor, type FeatureKey } from "../../shared/entitlements";
import UpsellGate from "./UpsellGate";

interface RequireFeatureProps {
  feature: FeatureKey;
  children?: ReactNode;
}

/**
 * Route guard for gated features (UI-only soft paywall).
 *
 * While the license is still loading or errored (`!ready`) it renders a
 * NEUTRAL loader — never the upsell — so a paying user never sees a
 * "locked" flash at boot or during a transient IPC failure (the retry loop
 * lives in LicenseProvider; this component only respects `ready`).
 *
 * Usable two ways:
 * - layout route grouping all routes of one feature (children omitted →
 *   renders <Outlet/>):
 *     <Route element={<RequireFeature feature="balance" />}> …sub-routes
 * - explicit wrapper:
 *     <RequireFeature feature="budget"><BudgetPage /></RequireFeature>
 */
export default function RequireFeature({ feature, children }: RequireFeatureProps) {
  const { allowed, ready } = useEntitlement(feature);

  if (!ready) {
    return (
      <div className="flex min-h-full items-center justify-center">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-[var(--primary)]" />
      </div>
    );
  }

  if (!allowed) {
    return <UpsellGate feature={feature} requiredTier={requiredTierFor(feature)} />;
  }

  return children !== undefined ? <>{children}</> : <Outlet />;
}
