"use client";

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

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

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

  useEffect(() => {
    const initSession = async () => {
      const localStorageKey = `${funnelId}_sessionId`;
      let sid = localStorage.getItem(localStorageKey);
      
      if (!sid) {
        console.log(`[UnleashSessionProvider] Creating new session...`);
        const result = await createSession();
        sid = result.sessionId;
      }
      
      if (sid) {
        console.log(`[UnleashSessionProvider] Using sessionId: ${sid}`);
        setSessionId(sid);
      }
      
      setIsReady(true);
    };

    initSession();
  }, [funnelId, createSession]);

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

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