"use client";

import { FlagProvider } from "@unleash/proxy-client-react";
import { type ReactNode, useMemo } from "react";

interface UnleashProviderProps {
  children: ReactNode;
  userId?: string;
  sessionId?: string;
}

/**
 * Unleash Provider для воронок
 * Инициализирует Unleash клиент с настройками для AB тестирования
 */
export function UnleashProvider({
  children,
  userId,
  sessionId,
}: UnleashProviderProps) {
  // Проверяем наличие необходимых env переменных
  const unleashUrl = process.env.NEXT_PUBLIC_UNLEASH_URL;
  const unleashClientKey = process.env.NEXT_PUBLIC_UNLEASH_CLIENT_KEY;

  // Создаем config с useMemo ДО условного return
  const config = useMemo(() => ({
    url: unleashUrl || "",
    clientKey: unleashClientKey || "",
    refreshInterval: 15,
    appName: "witlab-funnel",
    context: {
      userId: userId,
      sessionId: sessionId || userId || "anonymous",
      properties: {},
    },
  }), [unleashUrl, unleashClientKey, userId, sessionId]);

  // Если настройки не заданы, просто возвращаем children без Unleash
  if (!unleashUrl || !unleashClientKey) {
    if (process.env.NODE_ENV === "development") {
      console.warn(
        "[Unleash] Missing configuration. Set NEXT_PUBLIC_UNLEASH_URL and NEXT_PUBLIC_UNLEASH_CLIENT_KEY to enable AB testing."
      );
    }
    return <>{children}</>;
  }

  console.log("[UnleashProvider] Initializing with sessionId:", sessionId || userId || "anonymous");

  return (
    <FlagProvider config={config}>
      {children}
    </FlagProvider>
  );
}
