"use client";

import { type ReactNode, useEffect, useState, useRef } from "react";
import { UnleashProvider } from "./UnleashProvider";
import { useSession } from "@/hooks/session/useSession";

interface UnleashSessionProviderProps {
  children: ReactNode;
  funnelId: string;
  googleAnalyticsId?: string;
}

/**
 * Создает сессию и инициализирует Unleash с sessionId
 */
export function UnleashSessionProvider({
  children,
  funnelId,
  googleAnalyticsId,
}: UnleashSessionProviderProps) {
  const [sessionId, setSessionId] = useState<string | null>(null);
  const [isReady, setIsReady] = useState(false);
  const { createSession } = useSession({ funnelId, googleAnalyticsId });
  const initCalledRef = useRef(false);

  useEffect(() => {
    // Prevent multiple initializations
    if (initCalledRef.current) return;
    initCalledRef.current = true;

    const initSession = async () => {
      console.log(`[UnleashSessionProvider] Initializing session...`);
      const result = await createSession();
      if (result.sessionId) {
        console.log(`[UnleashSessionProvider] Using sessionId: ${result.sessionId}`);
        setSessionId(result.sessionId);
      }
      setIsReady(true);
    };

    initSession();
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [funnelId]);

  // Показываем loading пока создается сессия
  if (!isReady || !sessionId) {
    return null;
  }

  return (
    <UnleashProvider sessionId={sessionId}>
      {children}
    </UnleashProvider>
  );
}
