import { useEffect } from 'react';
import { useSessionStore } from '@/stores/sessionStore';
import { joinSession } from '@/lib/sync/wsSync';

/**
 * App-level player connection. While a joinIntent is set (persisted), keep the
 * room connection alive no matter which view the player is on — so switching to
 * their character sheet, the compendium, etc. never drops the live session.
 * Mounted once in the app shell. Leaving is explicit (leaveRoom).
 */
export function usePlayerConnection(): void {
  const code = useSessionStore((s) => s.joinIntent?.joinCode);
  const password = useSessionStore((s) => s.joinIntent?.password);
  useEffect(() => {
    if (code) joinSession(code, password);
  }, [code, password]);
}
