All files / web/src/components/ui InteractiveDice.tsx

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

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 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 
'use client'

import { animated, useSpring } from '@react-spring/web'
import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react'
import { createPortal } from 'react-dom'
import { useTheme } from '@/contexts/ThemeContext'
import {
  type CubeOrientation,
  type TipDirection,
  orientationForFace,
  applyTip,
} from '@/lib/cubeOrientation'
import { type JoltEvent, type JoltConfig, DEFAULT_JOLT_CONFIG } from '@/hooks/useDeviceJolt'

export interface DiceColorScheme {
  faceLight: string
  faceDark: string
  dotLight: string
  dotDark: string
}

// Dot patterns for each dice face (positions as fractions of face size)
const DICE_DOT_PATTERNS: Record<number, Array<[number, number]>> = {
  1: [[0.5, 0.5]],
  2: [
    [0.25, 0.25],
    [0.75, 0.75],
  ],
  3: [
    [0.25, 0.25],
    [0.5, 0.5],
    [0.75, 0.75],
  ],
  4: [
    [0.25, 0.25],
    [0.75, 0.25],
    [0.25, 0.75],
    [0.75, 0.75],
  ],
  5: [
    [0.25, 0.25],
    [0.75, 0.25],
    [0.5, 0.5],
    [0.25, 0.75],
    [0.75, 0.75],
  ],
  6: [
    [0.25, 0.2],
    [0.25, 0.5],
    [0.25, 0.8],
    [0.75, 0.2],
    [0.75, 0.5],
    [0.75, 0.8],
  ],
}

// Rotation needed to show each face
// Standard dice: 1 opposite 6, 2 opposite 5, 3 opposite 4
const DICE_FACE_ROTATIONS: Record<number, { rotateX: number; rotateY: number }> = {
  1: { rotateX: 0, rotateY: 0 }, // front
  2: { rotateX: 0, rotateY: -90 }, // right
  3: { rotateX: -90, rotateY: 0 }, // top
  4: { rotateX: 90, rotateY: 0 }, // bottom
  5: { rotateX: 0, rotateY: 90 }, // left
  6: { rotateX: 0, rotateY: 180 }, // back
}

/**
 * 3D Dice Icon using react-spring for smooth animations
 *
 * Creates a cube with 6 faces, each showing the appropriate dot pattern.
 * The cube rotates on all 3 axes when rolling, with physics-based easing.
 */
function DiceIcon({
  className,
  rotateX,
  rotateY,
  rotateZ,
  isDark,
  size = 22,
  colorScheme,
  perspective = 100,
}: {
  className?: string
  rotateX: number
  rotateY: number
  rotateZ: number
  isDark: boolean
  size?: number
  colorScheme?: DiceColorScheme
  perspective?: number
}) {
  const halfSize = size / 2

  // Animate rotation with react-spring
  const springProps = useSpring({
    rotateX,
    rotateY,
    rotateZ,
    config: {
      tension: 120,
      friction: 14,
    },
  })

  // Theme-aware colors
  // Dark mode: lighter indigo with more contrast against dark backgrounds
  // Light mode: deeper indigo that stands out against light backgrounds
  const faceBackground = colorScheme
    ? isDark
      ? colorScheme.faceDark
      : colorScheme.faceLight
    : isDark
      ? '#818cf8'
      : '#4f46e5' // indigo-400 dark, indigo-600 light
  const faceBorder = isDark ? 'rgba(255, 255, 255, 0.6)' : 'rgba(255, 255, 255, 0.5)'
  const dotColor = colorScheme
    ? isDark
      ? colorScheme.dotDark
      : colorScheme.dotLight
    : isDark
      ? '#1e1b4b'
      : 'white' // indigo-950 dots on light bg in dark mode

  // Render dots for a face
  const renderDots = (face: number) => {
    const dots = DICE_DOT_PATTERNS[face] || []
    return dots.map(([x, y], i) => (
      <div
        key={i}
        style={{
          position: 'absolute',
          left: `${x * 100}%`,
          top: `${y * 100}%`,
          width: '18%',
          height: '18%',
          backgroundColor: dotColor,
          borderRadius: '50%',
          transform: 'translate(-50%, -50%)',
        }}
      />
    ))
  }

  // Common face styles - opaque background to prevent artifacts during rotation
  const faceStyle: React.CSSProperties = {
    position: 'absolute',
    width: size,
    height: size,
    backgroundColor: faceBackground,
    border: `1.5px solid ${faceBorder}`,
    borderRadius: 2,
    backfaceVisibility: 'hidden',
    WebkitBackfaceVisibility: 'hidden',
  }

  return (
    <div
      className={className}
      style={{
        width: size,
        height: size,
        perspective,
        perspectiveOrigin: 'center',
      }}
    >
      <animated.div
        data-dice-cube
        style={{
          width: size,
          height: size,
          position: 'relative',
          transformStyle: 'preserve-3d',
          transform: springProps.rotateX.to(
            (rx) =>
              `rotateX(${rx}deg) rotateY(${springProps.rotateY.get()}deg) rotateZ(${springProps.rotateZ.get()}deg)`
          ),
        }}
      >
        {/* Front face (1) */}
        <div style={{ ...faceStyle, transform: `translateZ(${halfSize}px)` }}>{renderDots(1)}</div>
        {/* Back face (6) */}
        <div
          style={{
            ...faceStyle,
            transform: `rotateY(180deg) translateZ(${halfSize}px)`,
          }}
        >
          {renderDots(6)}
        </div>
        {/* Right face (2) */}
        <div
          style={{
            ...faceStyle,
            transform: `rotateY(90deg) translateZ(${halfSize}px)`,
          }}
        >
          {renderDots(2)}
        </div>
        {/* Left face (5) */}
        <div
          style={{
            ...faceStyle,
            transform: `rotateY(-90deg) translateZ(${halfSize}px)`,
          }}
        >
          {renderDots(5)}
        </div>
        {/* Top face (3) */}
        <div
          style={{
            ...faceStyle,
            transform: `rotateX(90deg) translateZ(${halfSize}px)`,
          }}
        >
          {renderDots(3)}
        </div>
        {/* Bottom face (4) */}
        <div
          style={{
            ...faceStyle,
            transform: `rotateX(-90deg) translateZ(${halfSize}px)`,
          }}
        >
          {renderDots(4)}
        </div>
      </animated.div>
    </div>
  )
}

export interface InteractiveDiceProps {
  /** Called when the dice is rolled (clicked or thrown) - fires immediately */
  onRoll: () => void
  /** Called when dragging starts - useful for preloading/prefetching */
  onDragStart?: () => void
  /** Called when the dice animation completes and settles back home */
  onRollComplete?: () => void
  /** Called for instant roll (shift+click) - bypasses animation */
  onInstantRoll?: () => void
  /** Whether the dice is disabled */
  disabled?: boolean
  /** Size of the dice in pixels (default: 22) */
  size?: number
  /** Title/tooltip for the dice button */
  title?: string
  /** Additional CSS class for the button */
  className?: string
  /** Button style overrides */
  style?: React.CSSProperties
  /** Override the default indigo color scheme */
  colorScheme?: DiceColorScheme
  /** Reports the rolled face value (1-6). When present, enables face 1. */
  onRolledValue?: (value: number) => void
  /** Increment to trigger a roll programmatically (e.g. for "Roll All") */
  rollTrigger?: number
  /** CSS perspective value in px for 3D depth (default: 100) */
  perspective?: number
  /** Ref containing current tilt force vector, updated by accelerometer at ~60Hz */
  tiltForceRef?: { readonly current: { x: number; y: number } }
  /** Whether tilt/accelerometer mode is active */
  tiltEnabled?: boolean
  /** Ref containing latest jolt event from device motion, or null */
  joltRef?: { readonly current: JoltEvent | null }
  /** Override jolt detection thresholds */
  joltConfig?: Partial<JoltConfig>
}

/**
 * Interactive 3D dice that can be clicked or dragged and thrown.
 *
 * Features:
 * - Click to roll
 * - Drag and release to throw (physics simulation)
 * - Bounces off viewport edges
 * - Grows when flying, shrinks when returning
 * - Smooth spring-based animations
 */
export function InteractiveDice({
  onRoll,
  onDragStart,
  onRollComplete,
  onInstantRoll,
  disabled = false,
  size = 22,
  title = 'Roll dice (drag or click)',
  className,
  style,
  colorScheme,
  onRolledValue,
  rollTrigger,
  perspective = 100,
  tiltForceRef,
  tiltEnabled = false,
  joltRef,
  joltConfig,
}: InteractiveDiceProps) {
  const { resolvedTheme } = useTheme()
  const isDark = resolvedTheme === 'dark'

  // Dice rotation state for react-spring animation
  // We track cumulative spins to add visual flair, then compute final rotation
  // to land on the correct face derived from a random value
  const [spinCount, setSpinCount] = useState(0)
  // Track which face we're showing (for ensuring consecutive rolls differ)
  const minFace = onRolledValue ? 1 : 2
  const faceCount = onRolledValue ? 6 : 5
  const [currentFace, setCurrentFace] = useState(
    () => Math.floor(Math.random() * faceCount) + minFace
  )

  // Draggable dice state with physics simulation
  const [isDragging, setIsDragging] = useState(false)
  const [diceOrigin, setDiceOrigin] = useState({ x: 0, y: 0 })
  const diceButtonRef = useRef<HTMLButtonElement>(null)
  const diceContainerRef = useRef<HTMLDivElement>(null)
  const dragStartPos = useRef({ x: 0, y: 0 })

  // Physics state for thrown dice
  const [isFlying, setIsFlying] = useState(false)
  const dicePhysics = useRef({
    x: 0,
    y: 0,
    vx: 0,
    vy: 0,
    rotationX: 0,
    rotationY: 0,
    rotationZ: 0,
    scale: 1, // Grows to 3x when flying, shrinks back when settling
  })
  const lastPointerPos = useRef({ x: 0, y: 0, time: 0 })
  // Track velocity samples for smoother flick detection
  const velocitySamples = useRef<Array<{ vx: number; vy: number; time: number }>>([])
  const animationFrameRef = useRef<number>()

  // Tip animation state for jolt-based cube tipping
  const tipState = useRef<{
    orientation: CubeOrientation
    tipAnimation: {
      active: boolean
      startTime: number
      duration: number
      axis: 'X' | 'Y'
      direction: 1 | -1
      originCSS: string
      tipDirection: TipDirection
    } | null
    tipQueue: TipDirection[]
    tipThreshold: number // per-die randomized threshold
    tipDuration: number // per-die randomized duration
    lastJoltTimestamp: number // to avoid re-reading same jolt
  }>({
    orientation: orientationForFace(currentFace),
    tipAnimation: null,
    tipQueue: [],
    tipThreshold: DEFAULT_JOLT_CONFIG.joltThreshold * (0.8 + Math.random() * 0.4),
    tipDuration: 200 + Math.random() * 100,
    lastJoltTimestamp: 0,
  })

  // Merged jolt config ref (always up to date, no re-renders)
  const joltConfigRef = useRef<JoltConfig>({ ...DEFAULT_JOLT_CONFIG, ...joltConfig })
  joltConfigRef.current = { ...DEFAULT_JOLT_CONFIG, ...joltConfig }
  // Timeout ref for click-only roll completion callback
  const rollCompleteTimeoutRef = useRef<ReturnType<typeof setTimeout>>()
  // Flag to prevent click from firing after a throw (pointerup + click both fire)
  const justThrewRef = useRef(false)

  // Ref to the portal dice element for direct DOM manipulation during drag/flying (avoids re-renders)
  const portalDiceRef = useRef<HTMLDivElement>(null)

  // Compute target rotation for the current face (needed by physics simulation)
  const targetFaceRotation = DICE_FACE_ROTATIONS[currentFace] || {
    rotateX: 0,
    rotateY: 0,
  }

  // Roll the dice - animate and call onRoll
  // isFromThrow: true if this roll is from a drag-throw (physics simulation will handle completion)
  const handleRoll = useCallback(
    (isFromThrow = false) => {
      // Clear any pending completion timeout from previous click roll
      if (rollCompleteTimeoutRef.current) {
        clearTimeout(rollCompleteTimeoutRef.current)
        rollCompleteTimeoutRef.current = undefined
      }

      // Calculate target face (1-6 if onRolledValue, 2-6 otherwise)
      const baseFace = Math.floor(Math.random() * faceCount) + minFace

      // Ensure it's different from the current face
      const maxFace = minFace + faceCount - 1
      const targetFace =
        baseFace === currentFace ? (baseFace === maxFace ? minFace : baseFace + 1) : baseFace

      // Add 1-2 full spins for visual drama
      const extraSpins = Math.floor(Math.random() * 2) + 1

      setSpinCount((prev) => prev + extraSpins)
      setCurrentFace(targetFace)
      // Sync orientation state machine with new face from roll
      tipState.current.orientation = orientationForFace(targetFace)
      tipState.current.tipAnimation = null
      tipState.current.tipQueue = []
      onRolledValue?.(targetFace)
      onRoll()

      // For click-only rolls (not throws), schedule completion callback after spring animation
      // Spring config is tension: 120, friction: 14, which settles in ~600-700ms
      if (!isFromThrow && onRollComplete) {
        rollCompleteTimeoutRef.current = setTimeout(() => {
          onRollComplete()
          rollCompleteTimeoutRef.current = undefined
        }, 700)
      }
    },
    [currentFace, onRoll, onRollComplete, onRolledValue, minFace, faceCount]
  )

  // Physics simulation for thrown dice and tilt mode - uses direct DOM manipulation for performance
  useEffect(() => {
    const shouldAnimate = isFlying || (tiltEnabled && !isDragging)
    if (!shouldAnimate) return

    const BASE_GRAVITY = 0.8 // Base pull toward origin
    const BASE_FRICTION = 0.94 // Base velocity dampening
    const ROTATION_FACTOR = 0.5 // How much velocity affects rotation
    const STOP_THRESHOLD = 2 // Distance threshold to snap home
    const VELOCITY_THRESHOLD = 0.5 // Velocity threshold to snap home
    const CLOSE_RANGE = 40 // Distance at which extra damping kicks in
    const MAX_SCALE = 3 // Maximum scale when flying
    const SCALE_GROW_SPEED = 0.2 // How fast to grow (faster)
    const SCALE_SHRINK_SPEED = 0.06 // How fast to shrink when close (slower for drama)
    const BOUNCE_DAMPING = 0.7 // How much velocity is retained on bounce (0-1)
    const DICE_SIZE = size // Size of the dice in pixels
    const TILT_FORCE_MULT = 1.5 // Amplification for tilt force
    const JOLT_IMPULSE = 4 // Velocity impulse from a jolt
    const WOBBLE_ROTATION = 10 // Degrees of wobble for sub-threshold jolts

    // Transform-origin and rotation axis mapping for tip directions
    const TIP_ORIGIN: Record<TipDirection, string> = {
      up: '50% 0%',
      down: '50% 100%',
      left: '0% 50%',
      right: '100% 50%',
    }
    const TIP_AXIS: Record<TipDirection, 'X' | 'Y'> = {
      up: 'X',
      down: 'X',
      left: 'Y',
      right: 'Y',
    }
    const TIP_SIGN: Record<TipDirection, 1 | -1> = {
      up: -1, // rotateX -= 90
      down: 1, // rotateX += 90
      left: 1, // rotateY += 90
      right: -1, // rotateY -= 90
    }

    // Quantize a jolt direction vector to cardinal
    const quantizeDirection = (dx: number, dy: number): TipDirection => {
      if (Math.abs(dx) > Math.abs(dy)) {
        return dx > 0 ? 'right' : 'left'
      }
      return dy > 0 ? 'down' : 'up'
    }

    // Start a tip animation from the queue
    const startNextTip = (ts: tipStateType, now: number) => {
      if (ts.tipQueue.length === 0) return
      const dir = ts.tipQueue.shift()!
      ts.tipAnimation = {
        active: true,
        startTime: now,
        duration: ts.tipDuration,
        axis: TIP_AXIS[dir],
        direction: TIP_SIGN[dir],
        originCSS: TIP_ORIGIN[dir],
        tipDirection: dir,
      }
    }

    type tipStateType = typeof tipState.current

    // Calculate initial throw power (only relevant for thrown dice, not tilt)
    const initialSpeed = isFlying
      ? Math.sqrt(
          dicePhysics.current.vx * dicePhysics.current.vx +
            dicePhysics.current.vy * dicePhysics.current.vy
        )
      : 0
    const throwPower = Math.min(initialSpeed / 20, 1)

    let frameCount = 0

    const animate = () => {
      const p = dicePhysics.current
      const el = portalDiceRef.current
      if (!el) {
        animationFrameRef.current = requestAnimationFrame(animate)
        return
      }

      frameCount++
      const now = performance.now()
      const ts = tipState.current
      const cfg = joltConfigRef.current
      const diceEl = el.querySelector('[data-dice-cube]') as HTMLElement | null

      // === Tip animation logic ===
      let tipOwnsRotation = false

      if (ts.tipAnimation?.active) {
        const tip = ts.tipAnimation
        const progress = Math.min((now - tip.startTime) / tip.duration, 1)

        if (progress >= 1) {
          // Tip complete
          const newOrientation = applyTip(ts.orientation, tip.tipDirection)
          ts.orientation = newOrientation
          const newFace = newOrientation.front
          const newFaceRot = DICE_FACE_ROTATIONS[newFace] ?? { rotateX: 0, rotateY: 0 }

          // Snap rotation to the new face's canonical rotation
          p.rotationX = newFaceRot.rotateX
          p.rotationY = newFaceRot.rotateY

          // Reset transform-origin
          if (diceEl) {
            diceEl.style.transformOrigin = '50% 50%'
          }

          // Position compensation: the cube pivoted around its edge, so its center
          // moved by half the dice size in the tip direction
          const halfSize = DICE_SIZE / 2
          switch (tip.tipDirection) {
            case 'up':
              p.y -= halfSize
              break
            case 'down':
              p.y += halfSize
              break
            case 'left':
              p.x -= halfSize
              break
            case 'right':
              p.x += halfSize
              break
          }

          // Update face state
          setCurrentFace(newFace)
          onRolledValue?.(newFace)
          setSpinCount(0) // Reset spin count so react-spring targets the new face correctly

          // Clear this animation
          ts.tipAnimation = null

          // Chain next tip if queue has more
          if (ts.tipQueue.length > 0) {
            startNextTip(ts, now)
          }
        } else {
          // Interpolate tip rotation with ease-out: t * (2 - t)
          const eased = progress * (2 - progress)
          const tipAngle = eased * 90 * tip.direction

          if (diceEl) {
            diceEl.style.transformOrigin = tip.originCSS
            // Build rotation: base face rotation + tip rotation on the tip axis
            const baseRot = DICE_FACE_ROTATIONS[ts.orientation.front] ?? { rotateX: 0, rotateY: 0 }
            if (tip.axis === 'X') {
              diceEl.style.transform = `rotateX(${baseRot.rotateX + tipAngle}deg) rotateY(${baseRot.rotateY}deg) rotateZ(${p.rotationZ}deg)`
            } else {
              diceEl.style.transform = `rotateX(${baseRot.rotateX}deg) rotateY(${baseRot.rotateY + tipAngle}deg) rotateZ(${p.rotationZ}deg)`
            }
          }
          tipOwnsRotation = true
        }
      }

      // === Jolt detection (only in tilt mode, not during active tip) ===
      if (!ts.tipAnimation?.active && joltRef?.current) {
        const jolt = joltRef.current
        if (jolt.timestamp !== ts.lastJoltTimestamp) {
          ts.lastJoltTimestamp = jolt.timestamp
          const magnitude = jolt.magnitude

          if (magnitude > ts.tipThreshold) {
            // Determine tip count based on magnitude
            let tipCount = 1
            if (magnitude > cfg.heavyTumbleThreshold) tipCount = 3
            else if (magnitude > cfg.tumbleThreshold) tipCount = 2

            // Primary direction from jolt
            const primaryDir = quantizeDirection(jolt.directionX, jolt.directionY)
            ts.tipQueue.push(primaryDir)

            // Additional tips with slight randomness
            const allDirs: TipDirection[] = ['up', 'down', 'left', 'right']
            for (let i = 1; i < tipCount; i++) {
              // 50% chance same direction, 50% random adjacent
              if (Math.random() < 0.5) {
                ts.tipQueue.push(primaryDir)
              } else {
                const others = allDirs.filter((d) => d !== primaryDir)
                ts.tipQueue.push(others[Math.floor(Math.random() * others.length)])
              }
            }

            // Add velocity impulse for physical kick
            p.vx += jolt.directionX * JOLT_IMPULSE
            p.vy += jolt.directionY * JOLT_IMPULSE

            // Start first tip (with per-die random delay)
            const delay = Math.random() * 80
            if (delay < 16) {
              startNextTip(ts, now)
            } else {
              setTimeout(() => startNextTip(ts, performance.now()), delay)
            }
          } else if (magnitude > cfg.wobbleThreshold) {
            // Sub-threshold wobble: rotational impulse + brief scale bump
            p.rotationZ += (Math.random() - 0.5) * WOBBLE_ROTATION * 2
            p.scale = Math.min(p.scale + 0.08, 1.3)
          }
        }
      }

      // === Position / velocity physics (same as before) ===

      // Calculate distance to origin
      const dist = Math.sqrt(p.x * p.x + p.y * p.y)

      // Read tilt force from ref (updated at ~60Hz by deviceorientation)
      const tilt = tiltForceRef?.current ?? { x: 0, y: 0 }
      const tiltMag = Math.sqrt(tilt.x * tilt.x + tilt.y * tilt.y)
      const isActiveTilt = tiltEnabled && tiltMag > 0.2

      // Apply tilt force (like gravity on a tilted surface)
      if (isActiveTilt) {
        p.vx += tilt.x * TILT_FORCE_MULT
        p.vy += tilt.y * TILT_FORCE_MULT
      }

      // Spring force toward origin (disabled during active tilt)
      if (!isActiveTilt && dist > 0) {
        const gravityRampUp = Math.min(frameCount / 30, 1)
        const effectiveGravity = BASE_GRAVITY * (0.3 + 0.7 * gravityRampUp) * (1 - throwPower * 0.5)
        const pullStrength = effectiveGravity * (dist / 50) ** 1.2
        p.vx += (-p.x / dist) * pullStrength
        p.vy += (-p.y / dist) * pullStrength
      }

      // Friction - extra close-range damping only in non-tilt mode
      const friction = dist < CLOSE_RANGE && !isActiveTilt ? 0.88 : BASE_FRICTION
      p.vx *= friction
      p.vy *= friction

      // Update position
      p.x += p.vx
      p.y += p.vy

      // Viewport edge bounce - calculate absolute position and check bounds
      const scaledSize = DICE_SIZE * p.scale
      const absoluteX = diceOrigin.x + p.x
      const absoluteY = diceOrigin.y + p.y
      const viewportWidth = window.innerWidth
      const viewportHeight = window.innerHeight

      // Left edge bounce
      if (absoluteX < 0) {
        p.x = -diceOrigin.x
        p.vx = Math.abs(p.vx) * BOUNCE_DAMPING
        p.rotationZ += p.vx * 5
      }
      // Right edge bounce
      if (absoluteX + scaledSize > viewportWidth) {
        p.x = viewportWidth - diceOrigin.x - scaledSize
        p.vx = -Math.abs(p.vx) * BOUNCE_DAMPING
        p.rotationZ -= p.vx * 5
      }
      // Top edge bounce
      if (absoluteY < 0) {
        p.y = -diceOrigin.y
        p.vy = Math.abs(p.vy) * BOUNCE_DAMPING
        p.rotationZ += p.vy * 5
      }
      // Bottom edge bounce
      if (absoluteY + scaledSize > viewportHeight) {
        p.y = viewportHeight - diceOrigin.y - scaledSize
        p.vy = -Math.abs(p.vy) * BOUNCE_DAMPING
        p.rotationZ -= p.vy * 5
      }

      // Update rotation based on velocity (dice rolls as it moves)
      const speed = Math.sqrt(p.vx * p.vx + p.vy * p.vy)

      if (!tipOwnsRotation) {
        // As dice gets closer to home, gradually lerp rotation toward final face
        const SETTLE_START_DIST = 150
        const settleProgress = Math.max(0, 1 - dist / SETTLE_START_DIST)
        const settleFactor = settleProgress * settleProgress * settleProgress

        // Physics rotation (tumbling)
        const physicsRotationDelta = {
          x: p.vy * ROTATION_FACTOR * 12,
          y: -p.vx * ROTATION_FACTOR * 12,
          z: speed * ROTATION_FACTOR * 3,
        }

        p.rotationX += physicsRotationDelta.x * (1 - settleFactor)
        p.rotationY += physicsRotationDelta.y * (1 - settleFactor)
        p.rotationZ += physicsRotationDelta.z * (1 - settleFactor)

        // Lerp toward target face rotation as we settle
        const lerpSpeed = 0.08 * settleFactor
        if (settleFactor > 0.01) {
          const targetX = targetFaceRotation.rotateX
          const targetY = targetFaceRotation.rotateY

          const normalizeAngle = (angle: number) => {
            let normalized = angle % 360
            if (normalized > 180) normalized -= 360
            if (normalized < -180) normalized += 360
            return normalized
          }

          const currentX = normalizeAngle(p.rotationX)
          const currentY = normalizeAngle(p.rotationY)
          const currentZ = normalizeAngle(p.rotationZ)

          p.rotationX = currentX + (targetX - currentX) * lerpSpeed
          p.rotationY = currentY + (targetY - currentY) * lerpSpeed
          p.rotationZ = currentZ + (0 - currentZ) * lerpSpeed
        }
      }

      // Scale behavior
      if (tiltEnabled && !isFlying) {
        // Tilt mode: subtle scale based on velocity (rolling on tray surface)
        const targetScale = 1 + Math.min(speed / 30, 0.3)
        p.scale += (targetScale - p.scale) * 0.1
      } else {
        // Throw mode: grow when far, shrink when close
        const targetScale =
          dist > CLOSE_RANGE ? MAX_SCALE : 1 + ((MAX_SCALE - 1) * dist) / CLOSE_RANGE
        if (p.scale < targetScale) {
          p.scale = Math.min(p.scale + SCALE_GROW_SPEED, targetScale)
        } else if (p.scale > targetScale) {
          p.scale = Math.max(p.scale - SCALE_SHRINK_SPEED, targetScale)
        }
      }

      // Update DOM directly - no React re-renders
      const scaleOffset = ((p.scale - 1) * DICE_SIZE) / 2
      el.style.transform = `translate(${p.x - scaleOffset}px, ${p.y - scaleOffset}px) scale(${p.scale})`

      // Dynamic shadow based on scale
      const shadowSize = (p.scale - 1) * 10
      const shadowOpacity = Math.min((p.scale - 1) * 0.2, 0.4)
      el.style.filter =
        shadowSize > 0
          ? `drop-shadow(0 ${shadowSize}px ${shadowSize * 1.5}px rgba(0,0,0,${shadowOpacity}))`
          : 'none'

      // Update dice rotation (only if tip doesn't own it this frame)
      if (!tipOwnsRotation && diceEl) {
        diceEl.style.transformOrigin = '50% 50%'
        diceEl.style.transform = `rotateX(${p.rotationX}deg) rotateY(${p.rotationY}deg) rotateZ(${p.rotationZ}deg)`
      }

      // Stop condition (only when tilt is off — tilt mode keeps the loop alive)
      if (!tiltEnabled) {
        const totalVelocity = Math.sqrt(p.vx * p.vx + p.vy * p.vy)
        const rotationSettled =
          Math.abs(p.rotationX - targetFaceRotation.rotateX) < 5 &&
          Math.abs(p.rotationY - targetFaceRotation.rotateY) < 5 &&
          Math.abs(p.rotationZ) < 5

        if (
          dist < STOP_THRESHOLD &&
          totalVelocity < VELOCITY_THRESHOLD &&
          p.scale < 1.1 &&
          rotationSettled &&
          !ts.tipAnimation?.active
        ) {
          el.style.filter = 'none'
          setIsFlying(false)
          dicePhysics.current = {
            x: 0,
            y: 0,
            vx: 0,
            vy: 0,
            rotationX: targetFaceRotation.rotateX,
            rotationY: targetFaceRotation.rotateY,
            rotationZ: 0,
            scale: 1,
          }
          onRollComplete?.()
          return
        }
      }

      animationFrameRef.current = requestAnimationFrame(animate)
    }

    animationFrameRef.current = requestAnimationFrame(animate)

    return () => {
      if (animationFrameRef.current) {
        cancelAnimationFrame(animationFrameRef.current)
      }
    }
  }, [
    isFlying,
    tiltEnabled,
    isDragging,
    diceOrigin.x,
    diceOrigin.y,
    targetFaceRotation.rotateX,
    targetFaceRotation.rotateY,
    size,
    onRollComplete,
    onRolledValue,
    joltRef,
  ])

  // Cleanup timeout on unmount
  useEffect(() => {
    return () => {
      if (rollCompleteTimeoutRef.current) {
        clearTimeout(rollCompleteTimeoutRef.current)
      }
    }
  }, [])

  // Capture origin and prepare physics when tilt mode activates
  // eslint-disable-next-line react-hooks/exhaustive-deps
  useLayoutEffect(() => {
    if (tiltEnabled && !isDragging && !isFlying && diceContainerRef.current) {
      const rect = diceContainerRef.current.getBoundingClientRect()
      setDiceOrigin({ x: rect.left, y: rect.top })
      dicePhysics.current = {
        x: 0,
        y: 0,
        vx: 0,
        vy: 0,
        rotationX: targetFaceRotation.rotateX,
        rotationY: targetFaceRotation.rotateY,
        rotationZ: 0,
        scale: 1,
      }
    }
  }, [tiltEnabled])

  // When tilt disables, fly dice back home if displaced
  const prevTiltEnabled = useRef(tiltEnabled)
  useLayoutEffect(() => {
    if (prevTiltEnabled.current && !tiltEnabled) {
      const p = dicePhysics.current
      const dist = Math.sqrt(p.x * p.x + p.y * p.y)
      const vel = Math.sqrt(p.vx * p.vx + p.vy * p.vy)
      if (dist > 5 || vel > 1) {
        // Die is displaced — fly it back home via the existing spring-to-origin
        setIsFlying(true)
      } else {
        // Close enough — snap home immediately
        dicePhysics.current = {
          x: 0,
          y: 0,
          vx: 0,
          vy: 0,
          rotationX: targetFaceRotation.rotateX,
          rotationY: targetFaceRotation.rotateY,
          rotationZ: 0,
          scale: 1,
        }
      }
    }
    prevTiltEnabled.current = tiltEnabled
  }, [tiltEnabled, targetFaceRotation.rotateX, targetFaceRotation.rotateY])

  // Programmatic roll trigger — when rollTrigger increments, fire a roll
  const prevRollTrigger = useRef(rollTrigger ?? 0)
  useEffect(() => {
    if (rollTrigger !== undefined && rollTrigger !== prevRollTrigger.current && rollTrigger > 0) {
      prevRollTrigger.current = rollTrigger
      handleRoll()
    }
  }, [rollTrigger, handleRoll])

  // Compute dice rotation for react-spring animation (used when not flying)
  const diceRotation = {
    rotateX: spinCount * 360 + targetFaceRotation.rotateX,
    rotateY: spinCount * 360 + targetFaceRotation.rotateY,
    rotateZ: spinCount * 180, // Z rotation for extra tumble effect
  }

  // Dice drag handlers for the easter egg - drag dice off and release to roll
  const handleDicePointerDown = useCallback(
    (e: React.PointerEvent) => {
      if (disabled) return
      e.preventDefault()
      e.stopPropagation()

      // Cancel any ongoing physics animation
      if (animationFrameRef.current) {
        cancelAnimationFrame(animationFrameRef.current)
      }
      setIsFlying(false)

      // Capture the pointer
      ;(e.target as HTMLElement).setPointerCapture(e.pointerId)

      // Get the dice container's position for portal rendering
      if (diceContainerRef.current) {
        const rect = diceContainerRef.current.getBoundingClientRect()
        setDiceOrigin({ x: rect.left, y: rect.top })
      }

      dragStartPos.current = { x: e.clientX, y: e.clientY }
      lastPointerPos.current = {
        x: e.clientX,
        y: e.clientY,
        time: performance.now(),
      }
      velocitySamples.current = [] // Reset velocity tracking
      dicePhysics.current = {
        x: 0,
        y: 0,
        vx: 0,
        vy: 0,
        rotationX: 0,
        rotationY: 0,
        rotationZ: 0,
        scale: 1,
      }
      setIsDragging(true)
      // Notify that drag started - useful for prefetching
      onDragStart?.()
    },
    [disabled, onDragStart]
  )

  const handleDicePointerMove = useCallback(
    (e: React.PointerEvent) => {
      if (!isDragging) return
      e.preventDefault()

      const dx = e.clientX - dragStartPos.current.x
      const dy = e.clientY - dragStartPos.current.y

      // Calculate drag velocity for live rotation
      const now = performance.now()
      const dt = Math.max(now - lastPointerPos.current.time, 8)
      const vx = (e.clientX - lastPointerPos.current.x) / dt
      const vy = (e.clientY - lastPointerPos.current.y) / dt

      // Update rotation based on drag velocity (dice tumbles while being dragged)
      const p = dicePhysics.current
      p.rotationX += vy * 8
      p.rotationY -= vx * 8
      p.rotationZ += Math.sqrt(vx * vx + vy * vy) * 2

      // Scale up slightly based on distance (feels like pulling it out)
      const dist = Math.sqrt(dx * dx + dy * dy)
      p.scale = 1 + Math.min(dist / 150, 0.5) // Max 1.5x during drag

      // Update DOM directly to avoid React re-renders during drag
      if (portalDiceRef.current) {
        const scaleOffset = ((p.scale - 1) * size) / 2
        portalDiceRef.current.style.transform = `translate(${dx - scaleOffset}px, ${dy - scaleOffset}px) scale(${p.scale})`
        // Add shadow that grows with distance
        const shadowSize = Math.min(dist / 10, 20)
        const shadowOpacity = Math.min(dist / 200, 0.4)
        portalDiceRef.current.style.filter = `drop-shadow(0 ${shadowSize}px ${shadowSize * 1.5}px rgba(0,0,0,${shadowOpacity}))`

        // Update dice rotation
        const diceEl = portalDiceRef.current.querySelector('[data-dice-cube]') as HTMLElement | null
        if (diceEl) {
          diceEl.style.transform = `rotateX(${p.rotationX}deg) rotateY(${p.rotationY}deg) rotateZ(${p.rotationZ}deg)`
        }
      }

      // Store position in ref for use when releasing
      p.x = dx
      p.y = dy

      // Track velocity samples for flick detection (keep last 5 samples, ~80ms window)
      velocitySamples.current.push({ vx, vy, time: now })
      if (velocitySamples.current.length > 5) {
        velocitySamples.current.shift()
      }

      // Track velocity for throw calculation
      lastPointerPos.current = { x: e.clientX, y: e.clientY, time: now }
    },
    [isDragging, size]
  )

  const handleDicePointerUp = useCallback(
    (e: React.PointerEvent) => {
      if (!isDragging) return
      e.preventDefault()

      // Release the pointer
      ;(e.target as HTMLElement).releasePointerCapture(e.pointerId)

      // Calculate throw velocity from velocity samples (average of recent samples for smooth flick)
      const samples = velocitySamples.current
      let vx = 0
      let vy = 0

      if (samples.length > 0) {
        // Weight recent samples more heavily
        let totalWeight = 0
        for (let i = 0; i < samples.length; i++) {
          const weight = i + 1 // Later samples get higher weight
          vx += samples[i].vx * weight
          vy += samples[i].vy * weight
          totalWeight += weight
        }
        vx /= totalWeight
        vy /= totalWeight
      }

      // Get position from physics ref (set during drag)
      const posX = dicePhysics.current.x
      const posY = dicePhysics.current.y

      // Calculate distance dragged
      const distance = Math.sqrt(posX ** 2 + posY ** 2)

      // Calculate flick speed
      const flickSpeed = Math.sqrt(vx * vx + vy * vy)

      // If dragged more than 20px OR flicked fast enough, trigger throw physics
      if (distance > 20 || flickSpeed > 0.3) {
        // Amplify throw velocity significantly for satisfying flick
        const throwMultiplier = 25 // Much stronger throw!

        // Initialize physics with current position and throw velocity
        dicePhysics.current = {
          x: posX,
          y: posY,
          vx: vx * throwMultiplier,
          vy: vy * throwMultiplier,
          rotationX: dicePhysics.current.rotationX, // Keep current rotation
          rotationY: dicePhysics.current.rotationY,
          rotationZ: dicePhysics.current.rotationZ,
          scale: dicePhysics.current.scale, // Keep current scale
        }
        setIsFlying(true)
        // Mark that we just threw - prevents click event from also firing handleRoll
        justThrewRef.current = true
        // Trigger roll when thrown (pass true to indicate physics will handle completion)
        handleRoll(true)
      } else {
        // Not thrown far enough, snap back
        dicePhysics.current = {
          x: 0,
          y: 0,
          vx: 0,
          vy: 0,
          rotationX: 0,
          rotationY: 0,
          rotationZ: 0,
          scale: 1,
        }
      }

      setIsDragging(false)
    },
    [isDragging, handleRoll]
  )

  return (
    <>
      <button
        ref={diceButtonRef}
        type="button"
        data-action="roll-dice"
        onClick={(e) => {
          // Skip if we just did a throw (pointerup already called handleRoll)
          if (justThrewRef.current) {
            justThrewRef.current = false
            return
          }
          // Shift+click = instant roll (bypass animation)
          if (e.shiftKey && onInstantRoll) {
            onInstantRoll()
            return
          }
          handleRoll()
        }}
        onPointerDown={handleDicePointerDown}
        onPointerMove={handleDicePointerMove}
        onPointerUp={handleDicePointerUp}
        onPointerCancel={handleDicePointerUp}
        disabled={disabled}
        title={title}
        className={className}
        style={{
          cursor: isDragging ? 'grabbing' : disabled ? 'not-allowed' : 'grab',
          opacity: disabled ? 0.7 : 1,
          touchAction: 'none', // Prevent scroll on touch devices
          userSelect: 'none',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          ...style,
        }}
      >
        {/* Dice container - hidden when dragging/flying since we show portal version */}
        <div
          ref={diceContainerRef}
          style={{
            opacity: isDragging || isFlying ? 0 : 1,
            pointerEvents: 'none',
          }}
        >
          <DiceIcon
            rotateX={diceRotation.rotateX}
            rotateY={diceRotation.rotateY}
            rotateZ={diceRotation.rotateZ}
            isDark={isDark}
            size={size}
            colorScheme={colorScheme}
            perspective={perspective}
          />
        </div>
      </button>

      {/* Portal-rendered dice when dragging/flying/tilting - renders outside button to avoid clipping */}
      {/* All transforms are applied directly via ref for performance - no React re-renders */}
      {(isDragging || isFlying || tiltEnabled) &&
        createPortal(
          <div
            ref={portalDiceRef}
            style={{
              position: 'fixed',
              left: diceOrigin.x,
              top: diceOrigin.y,
              // Transform is updated directly via ref during drag/flying
              transform: 'translate(0px, 0px)',
              pointerEvents: 'none',
              zIndex: 100000,
              cursor: isDragging ? 'grabbing' : 'default',
              willChange: 'transform', // Hint to browser for GPU acceleration
            }}
          >
            {/* During flying, rotation is updated directly on data-dice-cube element */}
            <DiceIcon
              rotateX={diceRotation.rotateX}
              rotateY={diceRotation.rotateY}
              rotateZ={diceRotation.rotateZ}
              isDark={isDark}
              size={size}
              colorScheme={colorScheme}
              perspective={perspective}
            />
          </div>,
          document.body
        )}
    </>
  )
}