All files / web/src/arcade-games/know-your-world/features/magnifier MagnifierOverlay.tsx

0% Statements 0/551
0% Branches 0/1
0% Functions 0/1
0% Lines 0/551

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 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               
/**
 * Magnifier Overlay Component
 *
 * Renders the magnified view of the map centered on cursor position.
 * Includes:
 * - Zoomed SVG view of map regions
 * - Crosshair at cursor position
 * - Pixel grid for precision mode
 * - Debug bounding boxes (optional)
 * - Zoom label with precision mode indicator
 * - Mobile controls (expand, select, full map)
 *
 * Extracted from MapRenderer to improve maintainability.
 *
 * This component can consume state from:
 * - MagnifierContext (magnifier-specific state, refs, springs)
 * - MapGameContext (game state, callbacks, debug info)
 *
 * When used with context providers, most props become optional.
 */

'use client'

import { animated, type SpringValue } from '@react-spring/web'
import { getRegionColor, getRegionStroke } from '../../mapColors'
import {
  getAdjustedMagnifiedDimensions,
  getMagnifierDimensions,
} from '../../utils/magnifierDimensions'
import { calculateScreenPixelRatio, isAboveThreshold } from '../../utils/screenPixelRatio'
import { useMapGameContext } from '../game'
import { getRenderedViewport } from '../labels'
import { useMagnifierContext } from './MagnifierContext'
import { MagnifierControls } from './MagnifierControls'
import { MagnifierCrosshair } from './MagnifierCrosshair'
import { MagnifierPixelGrid } from './MagnifierPixelGrid'
import { MagnifierRegions } from './MagnifierRegions'

// ============================================================================
// Types
// ============================================================================

export interface MagnifierOverlayProps {
  // These props are ONLY needed if not using context or for overrides
  // When wrapped in MagnifierProvider + MapGameProvider, these are optional

  // Crosshair rotation (not in context - specific to this component)
  rotationAngle: SpringValue<number>

  // Touch handlers (not in context yet - will be extracted to hook)
  handleMagnifierTouchStart: (e: React.TouchEvent<HTMLDivElement>) => void
  handleMagnifierTouchMove: (e: React.TouchEvent<HTMLDivElement>) => void
  handleMagnifierTouchEnd: (e: React.TouchEvent<HTMLDivElement>) => void
}

// ============================================================================
// Component
// ============================================================================

export function MagnifierOverlay({
  rotationAngle,
  handleMagnifierTouchStart,
  handleMagnifierTouchMove,
  handleMagnifierTouchEnd,
}: MagnifierOverlayProps) {
  // -------------------------------------------------------------------------
  // Context Consumption
  // -------------------------------------------------------------------------
  const {
    magnifierRef,
    svgRef,
    containerRef,
    cursorPosition,
    zoomSpring,
    magnifierSpring,
    parsedViewBox,
    safeZoneMargins,
    isMagnifierExpanded,
    setIsMagnifierExpanded,
    isDark,
    pointerLocked,
    isTouchDevice,
    canUsePrecisionMode,
    mobileMapDragTriggeredMagnifier,
    isMobileMapDragging,
    isMagnifierDragging,
    precisionModeThreshold,
    precisionCalcs,
    getCurrentZoom,
    highZoomThreshold,
    scaleProbe1Ref,
    scaleProbe2Ref,
    anchorProbeRef,
    anchorSvgPositionRef,
    interaction,
  } = useMagnifierContext()

  // Distance between scale probes in SVG units (must match useEmpiricalScale.ts)
  const SCALE_PROBE_DISTANCE = 100

  const {
    mapData,
    regionsFound,
    hoveredRegion,
    celebration,
    giveUpReveal,
    isGiveUpAnimating,
    celebrationFlashProgress,
    giveUpFlashProgress,
    effectiveHotColdEnabled,
    hotColdFeedbackType,
    magnifierBorderStyle,
    crosshairHeatStyle,
    effectiveShowDebugBoundingBoxes,
    effectiveShowMagnifierDebugInfo,
    debugBoundingBoxes,
    getPlayerWhoFoundRegion,
    showOutline,
    selectRegionAtCrosshairs,
    requestPointerLock,
  } = useMapGameContext()

  // -------------------------------------------------------------------------
  // Early Returns
  // -------------------------------------------------------------------------
  // Get container and SVG info for viewBox calculations
  const containerRect = containerRef.current?.getBoundingClientRect()
  if (!containerRect || !svgRef.current || !cursorPosition) {
    return null
  }

  // Calculate leftover area for debug/label positioning (not for magnifier sizing)
  const leftoverWidth = containerRect.width - safeZoneMargins.left - safeZoneMargins.right
  const leftoverHeight = containerRect.height - safeZoneMargins.top - safeZoneMargins.bottom

  const svgRect = svgRef.current.getBoundingClientRect()
  const { x: viewBoxX, y: viewBoxY, width: viewBoxWidth, height: viewBoxHeight } = parsedViewBox

  return (
    <animated.div
      ref={magnifierRef}
      data-element="magnifier"
      onTouchStart={handleMagnifierTouchStart}
      onTouchMove={handleMagnifierTouchMove}
      onTouchEnd={handleMagnifierTouchEnd}
      onTouchCancel={handleMagnifierTouchEnd}
      style={{
        position: 'absolute',
        // Position and size are always animated via react-spring
        top: magnifierSpring.top,
        left: magnifierSpring.left,
        width: magnifierSpring.width,
        height: magnifierSpring.height,
        // Border color priority: 1) Hot/cold heat colors (if enabled), 2) High zoom gold, 3) Default blue
        border: (() => {
          // When hot/cold is enabled, use heat-based colors (from memoized magnifierBorderStyle)
          if (effectiveHotColdEnabled && hotColdFeedbackType) {
            return `${magnifierBorderStyle.width}px solid ${magnifierBorderStyle.border}`
          }
          // Fall back to zoom-based coloring
          return zoomSpring.to(
            (zoom: number) =>
              zoom > highZoomThreshold
                ? `4px solid ${isDark ? '#fbbf24' : '#f59e0b'}` // gold-400/gold-500
                : `3px solid ${isDark ? '#60a5fa' : '#3b82f6'}` // blue-400/blue-600
          )
        })(),
        borderRadius: '12px',
        overflow: 'hidden',
        // Enable touch events on mobile for panning, but keep mouse events disabled
        pointerEvents: 'auto',
        touchAction: 'none', // Prevent browser handling of touch gestures
        zIndex: 100,
        // Box shadow with heat glow when hot/cold is enabled
        boxShadow: (() => {
          if (effectiveHotColdEnabled && hotColdFeedbackType) {
            return `0 10px 40px rgba(0, 0, 0, 0.3), 0 0 25px ${magnifierBorderStyle.glow}`
          }
          return zoomSpring.to((zoom: number) =>
            zoom > highZoomThreshold
              ? '0 10px 40px rgba(251, 191, 36, 0.4), 0 0 20px rgba(251, 191, 36, 0.2)' // Gold glow
              : '0 10px 40px rgba(0, 0, 0, 0.5)'
          )
        })(),
        background: isDark ? '#111827' : '#f3f4f6',
        opacity: magnifierSpring.opacity,
      }}
    >
      <animated.svg
        viewBox={zoomSpring.to((zoom: number) => {
          // Calculate magnified viewBox centered on cursor
          const viewport = getRenderedViewport(
            svgRect,
            viewBoxX,
            viewBoxY,
            viewBoxWidth,
            viewBoxHeight
          )

          // Center position relative to SVG (uses reveal center during give-up animation)
          const svgOffsetX = svgRect.left - containerRect.left + viewport.letterboxX
          const svgOffsetY = svgRect.top - containerRect.top + viewport.letterboxY
          const cursorSvgX = (cursorPosition.x - svgOffsetX) / viewport.scale + viewBoxX
          const cursorSvgY = (cursorPosition.y - svgOffsetY) / viewport.scale + viewBoxY

          // Magnified view: adjust dimensions to match magnifier container aspect ratio
          const leftoverW = containerRect.width - safeZoneMargins.left - safeZoneMargins.right
          const leftoverH = containerRect.height - safeZoneMargins.top - safeZoneMargins.bottom
          const { width: magnifiedWidth, height: magnifiedHeight } = getAdjustedMagnifiedDimensions(
            viewBoxWidth,
            viewBoxHeight,
            zoom,
            leftoverW,
            leftoverH
          )

          // Center the magnified viewBox on the cursor
          const magnifiedViewBoxX = cursorSvgX - magnifiedWidth / 2
          const magnifiedViewBoxY = cursorSvgY - magnifiedHeight / 2

          return `${magnifiedViewBoxX} ${magnifiedViewBoxY} ${magnifiedWidth} ${magnifiedHeight}`
        })}
        style={{
          width: '100%',
          height: '100%',
          // Apply "disabled" visual effect when precision mode is recommended (desktop only)
          filter: interaction.precisionModeRecommended ? 'brightness(0.6) saturate(0.5)' : 'none',
        }}
      >
        {/* Sea/ocean background for magnifier - solid color to match container */}
        <rect
          x={parsedViewBox.x}
          y={parsedViewBox.y}
          width={parsedViewBox.width}
          height={parsedViewBox.height}
          fill={isDark ? '#1e3a5f' : '#a8d4f0'}
        />

        {/* Render all regions in magnified view */}
        <MagnifierRegions
          regions={mapData.regions}
          regionState={{
            regionsFound,
            hoveredRegion,
            celebrationRegionId: celebration?.regionId ?? null,
            giveUpRegionId: giveUpReveal?.regionId ?? null,
            isGiveUpAnimating,
          }}
          flashProgress={{
            celebrationFlash: celebrationFlashProgress,
            giveUpFlash: giveUpFlashProgress,
          }}
          isDark={isDark}
          getPlayerWhoFoundRegion={getPlayerWhoFoundRegion}
          getRegionColor={getRegionColor}
          getRegionStroke={getRegionStroke}
          showOutline={showOutline}
        />

        {/* Crosshair at center position + Scale probes for empirical measurement */}
        {(() => {
          const viewport = getRenderedViewport(
            svgRect,
            viewBoxX,
            viewBoxY,
            viewBoxWidth,
            viewBoxHeight
          )
          const svgOffsetX = svgRect.left - containerRect.left + viewport.letterboxX
          const svgOffsetY = svgRect.top - containerRect.top + viewport.letterboxY
          const cursorSvgX = (cursorPosition.x - svgOffsetX) / viewport.scale + viewBoxX
          const cursorSvgY = (cursorPosition.y - svgOffsetY) / viewport.scale + viewBoxY

          return (
            <>
              <MagnifierCrosshair
                cursorSvgX={cursorSvgX}
                cursorSvgY={cursorSvgY}
                viewBoxWidth={viewBoxWidth}
                rotationAngle={rotationAngle}
                heatStyle={crosshairHeatStyle}
              />
              {/* Scale probe circles for empirical 1:1 tracking measurement */}
              {/* These are invisible but their screen positions are measured via getBoundingClientRect */}
              <circle
                ref={scaleProbe1Ref}
                cx={cursorSvgX - SCALE_PROBE_DISTANCE / 2}
                cy={cursorSvgY}
                r={0.5}
                fill="transparent"
                stroke="none"
                pointerEvents="none"
                data-scale-probe="1"
              />
              <circle
                ref={scaleProbe2Ref}
                cx={cursorSvgX + SCALE_PROBE_DISTANCE / 2}
                cy={cursorSvgY}
                r={0.5}
                fill="transparent"
                stroke="none"
                pointerEvents="none"
                data-scale-probe="2"
              />
              {/* Anchor probe for closed-loop 1:1 tracking */}
              {/* Position is set on touch start and stays fixed in SVG coords */}
              {/* We measure its screen position to solve for cursor movement */}
              {anchorSvgPositionRef.current && (
                <circle
                  ref={anchorProbeRef}
                  cx={anchorSvgPositionRef.current.x}
                  cy={anchorSvgPositionRef.current.y}
                  r={0.5}
                  fill="transparent"
                  stroke="none"
                  pointerEvents="none"
                  data-anchor-probe="true"
                />
              )}
            </>
          )
        })()}

        {/* Pixel grid overlay - shows when approaching/at/above precision mode threshold */}
        {(() => {
          if (!viewBoxWidth || Number.isNaN(viewBoxWidth)) return null

          const currentZoom = getCurrentZoom()
          const viewport = getRenderedViewport(
            svgRect,
            viewBoxX,
            viewBoxY,
            viewBoxWidth,
            viewBoxHeight
          )
          const svgOffsetX = svgRect.left - containerRect.left + viewport.letterboxX
          const svgOffsetY = svgRect.top - containerRect.top + viewport.letterboxY
          const cursorSvgX = (cursorPosition.x - svgOffsetX) / viewport.scale + viewBoxX
          const cursorSvgY = (cursorPosition.y - svgOffsetY) / viewport.scale + viewBoxY

          return (
            <MagnifierPixelGrid
              currentZoom={currentZoom}
              screenPixelRatio={precisionCalcs.screenPixelRatio}
              precisionModeThreshold={precisionModeThreshold}
              cursorSvgX={cursorSvgX}
              cursorSvgY={cursorSvgY}
              viewBoxWidth={viewBoxWidth}
              viewBoxHeight={viewBoxHeight}
              viewportScale={viewport.scale}
              isDark={isDark}
              enabled={canUsePrecisionMode}
            />
          )
        })()}

        {/* Debug: Bounding boxes for detected regions in magnifier */}
        {effectiveShowDebugBoundingBoxes &&
          debugBoundingBoxes.map((bbox) => {
            const importance = bbox.importance ?? 0
            let strokeColor = '#888888'
            if (bbox.wasAccepted) {
              strokeColor = '#00ff00'
            } else if (importance > 1.5) {
              strokeColor = '#ff6600'
            } else if (importance > 0.5) {
              strokeColor = '#ffcc00'
            }

            return (
              <rect
                key={`mag-bbox-${bbox.regionId}`}
                x={bbox.x}
                y={bbox.y}
                width={bbox.width}
                height={bbox.height}
                fill="none"
                stroke={strokeColor}
                strokeWidth={1}
                vectorEffect="non-scaling-stroke"
                pointerEvents="none"
              />
            )
          })}
      </animated.svg>

      {/* Debug: Bounding box labels as HTML overlays */}
      {effectiveShowDebugBoundingBoxes &&
        debugBoundingBoxes.map((bbox) => {
          const importance = bbox.importance ?? 0
          let strokeColor = '#888888'
          if (bbox.wasAccepted) {
            strokeColor = '#00ff00'
          } else if (importance > 1.5) {
            strokeColor = '#ff6600'
          } else if (importance > 0.5) {
            strokeColor = '#ffcc00'
          }

          const bboxCenterSvgX = bbox.x + bbox.width / 2
          const bboxCenterSvgY = bbox.y + bbox.height / 2

          return (
            <animated.div
              key={`mag-bbox-label-${bbox.regionId}`}
              style={{
                position: 'absolute',
                left: zoomSpring.to((zoom: number) => {
                  const viewport = getRenderedViewport(
                    svgRect,
                    viewBoxX,
                    viewBoxY,
                    viewBoxWidth,
                    viewBoxHeight
                  )
                  const svgOffsetX = svgRect.left - containerRect.left + viewport.letterboxX
                  const cursorSvgX = (cursorPosition.x - svgOffsetX) / viewport.scale + viewBoxX
                  const magnifiedWidth = viewBoxWidth / zoom
                  const magnifiedViewBoxX = cursorSvgX - magnifiedWidth / 2
                  const relativeX = (bboxCenterSvgX - magnifiedViewBoxX) / magnifiedWidth
                  if (relativeX < 0 || relativeX > 1) return '-9999px'

                  const { width: magnifierWidth } = getMagnifierDimensions(
                    leftoverWidth,
                    leftoverHeight
                  )
                  return `${relativeX * magnifierWidth}px`
                }),
                top: zoomSpring.to((zoom: number) => {
                  const viewport = getRenderedViewport(
                    svgRect,
                    viewBoxX,
                    viewBoxY,
                    viewBoxWidth,
                    viewBoxHeight
                  )
                  const svgOffsetY = svgRect.top - containerRect.top + viewport.letterboxY
                  const cursorSvgY = (cursorPosition.y - svgOffsetY) / viewport.scale + viewBoxY
                  const magnifiedHeight = viewBoxHeight / zoom
                  const magnifiedViewBoxY = cursorSvgY - magnifiedHeight / 2
                  const relativeY = (bboxCenterSvgY - magnifiedViewBoxY) / magnifiedHeight
                  if (relativeY < 0 || relativeY > 1) return '-9999px'

                  const { height: magnifierHeight } = getMagnifierDimensions(
                    leftoverWidth,
                    leftoverHeight
                  )
                  return `${relativeY * magnifierHeight}px`
                }),
                transform: 'translate(-50%, -50%)',
                pointerEvents: 'none',
                zIndex: 15,
                fontSize: '10px',
                fontWeight: 'bold',
                color: strokeColor,
                textAlign: 'center',
                textShadow: '0 0 2px black, 0 0 2px black, 0 0 2px black',
                whiteSpace: 'nowrap',
              }}
            >
              <div>{bbox.regionId}</div>
              <div style={{ fontSize: '8px', fontWeight: 'normal' }}>{importance.toFixed(2)}</div>
            </animated.div>
          )
        })}

      {/* Magnifier label */}
      <animated.div
        style={{
          position: 'absolute',
          top: '8px',
          left: '8px',
          padding: '4px 8px',
          background: isDark ? 'rgba(31, 41, 55, 0.9)' : 'rgba(255, 255, 255, 0.9)',
          borderRadius: '6px',
          fontSize: '11px',
          fontWeight: 'bold',
          color: isDark ? '#60a5fa' : '#3b82f6',
          pointerEvents: pointerLocked ? 'none' : 'auto',
          cursor: pointerLocked ? 'default' : 'pointer',
        }}
        onClick={(e) => {
          if (!pointerLocked) {
            e.stopPropagation()
            requestPointerLock()
          }
        }}
        data-element="magnifier-label"
      >
        {zoomSpring.to((z: number) => {
          if (pointerLocked) {
            return 'Precision mode active'
          }

          if (!viewBoxWidth || Number.isNaN(viewBoxWidth)) {
            return `${z.toFixed(1)}×`
          }

          const { width: magnifierWidth } = getMagnifierDimensions(leftoverWidth, leftoverHeight)
          const screenPixelRatio = calculateScreenPixelRatio({
            magnifierWidth,
            viewBoxWidth,
            svgWidth: svgRect.width,
            zoom: z,
          })

          if (canUsePrecisionMode && isAboveThreshold(screenPixelRatio, precisionModeThreshold)) {
            return 'Click to activate precision mode'
          }

          if (effectiveShowMagnifierDebugInfo) {
            return `${z.toFixed(1)}× | ${screenPixelRatio.toFixed(1)} px/px`
          }

          return `${z.toFixed(1)}×`
        })}
      </animated.div>

      {/* Scrim overlay - shows when precision mode is recommended (desktop only) */}
      {interaction.precisionModeRecommended && (
        <div
          data-element="precision-mode-scrim"
          style={{
            position: 'absolute',
            inset: 0,
            background: 'rgba(251, 191, 36, 0.15)',
            pointerEvents: 'none',
            borderRadius: '12px',
          }}
        />
      )}

      {/* Mobile magnifier controls (Expand, Select, Close buttons) */}
      <MagnifierControls
        isTouchDevice={isTouchDevice}
        showSelectButton={
          mobileMapDragTriggeredMagnifier && !isMobileMapDragging && !isMagnifierDragging
        }
        isExpanded={isMagnifierExpanded}
        isSelectDisabled={!hoveredRegion || regionsFound.includes(hoveredRegion)}
        isDark={isDark}
        pointerLocked={pointerLocked}
        hideControls={isMagnifierDragging}
        onSelect={selectRegionAtCrosshairs}
        onExitExpanded={() => setIsMagnifierExpanded(false)}
        onExpand={() => setIsMagnifierExpanded(true)}
        onClose={() => interaction.dispatch({ type: 'MAGNIFIER_DEACTIVATED' })}
      />
    </animated.div>
  )
}