All files / components/screens/training/components TrainingStatsOverlayHtml.tsx

88.57% Statements 31/35
76.92% Branches 50/65
100% Functions 8/8
87.5% Lines 28/32

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 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420                                                                                                                                                              2x                 31x 31x 31x     31x 31x         31x 31x         31x 31x             31x 31x 24x 24x                   31x 31x 31x         31x                           31x       31x                                                                                                                                                                                                                                                                                                                                                 48x                                 2x                       2x                 234x     234x 234x       234x                                                                                                   2x      
/**
 * TrainingStatsOverlayHtml - Html overlay for training statistics
 *
 * Displays score, combo, hits, misses, and accuracy with consistent Korean theming.
 * Uses Korean cyberpunk color palette and bilingual text formatting.
 *
 * @module components/screens/training
 * @category Training UI
 * @korean 훈련통계오버레이
 */
 
import React, { useMemo } from "react";
import { FONT_FAMILY, KOREAN_COLORS } from "../../../../types/constants";
import { SPACING } from "../../../../types/constants/ui";
import { hexToRgbaString } from "../../../../utils/colorUtils";
import {
  formatBilingualText,
  getEnhancedKoreanOverlayStyles,
  getResponsiveSpacing,
} from "../../../../utils/koreanThemeHelpers";
import { getMobileKoreanFontSize } from "../../../../utils/mobileUIUtils";
import { getSafeAreaPadding } from "../../../../utils/safeAreaUtils";
import {
  getNeonTextShadow,
  getSmoothTransition,
} from "../../../../utils/visualEffects";
 
/**
 * Training statistics interface
 */
export interface TrainingStats {
  readonly score: number;
  readonly combo: number;
  readonly hits: number;
  readonly misses: number;
  readonly accuracy: number;
  readonly sessionDuration?: number;
  readonly bestCombo?: number;
  readonly perfectStrikes?: number;
}
 
/**
 * Props for TrainingStatsOverlayHtml component
 */
export interface TrainingStatsOverlayHtmlProps {
  /** Current training statistics */
  readonly stats: TrainingStats;
  /** Whether on mobile device */
  readonly isMobile: boolean;
  /** Viewport width for Super HD font scaling */
  readonly width?: number;
  /** Distance to training dummy in meters (for distance-based hit feedback) */
  readonly distanceToDummy?: number;
  /** Effective reach for current technique in meters */
  readonly effectiveReach?: number;
}
 
/**
 * TrainingStatsOverlayHtml Component
 *
 * Html overlay displaying training performance metrics with Korean theming.
 * All colors use KOREAN_COLORS constants for consistency.
 *
 * Optimized with React.memo for 60fps performance:
 * - Memoized with custom comparison function
 * - Only re-renders when stats actually change
 * - Reduces unnecessary DOM updates
 *
 * @example
 * ```tsx
 * <TrainingStatsOverlayHtml
 *   stats={{ score: 1500, combo: 8, hits: 45, misses: 5, accuracy: 90 }}
 *   isMobile={false}
 * />
 * ```
 *
 * @korean 훈련통계오버레이컴포넌트
 */
export const TrainingStatsOverlayHtml =
  React.memo<TrainingStatsOverlayHtmlProps>(
    ({
      stats,
      isMobile,
      width = 375,
      distanceToDummy,
      effectiveReach = 0.7, // Default punch reach
    }) => {
      // Use full width of container (passed from parent HUD)
      const panelWidth = width > 10 ? width : isMobile ? 180 : 200;
      const padding = getResponsiveSpacing("sm", isMobile);
      const gap = getResponsiveSpacing("xs", isMobile);
 
      // Safe area support for notched devices
      const safeAreaStyles = useMemo(
        () => (isMobile ? getSafeAreaPadding(["top"], padding) : {}),
        [isMobile, padding],
      );
 
      // Format accuracy with memoization
      const formattedAccuracy = useMemo(
        () => stats.accuracy.toFixed(1),
        [stats.accuracy],
      );
 
      // Format session duration
      const formattedDuration = useMemo(() => {
        Eif (!stats.sessionDuration) return "00:00";
        const minutes = Math.floor(stats.sessionDuration / 60);
        const seconds = stats.sessionDuration % 60;
        return `${minutes.toString().padStart(2, "0")}:${seconds.toString().padStart(2, "0")}`;
      }, [stats.sessionDuration]);
 
      // Format distance to dummy and check if in range
      const distanceInfo = useMemo(() => {
        if (distanceToDummy === undefined) return null;
        const isInRange = distanceToDummy <= effectiveReach;
        return {
          formatted: distanceToDummy.toFixed(2),
          isInRange,
          rangeStatus: isInRange
            ? "사정거리 내 | In Range"
            : "사정거리 밖 | Out of Range",
        };
      }, [distanceToDummy, effectiveReach]);
 
      // Calculate perfect strike rate
      const perfectRate = useMemo(() => {
        const totalAttempts = stats.hits + stats.misses;
        Eif (totalAttempts === 0 || !stats.perfectStrikes) return "0";
        return ((stats.perfectStrikes / totalAttempts) * 100).toFixed(1);
      }, [stats.hits, stats.misses, stats.perfectStrikes]);
 
      // Enhanced panel styles with neon glow and safe area support
      const panelStyle: React.CSSProperties = {
        ...getEnhancedKoreanOverlayStyles({
          opacity: 0.92,
          glowIntensity: "medium",
          includeGradient: false,
          includeBackdropBlur: true,
          depthLayers: 3,
        }),
        ...safeAreaStyles,
        width: `${panelWidth}px`,
        padding: `${padding}px`,
      };
 
      // Header title styles with improved mobile font size (16px+ for Korean)
      const titleFontSize = isMobile
        ? getMobileKoreanFontSize("SMALL", width ?? 375) // 16px minimum
        : 18;
 
      return (
        <div style={panelStyle} data-testid="training-stats-html">
          {/* Header with bilingual title */}
          <div style={{ marginBottom: `${padding}px` }}>
            <div
              style={{
                fontSize: `${titleFontSize}px`,
                fontWeight: "bold",
                color: hexToRgbaString(KOREAN_COLORS.ACCENT_GOLD),
                fontFamily: FONT_FAMILY.KOREAN,
                textShadow: getNeonTextShadow(
                  KOREAN_COLORS.ACCENT_GOLD,
                  "medium",
                ),
                transition: getSmoothTransition("all", "normal"),
              }}
            >
              {formatBilingualText("훈련 통계", "Training Statistics", "pipe")}
            </div>
          </div>
 
          {/* Stats Grid with consistent Korean theming */}
          <div
            style={{
              display: "flex",
              flexDirection: "column",
              gap: `${gap}px`,
            }}
          >
            {/* Score - 점수 */}
            <StatRow
              korean="점수"
              english="Score"
              value={stats.score.toLocaleString()}
              color={KOREAN_COLORS.ACCENT_GOLD}
              isMobile={isMobile}
              width={width}
            />
 
            {/* Combo - 콤보 */}
            <StatRow
              korean="콤보"
              english="Combo"
              value={`${stats.combo}x`}
              color={
                stats.combo > 5
                  ? KOREAN_COLORS.ACCENT_RED
                  : KOREAN_COLORS.PRIMARY_CYAN
              }
              isMobile={isMobile}
              width={width}
            />
 
            {/* Hits - 성공 */}
            <StatRow
              korean="성공"
              english="Hits"
              value={stats.hits.toString()}
              color={KOREAN_COLORS.ACCENT_GREEN}
              isMobile={isMobile}
              width={width}
            />
 
            {/* Misses - 실패 */}
            <StatRow
              korean="실패"
              english="Misses"
              value={stats.misses.toString()}
              color={KOREAN_COLORS.TEXT_TERTIARY}
              isMobile={isMobile}
              width={width}
            />
 
            {/* Accuracy - 정확도 */}
            <StatRow
              korean="정확도"
              english="Accuracy"
              value={`${formattedAccuracy}%`}
              color={
                stats.accuracy >= 80
                  ? KOREAN_COLORS.ACCENT_GREEN
                  : stats.accuracy >= 50
                    ? KOREAN_COLORS.ACCENT_GOLD
                    : KOREAN_COLORS.ACCENT_RED
              }
              isMobile={isMobile}
              width={width}
            />
 
            {/* Session Duration - 시간 */}
            {stats.sessionDuration !== undefined && (
              <StatRow
                korean="시간"
                english="Duration"
                value={formattedDuration}
                color={KOREAN_COLORS.PRIMARY_CYAN}
                isMobile={isMobile}
                width={width}
              />
            )}
 
            {/* Best Combo - 최고 콤보 */}
            {stats.bestCombo !== undefined && stats.bestCombo > 0 && (
              <StatRow
                korean="최고 콤보"
                english="Best Combo"
                value={`${stats.bestCombo}x`}
                color={KOREAN_COLORS.ACCENT_GOLD}
                isMobile={isMobile}
                width={width}
              />
            )}
 
            {/* Perfect Rate - 완벽률 */}
            {stats.hits + stats.misses > 0 && (
              <StatRow
                korean="완벽률"
                english="Perfect Rate"
                value={`${perfectRate}%`}
                color={
                  parseFloat(perfectRate) >= 30
                    ? KOREAN_COLORS.ACCENT_GOLD
                    : parseFloat(perfectRate) >= 10
                      ? KOREAN_COLORS.PRIMARY_CYAN
                      : KOREAN_COLORS.TEXT_TERTIARY
                }
                isMobile={isMobile}
                width={width}
              />
            )}
 
            {/* Distance to Dummy - 거리 */}
            {distanceInfo && (
              <>
                <StatRow
                  korean="거리"
                  english="Distance"
                  value={`${distanceInfo.formatted}m`}
                  color={
                    distanceInfo.isInRange
                      ? KOREAN_COLORS.ACCENT_GREEN
                      : KOREAN_COLORS.ACCENT_RED
                  }
                  isMobile={isMobile}
                  width={width}
                />
                <StatRow
                  korean="상태"
                  english="Status"
                  value={
                    distanceInfo.rangeStatus.split(" | ")[isMobile ? 0 : 1]
                  }
                  color={
                    distanceInfo.isInRange
                      ? KOREAN_COLORS.ACCENT_GREEN
                      : KOREAN_COLORS.ACCENT_RED
                  }
                  isMobile={isMobile}
                  width={width}
                />
              </>
            )}
          </div>
        </div>
      );
    },
    (prevProps, nextProps) => {
      // Custom comparison for optimal re-render prevention
      // Only re-render if stats values actually changed
      return (
        prevProps.stats.score === nextProps.stats.score &&
        prevProps.stats.combo === nextProps.stats.combo &&
        prevProps.stats.hits === nextProps.stats.hits &&
        prevProps.stats.misses === nextProps.stats.misses &&
        prevProps.stats.accuracy === nextProps.stats.accuracy &&
        prevProps.stats.sessionDuration === nextProps.stats.sessionDuration &&
        prevProps.stats.bestCombo === nextProps.stats.bestCombo &&
        prevProps.stats.perfectStrikes === nextProps.stats.perfectStrikes &&
        prevProps.isMobile === nextProps.isMobile &&
        prevProps.width === nextProps.width &&
        prevProps.distanceToDummy === nextProps.distanceToDummy &&
        prevProps.effectiveReach === nextProps.effectiveReach
      );
    },
  );
 
TrainingStatsOverlayHtml.displayName = "TrainingStatsOverlayHtml";
 
/**
 * Single stat row component with Korean theming
 *
 * Uses KOREAN_COLORS constants for all text colors
 * Enhanced with smooth transitions and neon glow on value
 *
 * Optimized with React.memo for performance
 *
 * @korean 통계행컴포넌트
 */
const StatRow = React.memo<{
  korean: string;
  english: string;
  value: string;
  color: number; // Numeric hex color from KOREAN_COLORS (e.g., 0x00ffff)
  isMobile: boolean;
  width: number; // Width for Super HD font scaling
}>(({ korean, english, value, color, isMobile, width }) => {
  // Improved font sizes for mobile readability (min 16px for Korean body text)
  const labelFontSize = isMobile
    ? getMobileKoreanFontSize("SMALL", width) // 16px minimum
    : 14;
  const sublabelFontSize = isMobile ? 12 : 11; // Increased from 8-9px
  const valueFontSize = isMobile
    ? getMobileKoreanFontSize("MEDIUM", width) // 18px minimum
    : 20;
 
  return (
    <div
      style={{
        display: "flex",
        justifyContent: "space-between",
        alignItems: "center",
        paddingBottom: `${SPACING.SM}px`,
        borderBottom: `1px solid ${hexToRgbaString(KOREAN_COLORS.TEXT_PRIMARY, 0.1)}`,
        transition: getSmoothTransition("all", "normal"),
      }}
    >
      <div>
        <div
          style={{
            fontSize: `${labelFontSize}px`,
            color: hexToRgbaString(KOREAN_COLORS.PRIMARY_CYAN),
            fontWeight: "bold",
            fontFamily: FONT_FAMILY.KOREAN,
            textShadow: getNeonTextShadow(KOREAN_COLORS.PRIMARY_CYAN, "subtle"),
          }}
        >
          {korean}
        </div>
        <div
          style={{
            fontSize: `${sublabelFontSize}px`,
            color: hexToRgbaString(KOREAN_COLORS.TEXT_TERTIARY),
            fontFamily: FONT_FAMILY.KOREAN,
          }}
        >
          {english}
        </div>
      </div>
      <div
        style={{
          fontSize: `${valueFontSize}px`,
          fontWeight: "bold",
          color: hexToRgbaString(color),
          fontFamily: FONT_FAMILY.KOREAN,
          textShadow: getNeonTextShadow(color, "medium"),
          transition: getSmoothTransition("transform, color", "normal"),
          transform: "scale(1)",
        }}
      >
        {value}
      </div>
    </div>
  );
});
 
StatRow.displayName = "StatRow";
 
export default TrainingStatsOverlayHtml;