All files / web/src/arcade-games/rithmomachia/components/capture CaptureRelationOptions.tsx

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

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       
'use client'

import * as Tooltip from '@radix-ui/react-tooltip'
import { animated, useSpring } from '@react-spring/web'
import { useEffect, useState } from 'react'
import { getRelationColor, getRelationOperator } from '../../constants/captureRelations'
import type { RelationKind } from '../../types'
import { useCaptureContext } from '../../contexts/CaptureContext'
import { getEffectiveValue } from '../../utils/pieceSetup'
import { getSquarePosition } from '../../utils/boardCoordinates'

interface CaptureRelationOptionsProps {
  availableRelations: RelationKind[]
}

/**
 * Animated floating capture relation options with number bond preview on hover
 */
export function CaptureRelationOptions({ availableRelations }: CaptureRelationOptionsProps) {
  const {
    layout,
    pieces,
    closing,
    allPieces,
    pyramidFaceValues,
    findValidHelpers,
    selectRelation,
  } = useCaptureContext()
  const { targetPos, cellSize, gap, padding } = layout
  const { mover: moverPiece, target: targetPiece } = pieces
  const [hoveredRelation, setHoveredRelation] = useState<RelationKind | null>(null)
  const [currentHelperIndex, setCurrentHelperIndex] = useState(0)

  // Get mover value - either from pyramidFaceValues map (for pyramids) or from piece directly
  const getMoverValue = (relation: RelationKind): number | null => {
    if (pyramidFaceValues && pyramidFaceValues.has(relation)) {
      return pyramidFaceValues.get(relation) || null
    }
    return getEffectiveValue(moverPiece)
  }

  // Cycle through valid helpers every 1.5 seconds when hovering
  useEffect(() => {
    if (!hoveredRelation) {
      setCurrentHelperIndex(0)
      return
    }

    const moverValue = getMoverValue(hoveredRelation)
    const targetValue = getEffectiveValue(targetPiece)

    if (
      moverValue === undefined ||
      moverValue === null ||
      targetValue === undefined ||
      targetValue === null
    ) {
      return
    }

    const validHelpers = findValidHelpers(moverValue, targetValue, hoveredRelation)
    if (validHelpers.length <= 1) {
      // No need to cycle if only one or zero helpers
      setCurrentHelperIndex(0)
      return
    }

    // Cycle through helpers every 1.5 seconds
    const interval = setInterval(() => {
      setCurrentHelperIndex((prev) => (prev + 1) % validHelpers.length)
    }, 1500)

    return () => clearInterval(interval)
  }, [hoveredRelation, pyramidFaceValues, targetPiece, findValidHelpers])

  // Generate tooltip text with actual numbers for the currently displayed helper
  const getTooltipText = (relation: RelationKind): string => {
    if (relation !== hoveredRelation) {
      // Not hovered, use generic text
      const genericMap: Record<RelationKind, string> = {
        EQUAL: 'Equality: a = b',
        MULTIPLE: 'Multiple: b is multiple of a',
        DIVISOR: 'Divisor: a divides b',
        SUM: 'Sum: a + h = b (helper)',
        DIFF: 'Difference: |a - h| = b (helper)',
        PRODUCT: 'Product: a × h = b (helper)',
        RATIO: 'Ratio: a/h = b/h (helper)',
      }
      return genericMap[relation] || relation
    }

    const moverValue = getMoverValue(relation)
    const targetValue = getEffectiveValue(targetPiece)

    if (
      moverValue === undefined ||
      moverValue === null ||
      targetValue === undefined ||
      targetValue === null
    ) {
      return relation
    }

    // Relations that don't need helpers - show equation with just mover and target
    const helperRelations: RelationKind[] = ['SUM', 'DIFF', 'PRODUCT', 'RATIO']
    const needsHelper = helperRelations.includes(relation)

    if (!needsHelper) {
      // Generate equation with just mover and target values
      switch (relation) {
        case 'EQUAL':
          return `${moverValue} = ${targetValue}`
        case 'MULTIPLE':
          return `${targetValue} is multiple of ${moverValue}`
        case 'DIVISOR':
          return `${moverValue} divides ${targetValue}`
        default:
          return relation
      }
    }

    // Relations that need helpers
    const validHelpers = findValidHelpers(moverValue, targetValue, relation)
    if (validHelpers.length === 0) {
      return `${relation}: No valid helpers`
    }

    const currentHelper = validHelpers[currentHelperIndex]
    const helperValue = getEffectiveValue(currentHelper)

    if (helperValue === undefined || helperValue === null) {
      return relation
    }

    // Generate equation with actual numbers including helper
    switch (relation) {
      case 'SUM':
        return `${moverValue} + ${helperValue} = ${targetValue}`
      case 'DIFF':
        return `|${moverValue} - ${helperValue}| = ${targetValue}`
      case 'PRODUCT':
        return `${moverValue} × ${helperValue} = ${targetValue}`
      case 'RATIO':
        return `${moverValue}/${helperValue} = ${targetValue}/${helperValue}`
      default:
        return relation
    }
  }

  const allRelations = [
    { relation: 'EQUAL', label: '=', angle: 0, color: '#8b5cf6' },
    {
      relation: 'MULTIPLE',
      label: '×n',
      angle: 51.4,
      color: '#a855f7',
    },
    {
      relation: 'DIVISOR',
      label: '÷',
      angle: 102.8,
      color: '#c084fc',
    },
    {
      relation: 'SUM',
      label: '+',
      angle: 154.3,
      color: '#3b82f6',
    },
    {
      relation: 'DIFF',
      label: '−',
      angle: 205.7,
      color: '#06b6d4',
    },
    {
      relation: 'PRODUCT',
      label: '×',
      angle: 257.1,
      color: '#10b981',
    },
    {
      relation: 'RATIO',
      label: '÷÷',
      angle: 308.6,
      color: '#f59e0b',
    },
  ]

  // Filter to only available relations and redistribute angles evenly
  const availableRelationDefs = allRelations.filter((r) =>
    availableRelations.includes(r.relation as RelationKind)
  )
  const angleStep = availableRelationDefs.length > 1 ? 360 / availableRelationDefs.length : 0
  const relations = availableRelationDefs.map((r, index) => ({
    ...r,
    angle: index * angleStep,
  }))

  const maxRadius = cellSize * 1.2
  const buttonSize = 64

  // Animate all buttons simultaneously - reverse animation when closing
  const spring = useSpring({
    from: { radius: 0, opacity: 0 },
    radius: closing ? 0 : maxRadius,
    opacity: closing ? 0 : 0.85,
    config: { tension: 280, friction: 20 },
  })

  return (
    <Tooltip.Provider delayDuration={0} disableHoverableContent>
      <g>
        {relations.map(({ relation, label, angle, color }) => {
          const rad = (angle * Math.PI) / 180

          return (
            <animated.g
              key={relation}
              transform={spring.radius.to(
                (r) =>
                  `translate(${targetPos.x + Math.cos(rad) * r}, ${targetPos.y + Math.sin(rad) * r})`
              )}
            >
              <foreignObject
                x={-buttonSize / 2}
                y={-buttonSize / 2}
                width={buttonSize}
                height={buttonSize}
                style={{ overflow: 'visible' }}
              >
                <Tooltip.Root>
                  <Tooltip.Trigger asChild>
                    <animated.button
                      onClick={(e) => {
                        e.stopPropagation()
                        selectRelation(relation as RelationKind)
                      }}
                      style={{
                        width: buttonSize,
                        height: buttonSize,
                        borderRadius: '50%',
                        border: '3px solid rgba(255, 255, 255, 0.9)',
                        backgroundColor: color,
                        color: 'white',
                        fontSize: '28px',
                        fontWeight: 'bold',
                        cursor: 'pointer',
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'center',
                        opacity: spring.opacity,
                        transition: 'transform 0.15s ease, box-shadow 0.15s ease',
                        boxShadow: '0 4px 12px rgba(0, 0, 0, 0.3)',
                        textShadow: '0 2px 4px rgba(0, 0, 0, 0.5)',
                      }}
                      onMouseEnter={(e) => {
                        e.currentTarget.style.transform = 'scale(1.15)'
                        e.currentTarget.style.boxShadow = '0 6px 20px rgba(0, 0, 0, 0.4)'
                        setHoveredRelation(relation as RelationKind)
                      }}
                      onMouseLeave={(e) => {
                        e.currentTarget.style.transform = 'scale(1)'
                        e.currentTarget.style.boxShadow = '0 4px 12px rgba(0, 0, 0, 0.3)'
                        setHoveredRelation(null)
                      }}
                    >
                      {label}
                    </animated.button>
                  </Tooltip.Trigger>
                  <Tooltip.Portal>
                    <Tooltip.Content asChild sideOffset={8}>
                      <div
                        style={{
                          background: 'rgba(0,0,0,0.95)',
                          color: 'white',
                          padding: '8px 16px',
                          borderRadius: '8px',
                          fontSize: '14px',
                          fontWeight: 600,
                          maxWidth: '240px',
                          zIndex: 10000,
                          boxShadow: '0 4px 12px rgba(0, 0, 0, 0.4)',
                          pointerEvents: 'none',
                        }}
                      >
                        {getTooltipText(relation as RelationKind)}
                        <Tooltip.Arrow
                          style={{
                            fill: 'rgba(0,0,0,0.95)',
                          }}
                        />
                      </div>
                    </Tooltip.Content>
                  </Tooltip.Portal>
                </Tooltip.Root>
              </foreignObject>
            </animated.g>
          )
        })}

        {/* Number bond preview when hovering over a relation - cycle through valid helpers */}
        {hoveredRelation &&
          (() => {
            const moverValue = getMoverValue(hoveredRelation)
            const targetValue = getEffectiveValue(targetPiece)

            if (
              moverValue === undefined ||
              moverValue === null ||
              targetValue === undefined ||
              targetValue === null
            ) {
              return null
            }

            const validHelpers = findValidHelpers(moverValue, targetValue, hoveredRelation)

            if (validHelpers.length === 0) {
              return null
            }

            // Show only the current helper
            const currentHelper = validHelpers[currentHelperIndex]

            const color = getRelationColor(hoveredRelation)
            const operator = getRelationOperator(hoveredRelation)

            // Calculate piece positions on board
            const layout = { cellSize, gap, padding }
            const moverPos = getSquarePosition(moverPiece.square, layout)
            const targetBoardPos = getSquarePosition(targetPiece.square, layout)
            const helperPos = getSquarePosition(currentHelper.square, layout)

            return (
              <g key={currentHelper.id}>
                {/* Triangle connecting lines */}
                <g opacity={0.5}>
                  <line
                    x1={moverPos.x}
                    y1={moverPos.y}
                    x2={helperPos.x}
                    y2={helperPos.y}
                    stroke={color}
                    strokeWidth={4}
                  />
                  <line
                    x1={moverPos.x}
                    y1={moverPos.y}
                    x2={targetBoardPos.x}
                    y2={targetBoardPos.y}
                    stroke={color}
                    strokeWidth={4}
                  />
                  <line
                    x1={helperPos.x}
                    y1={helperPos.y}
                    x2={targetBoardPos.x}
                    y2={targetBoardPos.y}
                    stroke={color}
                    strokeWidth={4}
                  />
                </g>

                {/* Operator symbol - smart placement to avoid collinear collapse */}
                {(() => {
                  // Calculate center of triangle
                  const centerX = (moverPos.x + helperPos.x + targetBoardPos.x) / 3
                  const centerY = (moverPos.y + helperPos.y + targetBoardPos.y) / 3

                  // Check if pieces are nearly collinear using cross product
                  // Vector from mover to helper
                  const v1x = helperPos.x - moverPos.x
                  const v1y = helperPos.y - moverPos.y
                  // Vector from mover to target
                  const v2x = targetBoardPos.x - moverPos.x
                  const v2y = targetBoardPos.y - moverPos.y

                  // Cross product magnitude (2D)
                  const crossProduct = Math.abs(v1x * v2y - v1y * v2x)

                  // If cross product is small, pieces are nearly collinear
                  const minTriangleArea = cellSize * cellSize * 0.5 // Minimum triangle area threshold
                  const isCollinear = crossProduct < minTriangleArea

                  let operatorX = centerX
                  let operatorY = centerY

                  if (isCollinear) {
                    // Find the line connecting the three points (use mover to target as reference)
                    const lineLength = Math.sqrt(v2x * v2x + v2y * v2y)

                    if (lineLength > 0) {
                      // Perpendicular direction (rotate 90 degrees)
                      const perpX = -v2y / lineLength
                      const perpY = v2x / lineLength

                      // Offset operator perpendicular to the line
                      const offsetDistance = cellSize * 0.8
                      operatorX = centerX + perpX * offsetDistance
                      operatorY = centerY + perpY * offsetDistance
                    }
                  }

                  return (
                    <text
                      x={operatorX}
                      y={operatorY}
                      textAnchor="middle"
                      dominantBaseline="central"
                      fill={color}
                      fontSize={cellSize * 0.8}
                      fontWeight="900"
                      fontFamily="Georgia, 'Times New Roman', serif"
                      opacity={0.9}
                    >
                      {operator}
                    </text>
                  )
                })()}
              </g>
            )
          })()}
      </g>
    </Tooltip.Provider>
  )
}