---
/**
 * Feature - Server-rendered feature flag component for Astro
 *
 * This component evaluates feature flags on the server side during SSR/SSG.
 * Use `negate` for the off path (same as .NET `<feature negate>`).
 *
 * @example
 * ```astro
 * <Feature flag="new-dashboard">
 *   <p>This content is only shown when the feature is enabled</p>
 * </Feature>
 * ```
 *
 * @example Off path with negate
 * ```astro
 * <Feature flag="maintenance-mode" negate={true}>
 *   <p>Main app while maintenance is off</p>
 * </Feature>
 * ```
 *
 * @example Entity context
 * ```astro
 * <Feature flag="OrderBadge" context={order} contextKind="Order">
 *   <Badge />
 * </Feature>
 * ```
 */

interface Props {
  /** Single feature flag key to check */
  flag?: string;
  /** Multiple feature flag keys to check */
  flags?: string[];
  /** Requirement for multiple flags: 'all' or 'any' (default: 'all') */
  requirement?: 'all' | 'any';
  /** If true, negates the result (default: false) */
  negate?: boolean;
  /** Entity instance or canonical entity context for entity-gated flags */
  context?: import('@ops-ai/toggly-hooks-types').TogglyEntityContext | Record<string, unknown> | null;
  /** Context kind for registerContext mapper lookup when `context` is a domain object */
  contextKind?: string;
}

const { flag, flags, requirement = 'all', negate = false, context = null, contextKind } = Astro.props;

// Get Toggly client from Astro.locals
const toggly = Astro.locals.toggly;

if (!toggly) {
  console.warn(
    '[Toggly Feature] Client not found in Astro.locals. ' +
    'Make sure the Toggly integration is properly configured.'
  );
}

// Build feature keys array
const flagKeys: string[] = [];
if (flag) {
  flagKeys.push(flag);
}
if (flags && Array.isArray(flags)) {
  flagKeys.push(...flags);
}

// Evaluate feature gate
let isEnabled = false;
if (toggly && flagKeys.length > 0) {
  try {
    isEnabled = await toggly.evaluateGate(flagKeys, requirement, negate, context, contextKind);
  } catch (error) {
    console.error('[Toggly Feature] Error evaluating feature gate:', error);
    isEnabled = false;
  }
} else if (flagKeys.length === 0) {
  isEnabled = !negate;
}
---

{isEnabled ? <slot /> : null}
