All files / hooks useMatchCountdown.ts

100% Statements 52/52
95.23% Branches 20/21
100% Functions 12/12
100% Lines 52/52

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234                                                                                                                                  3x                                                                                         26x 8x                             26x 26x     26x 26x 26x     26x 26x 8x           26x 17x 7x 7x   17x 3x 3x   17x 2x 2x             26x 7x 7x 7x     7x 5x 5x     5x 5x 6x 6x   6x 2x 2x 2x       2x   2x 2x 2x                   26x 1x 1x 1x           26x 1x 1x 1x           26x 8x 8x       26x                      
/**
 * useMatchCountdown Hook - Manages match start countdown sequence
 *
 * Korean: 매치 시작 카운트다운 훅 (Match Start Countdown Hook)
 *
 * Handles the state machine for match start countdown:
 * - idle: Waiting to start
 * - ready: Showing "Ready?" message
 * - counting: Counting down "3... 2... 1..."
 * - fight: Showing "Fight!" announcement
 * - complete: Countdown finished, combat can begin
 *
 * @module hooks/useMatchCountdown
 * @category Combat Hooks
 */
 
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
 
/**
 * Match countdown states
 *
 * Korean: 매치 카운트다운 상태
 */
export type MatchCountdownState =
  | "idle"
  | "ready"
  | "counting"
  | "fight"
  | "complete";
 
/**
 * Match countdown configuration
 */
export interface MatchCountdownConfig {
  /** Duration of "Ready?" display in seconds */
  readonly readyDuration?: number;
  /** Duration of each countdown number in seconds */
  readonly countdownInterval?: number;
  /** Duration of "Fight!" display in seconds */
  readonly fightDuration?: number;
  /** Starting countdown number */
  readonly startNumber?: number;
}
 
/**
 * Match countdown hook state
 */
export interface UseMatchCountdownResult {
  /** Current countdown state */
  readonly state: MatchCountdownState;
  /** Current countdown number (3, 2, 1, or 0) */
  readonly currentNumber: number;
  /** Start countdown sequence */
  readonly startCountdown: () => void;
  /** Skip countdown and proceed immediately */
  readonly skipCountdown: () => void;
  /** Reset countdown to idle state */
  readonly resetCountdown: () => void;
  /** Whether countdown is in progress */
  readonly isActive: boolean;
}
 
/**
 * Default configuration values
 */
const DEFAULT_CONFIG: Required<MatchCountdownConfig> = {
  readyDuration: 1,
  countdownInterval: 1,
  fightDuration: 1,
  startNumber: 3,
};
 
/**
 * useMatchCountdown Hook
 *
 * Manages the complete match start countdown flow:
 * 1. Idle state waiting for match start
 * 2. Ready state shows "Ready?" message (1s)
 * 3. Counting state counts down from 3 to 1 (1s intervals)
 * 4. Fight state shows "Fight!" message (1s)
 * 5. Complete state signals combat can begin
 *
 * @param config - Configuration for countdown timings
 * @param onComplete - Callback when countdown completes
 * @returns Match countdown state and control functions
 *
 * @example
 * ```typescript
 * const {
 *   state,
 *   currentNumber,
 *   startCountdown,
 *   skipCountdown,
 * } = useMatchCountdown(
 *   { startNumber: 3 },
 *   () => {
 *     // Enable combat inputs
 *     enableCombatControls();
 *   }
 * );
 *
 * // When match initializes
 * startCountdown();
 * ```
 */
export function useMatchCountdown(
  config: MatchCountdownConfig = {},
  onComplete?: () => void
): UseMatchCountdownResult {
  // Memoize with individual config values to avoid reference equality issues
  const mergedConfig = useMemo(
    () => ({
      readyDuration: config.readyDuration ?? DEFAULT_CONFIG.readyDuration,
      countdownInterval:
        config.countdownInterval ?? DEFAULT_CONFIG.countdownInterval,
      fightDuration: config.fightDuration ?? DEFAULT_CONFIG.fightDuration,
      startNumber: config.startNumber ?? DEFAULT_CONFIG.startNumber,
    }),
    [
      config.readyDuration,
      config.countdownInterval,
      config.fightDuration,
      config.startNumber,
    ]
  );
 
  const [state, setState] = useState<MatchCountdownState>("idle");
  const [currentNumber, setCurrentNumber] = useState(mergedConfig.startNumber);
 
  // Use refs to track active timers
  const readyTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
  const countdownTimer = useRef<ReturnType<typeof setInterval> | null>(null);
  const fightTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
 
  // Use ref to always call the latest callback
  const onCompleteRef = useRef(onComplete);
  useEffect(() => {
    onCompleteRef.current = onComplete;
  }, [onComplete]);
 
  /**
   * Clear all active timers
   */
  const clearTimers = useCallback(() => {
    if (readyTimer.current) {
      clearTimeout(readyTimer.current);
      readyTimer.current = null;
    }
    if (countdownTimer.current) {
      clearInterval(countdownTimer.current);
      countdownTimer.current = null;
    }
    if (fightTimer.current) {
      clearTimeout(fightTimer.current);
      fightTimer.current = null;
    }
  }, []);
 
  /**
   * Start the countdown sequence
   */
  const startCountdown = useCallback(() => {
    clearTimers();
    setState("ready");
    setCurrentNumber(mergedConfig.startNumber);
 
    // Show "Ready?" message
    readyTimer.current = setTimeout(() => {
      setState("counting");
      setCurrentNumber(mergedConfig.startNumber);
 
      // Countdown timer
      let count = mergedConfig.startNumber;
      countdownTimer.current = setInterval(() => {
        count -= 1;
        setCurrentNumber(count);
 
        if (count <= 0) {
          Eif (countdownTimer.current) {
            clearInterval(countdownTimer.current);
            countdownTimer.current = null;
          }
 
          // Show "Fight!" message
          setState("fight");
 
          fightTimer.current = setTimeout(() => {
            setState("complete");
            onCompleteRef.current?.();
          }, mergedConfig.fightDuration * 1000);
        }
      }, mergedConfig.countdownInterval * 1000);
    }, mergedConfig.readyDuration * 1000);
  }, [clearTimers, mergedConfig]);
 
  /**
   * Skip countdown and proceed immediately to fight state
   */
  const skipCountdown = useCallback(() => {
    clearTimers();
    setState("complete");
    onCompleteRef.current?.();
  }, [clearTimers]);
 
  /**
   * Reset countdown to idle state
   */
  const resetCountdown = useCallback(() => {
    clearTimers();
    setState("idle");
    setCurrentNumber(mergedConfig.startNumber);
  }, [clearTimers, mergedConfig.startNumber]);
 
  /**
   * Cleanup on unmount
   */
  useEffect(() => {
    return () => {
      clearTimers();
    };
  }, [clearTimers]);
 
  return {
    state,
    currentNumber,
    startCountdown,
    skipCountdown,
    resetCountdown,
    isActive: state !== "idle" && state !== "complete",
  };
}
 
export default useMatchCountdown;