'use client';

import { useEffect, useRef, useState } from 'react';

/**
 * Returns `key` right after mount (and after every change). React StrictMode mounts effects twice
 * in development; feeding this to useGameConnection means only the surviving mount opens a socket,
 * instead of opening one and tearing it down mid-handshake. A microtask (not a timer) so a page
 * opened in a background tab, where timers are throttled, still connects immediately.
 */
export function useSettledKey(key: string | null): string | null {
  const [settled, setSettled] = useState<string | null>(null);
  useEffect(() => {
    let current = true;
    queueMicrotask(() => {
      if (current) setSettled(key);
    });
    return () => {
      current = false;
    };
  }, [key]);
  return settled;
}

/**
 * Counts increases of `value` (not the first render), so a `key={bump}` restarts a CSS
 * "score bump" animation exactly when the score goes up.
 */
export function useBump(value: number | null | undefined): number {
  const prev = useRef(value);
  const [bump, setBump] = useState(0);
  useEffect(() => {
    if (typeof value === 'number' && typeof prev.current === 'number' && value > prev.current) setBump((b) => b + 1);
    prev.current = value;
  }, [value]);
  return bump;
}
