All files / web/src/components/tutorial ReasonTooltip.tsx

66.66% Statements 268/402
70.58% Branches 36/51
20% Functions 2/10
66.66% Lines 268/402

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 4031x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 30x 30x       30x 30x 30x 30x 30x 30x 30x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x         1x 1x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 30x 29x 30x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x     34x 34x 34x 30x 30x 12x 12x 12x 12x 12x 12x 30x 8x 8x 8x 8x 8x 8x 30x 9x 9x 9x 9x 9x 9x 30x             30x 1x 1x 1x 1x 1x 1x 30x 34x 34x 34x 34x 34x 1x 1x 29x 29x 29x 29x 29x 29x                     29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 29x 29x 29x 34x 34x 34x 34x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 34x 34x 34x 34x       29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x                                                                                                                                                                                                           29x 29x 34x 34x 34x 34x 29x 22x           34x 34x 34x 34x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 34x 34x 34x 34x 34x 34x 34x 34x 34x  
'use client'
 
import * as HoverCard from '@radix-ui/react-hover-card'
import { useTranslations } from 'next-intl'
import type React from 'react'
import { useMemo, useState } from 'react'
import type { TermProvenance, UnifiedStepData } from '../../utils/unifiedStepGenerator'
import type { PedagogicalRule, PedagogicalSegment, TermReason } from './DecompositionWithReasons'
import './reason-tooltip.css'
 
// Helper hook to safely access TutorialUI context
// Check if TutorialUI module is available at module load time
let useTutorialUIImport: (() => any) | null = null
try {
  const module = require('./TutorialUIContext')
  useTutorialUIImport = module.useTutorialUI
} catch {
  // TutorialUI context not available
}
 
function useTutorialUIGate() {
  if (useTutorialUIImport) {
    // eslint-disable-next-line react-hooks/rules-of-hooks
    return useTutorialUIImport()
  }
  // Return a fallback that allows all focus requests (non-tutorial context)
  return {
    requestFocus: () => true,
    releaseFocus: () => {},
    hintFocus: 'none' as const,
  }
}
 
interface ReasonTooltipProps {
  children: React.ReactNode
  termIndex: number
  segment?: PedagogicalSegment
  reason?: TermReason
  originalValue?: string
  steps?: UnifiedStepData[]
  provenance?: TermProvenance // NEW: Provenance data for enhanced tooltips
}
 
// Fallback utility for legacy support
function _getPlaceName(place: number): string {
  const names = ['ones', 'tens', 'hundreds', 'thousands', 'ten-thousands']
  return names[place] || `10^${place}`
}
 
export function ReasonTooltip({
  children,
  termIndex,
  segment,
  reason,
  originalValue,
  steps,
  provenance,
}: ReasonTooltipProps) {
  // All hooks must be called before early return
  const [showBeadDetails, setShowBeadDetails] = useState(false)
  const [showMath, setShowMath] = useState(false)
  const [showDetails, setShowDetails] = useState(false)
  const [isOpen, setIsOpen] = useState(false)
  const ui = useTutorialUIGate()
  const t = useTranslations('tutorial.reasonTooltip')
  const rule = reason?.rule ?? segment?.plan[0]?.rule
 
  // Use readable format from segment, enhanced with provenance
  const readable = segment?.readable
 
  const enhancedContent = useMemo(() => {
    if (!provenance) return null
 
    if (rule === 'Direct') {
      const rodChip = readable?.chips.find((c) => /^(this )?rod shows$/i.test(c.label))
 
      return {
        title: t('directTitle', {
          place: provenance.rhsPlaceName,
          digit: provenance.rhsDigit,
          value: provenance.rhsValue,
        }),
        subtitle: t('directSubtitle', { addend: provenance.rhs }),
        chips: [
          {
            label: t('digitChip'),
            value: `${provenance.rhsDigit} (${provenance.rhsPlaceName})`,
          },
          ...(rodChip ? [{ label: t('rodChip'), value: rodChip.value }] : []),
          {
            label: t('addHereChip'),
            value: `+${provenance.rhsDigit} ${provenance.rhsPlaceName} → ${provenance.rhsValue}`,
          },
        ],
      }
    }
 
    if (readable) {
      const subtitleParts = [
        readable.subtitle,
        t('subtitleContext', {
          addend: provenance.rhs,
          place: provenance.rhsPlaceName,
          digit: provenance.rhsDigit,
        }),
      ].filter(Boolean)
 
      return {
        title: readable.title,
        subtitle: subtitleParts.join(' • '),
        chips: [
          {
            label: t('sourceDigit'),
            value: `${provenance.rhsDigit} from ${provenance.rhs} (${provenance.rhsPlaceName} place)`,
          },
          ...readable.chips,
        ],
      }
    }

    return null
  }, [provenance, readable, rule, t])
 
  const ruleInfo = useMemo(() => {
    switch (rule) {
      case 'Direct':
        return {
          emoji: '✨',
          name: t('ruleInfo.Direct.name'),
          description: t('ruleInfo.Direct.description'),
          color: 'green',
        }
      case 'FiveComplement':
        return {
          emoji: '🤝',
          name: t('ruleInfo.FiveComplement.name'),
          description: t('ruleInfo.FiveComplement.description'),
          color: 'blue',
        }
      case 'TenComplement':
        return {
          emoji: '🔟',
          name: t('ruleInfo.TenComplement.name'),
          description: t('ruleInfo.TenComplement.description'),
          color: 'purple',
        }
      case 'Cascade':
        return {
          emoji: '🌊',
          name: t('ruleInfo.Cascade.name'),
          description: t('ruleInfo.Cascade.description'),
          color: 'orange',
        }
      default:
        return {
          emoji: '💭',
          name: t('ruleInfo.Fallback.name'),
          description: t('ruleInfo.Fallback.description'),
          color: 'gray',
        }
    }
  }, [rule, t])
 
  const fromPrefix = t('fromPrefix')
 
  if (!rule) {
    return <>{children}</>
  }
 
  const contentClasses = `reason-tooltip reason-tooltip--${ruleInfo.color}`
 
  const tooltipId = `tooltip-${termIndex}`
 
  const handleOpenChange = (open: boolean) => {
    if (open) {
      const granted = ui.requestFocus('term')
      if (granted) {
        setIsOpen(true)
      }
    } else {
      ui.releaseFocus('term')
      setIsOpen(false)
    }
  }
 
  return (
    <HoverCard.Root open={isOpen} onOpenChange={handleOpenChange} openDelay={150} closeDelay={400}>
      <HoverCard.Trigger asChild>
        <span aria-describedby={`${tooltipId}-description`}>{children}</span>
      </HoverCard.Trigger>
 
      <HoverCard.Portal>
        <HoverCard.Content
          id={tooltipId}
          className={contentClasses}
          sideOffset={8}
          side="top"
          align="center"
        >
          <div className="reason-tooltip__content">
            <div className="reason-tooltip__header">
              <span className="reason-tooltip__emoji">{ruleInfo.emoji}</span>
              <div className="reason-tooltip__title">
                <h4 className="reason-tooltip__name">
                  {enhancedContent?.title || readable?.title || ruleInfo.name}
                </h4>
                <p id={`${tooltipId}-description`} className="reason-tooltip__description">
                  {enhancedContent?.subtitle || readable?.subtitle || ruleInfo.description}
                </p>
              </div>
            </div>
 
            {/* Primary, concise explanation */}
            {segment?.readable?.summary && (
              <div className="reason-tooltip__summary">
                <p className="reason-tooltip__explanation-text">{segment.readable.summary}</p>
              </div>
            )}
 
            {/* Optional provenance nudge (avoid duplicating subtitle) */}
            {provenance &&
              !(enhancedContent?.subtitle || readable?.subtitle || '').includes(
                `${fromPrefix} `
              ) && (
                <div className="reason-tooltip__reasoning">
                  <p className="reason-tooltip__explanation-text">
                    {t('reasoning', {
                      addend: provenance.rhs,
                      place: provenance.rhsPlaceName,
                      digit: provenance.rhsDigit,
                    })}
                  </p>
                </div>
              )}
 
            {/* More details disclosure for optional content */}
            {((enhancedContent?.chips || readable?.chips)?.length ||
              readable?.carryPath ||
              readable?.showMath ||
              (readable && readable.stepsFriendly.length > 1)) && (
              <div className="reason-tooltip__details">
                <button
                  className="reason-tooltip__details-toggle"
                  onClick={() => setShowDetails(!showDetails)}
                  aria-expanded={showDetails}
                  aria-controls={`${tooltipId}-details`}
                  type="button"
                >
                  <span className="reason-tooltip__details-label">
                    {t('details.toggle')}
                    <span
                      className="reason-tooltip__chevron"
                      style={{
                        transform: showDetails ? 'rotate(180deg)' : 'rotate(0deg)',
                      }}
                    >
                      ▼
                    </span>
                  </span>
                </button>
 
                {showDetails && (
                  <div id={`${tooltipId}-details`} className="reason-tooltip__details-content">
                    {/* Context chips */}
                    {(enhancedContent?.chips || readable?.chips)?.length ? (
                      <div className="reason-tooltip__context">
                        <dl className="reason-tooltip__chips">
                          {(enhancedContent?.chips || readable?.chips || []).map((chip, index) => (
                            <div key={index} className="reason-tooltip__chip">
                              <dt>{chip.label}</dt>
                              <dd>{chip.value}</dd>
                            </div>
                          ))}
                        </dl>
                      </div>
                    ) : null}

                    {/* Carry path only when it's interesting (cascades) */}
                    {segment?.plan?.some((p) => p.rule === 'Cascade') && readable?.carryPath && (
                      <div className="reason-tooltip__carry-path">
                        <p className="reason-tooltip__carry-description">
                          <strong>{t('details.carryPath')}</strong> {readable.carryPath}
                        </p>
                      </div>
                    )}

                    {/* Math toggle */}
                    {readable?.showMath && (
                      <div className="reason-tooltip__advanced">
                        <button
                          className="reason-tooltip__math-toggle"
                          onClick={() => setShowMath(!showMath)}
                          aria-expanded={showMath}
                          type="button"
                        >
                          <span className="reason-tooltip__math-label">
                            {t('details.showMath')}
                            <span
                              className="reason-tooltip__chevron"
                              style={{
                                transform: showMath ? 'rotate(180deg)' : 'rotate(0deg)',
                              }}
                            >

                            </span>
                          </span>
                        </button>

                        {showMath && (
                          <div className="reason-tooltip__math-content">
                            {readable.showMath.lines.map((line, index) => (
                              <p key={index} className="reason-tooltip__math-line">
                                {line}
                              </p>
                            ))}
                          </div>
                        )}
                      </div>
                    )}

                    {/* Step-by-step breakdown */}
                    {readable && readable.stepsFriendly.length > 1 && (
                      <div className="reason-tooltip__steps">
                        <button
                          className="reason-tooltip__expand-button"
                          onClick={() => setShowBeadDetails(!showBeadDetails)}
                          onKeyDown={(e) => {
                            if (e.key === 'Enter' || e.key === ' ') {
                              e.preventDefault()
                              setShowBeadDetails(!showBeadDetails)
                            }
                          }}
                          aria-expanded={showBeadDetails}
                          aria-controls={`${tooltipId}-steps`}
                          type="button"
                        >
                          <span className="reason-tooltip__section-title">
                            {t('details.steps')}
                            <span
                              className="reason-tooltip__chevron"
                              style={{
                                transform: showBeadDetails ? 'rotate(180deg)' : 'rotate(0deg)',
                              }}
                            >

                            </span>
                          </span>
                        </button>

                        {showBeadDetails && (
                          <ol id={`${tooltipId}-steps`} className="reason-tooltip__step-list">
                            {readable.stepsFriendly.map((stepInstruction, idx) => (
                              <li key={idx} className="reason-tooltip__step">
                                <span className="reason-tooltip__step-instruction">
                                  {stepInstruction}
                                </span>
                              </li>
                            ))}
                          </ol>
                        )}
                      </div>
                    )}
                  </div>
                )}
              </div>
            )}
 
            {/* Dev-only validation hint */}
            {process.env.NODE_ENV !== 'production' &&
              segment?.readable?.validation &&
              !segment.readable.validation.ok && (
                <div className="reason-tooltip__dev-warn">
                  {t('devWarning', {
                    issues: segment.readable.validation.issues.join('; '),
                  })}
                </div>
              )}
 
            {/* Original transformation shown at bottom */}
            {originalValue && segment?.expression && (
              <div className="reason-tooltip__formula">
                <div className="reason-tooltip__expansion">
                  <span className="reason-tooltip__original">{originalValue}</span>
                  <span className="reason-tooltip__arrow">→</span>
                  <code className="reason-tooltip__expanded">{segment.expression}</code>
                </div>
                <div className="reason-tooltip__label">
                  {t('formula', {
                    original: originalValue,
                    expanded: segment.expression,
                  })}
                </div>
              </div>
            )}
          </div>
 
          <HoverCard.Arrow className="reason-tooltip__arrow" />
        </HoverCard.Content>
      </HoverCard.Portal>
    </HoverCard.Root>
  )
}