import { useEffect, useRef, useState } from 'react';
import { v4 as uuidv4 } from 'uuid';

export function useStudioProjectSessionId(studioProjectId: string): string {
  // Track the last studio project ID to detect changes
  const lastStudioProjectIdRef = useRef<string | null>(null);

  // Generate initial session ID
  const [studioProjectSessionId, setStudioProjectSessionId] = useState(() => {
    lastStudioProjectIdRef.current = studioProjectId;
    return uuidv4();
  });

  // Generate new session ID when studio project changes
  useEffect(() => {
    if (lastStudioProjectIdRef.current !== studioProjectId) {
      lastStudioProjectIdRef.current = studioProjectId;
      setStudioProjectSessionId(uuidv4());
    }
  }, [studioProjectId]);

  return studioProjectSessionId;
}
