"use client";

import { createContext, useContext, type ReactNode } from "react";

interface UnleashContextValue {
  /**
   * Текущие активные варианты флагов
   * Ключ - название флага, значение - вариант
   */
  activeVariants: Record<string, string>;
  
  /**
   * Проверяет соответствует ли флаг ожидаемым вариантам
   */
  checkVariant: (
    flag: string,
    expectedVariants: string[],
    operator?: "includesAny" | "includesAll" | "includesExactly" | "equals"
  ) => boolean;
}

const UnleashContext = createContext<UnleashContextValue | null>(null);

interface UnleashContextProviderProps {
  children: ReactNode;
  activeVariants: Record<string, string>;
}

/**
 * Провайдер контекста для хранения текущих вариантов Unleash
 * Используется в navigation и variants logic
 */
export function UnleashContextProvider({
  children,
  activeVariants,
}: UnleashContextProviderProps) {
  const checkVariant = (
    flag: string,
    expectedVariants: string[],
    operator: "includesAny" | "includesAll" | "includesExactly" | "equals" = "includesAny"
  ): boolean => {
    const currentVariant = activeVariants[flag];
    
    if (!currentVariant || expectedVariants.length === 0) {
      return false;
    }

    switch (operator) {
      case "includesAny":
        return expectedVariants.includes(currentVariant);
      case "includesAll":
        return expectedVariants.includes(currentVariant);
      case "includesExactly":
        return expectedVariants.length === 1 && expectedVariants[0] === currentVariant;
      case "equals":
        return expectedVariants.length === 1 && expectedVariants[0] === currentVariant;
      default:
        return false;
    }
  };

  return (
    <UnleashContext.Provider value={{ activeVariants, checkVariant }}>
      {children}
    </UnleashContext.Provider>
  );
}

export function useUnleashContext() {
  const context = useContext(UnleashContext);
  if (!context) {
    // Возвращаем fallback если контекст не доступен
    return {
      activeVariants: {},
      checkVariant: () => false,
    };
  }
  return context;
}

export { UnleashContext };
