All files / web/src/components/practice PurposeBadge.tsx

94.14% Statements 450/478
84.7% Branches 72/85
100% Functions 6/6
94.14% Lines 450/478

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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21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 10x 10x 10x 10x 21x 21x 21x 2x 2x 2x 2x 21x 21x 21x 3x 3x         3x 3x 3x 3x 3x 3x 3x 3x 21x 21x 21x 3x 3x 3x 3x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 10x   10x 11x 5x   5x 6x 3x   3x 3x   3x 21x 21x 10x   10x 11x 5x   5x 6x 3x   3x 3x   3x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x  
'use client'
 
import { useTheme } from '@/contexts/ThemeContext'
import type { ProblemSlot } from '@/db/schema/session-plans'
import { Tooltip, TooltipProvider } from '../ui/Tooltip'
import { css } from '../../../styled-system/css'
 
type Purpose = 'focus' | 'reinforce' | 'review' | 'challenge'
 
/**
 * Minimal complexity data for tooltip display
 * Used when full slot isn't available (e.g., in session observer)
 */
export interface ComplexityData {
  /** Complexity bounds from slot constraints */
  bounds?: { min?: number; max?: number }
  /** Total complexity cost from generation trace */
  totalCost?: number
  /** Number of steps (for per-term average) */
  stepCount?: number
  /** Pre-formatted target skill name */
  targetSkillName?: string
}
 
interface PurposeBadgeProps {
  /** The purpose type */
  purpose: Purpose
  /** Optional slot for detailed tooltip (when available) */
  slot?: ProblemSlot
  /** Optional simplified complexity data (alternative to slot, for observers) */
  complexity?: ComplexityData
}
 
/**
 * Extract the primary skill from constraints for display
 */
export function extractTargetSkillName(slot: ProblemSlot): string | null {
  const targetSkills = slot.constraints?.targetSkills
  if (!targetSkills) return null
 
  // Look for specific skill in targetSkills
  for (const [category, skills] of Object.entries(targetSkills)) {
    if (skills && typeof skills === 'object') {
      const skillKeys = Object.keys(skills)
      if (skillKeys.length === 1) {
        // Single skill - this is a targeted reinforce/review
        return formatSkillName(category, skillKeys[0])
      }
    }
  }
  return null
}
 
/**
 * Format a skill ID into a human-readable name
 */
export function formatSkillName(category: string, skillKey: string): string {
  // Categories: basic, fiveComplements, tenComplements
  if (category === 'basic') {
    // Format "+3" or "-5" into "add 3" or "subtract 5"
    if (skillKey.startsWith('+')) {
      return `add ${skillKey.slice(1)}`
    }
    if (skillKey.startsWith('-')) {
      return `subtract ${skillKey.slice(1)}`
    }
    return skillKey
  }
 
  if (category === 'fiveComplements') {
    // Format "4=5-1" into "5-complement for 4"
    const match = skillKey.match(/^(\d+)=/)
    if (match) {
      return `5-complement for ${match[1]}`
    }
    return skillKey
  }
 
  if (category === 'tenComplements') {
    // Format "9=10-1" into "10-complement for 9"
    const match = skillKey.match(/^(\d+)=/)
    if (match) {
      return `10-complement for ${match[1]}`
    }
    return skillKey
  }
 
  return `${category}: ${skillKey}`
}
 
/**
 * Complexity section for purpose tooltip - shows complexity bounds and actual costs
 * Accepts either a full slot or simplified complexity data
 */
function ComplexitySection({
  slot,
  complexity,
  showBounds = true,
}: {
  slot?: ProblemSlot
  complexity?: ComplexityData
  showBounds?: boolean
}) {
  // Extract data from slot or use simplified complexity data
  const bounds = slot?.complexityBounds ?? complexity?.bounds
  const totalCost = slot?.problem?.generationTrace?.totalComplexityCost ?? complexity?.totalCost
  const stepCount = slot?.problem?.generationTrace?.steps?.length ?? complexity?.stepCount
 
  const hasBounds = bounds && (bounds.min !== undefined || bounds.max !== undefined)
  const hasCost = totalCost !== undefined && !Number.isNaN(totalCost)
 
  // Don't render anything if no complexity data
  if (!hasBounds && !hasCost) {
    return null
  }
 
  const sectionStyles = {
    container: css({
      marginTop: '0.5rem',
      padding: '0.5rem',
      backgroundColor: 'gray.800',
      borderRadius: '6px',
      fontSize: '0.8125rem',
    }),
    header: css({
      display: 'flex',
      alignItems: 'center',
      gap: '0.25rem',
      color: 'gray.400',
      fontWeight: '500',
      marginBottom: '0.375rem',
    }),
    row: css({
      display: 'flex',
      justifyContent: 'space-between',
      alignItems: 'center',
      color: 'gray.300',
      paddingY: '0.125rem',
    }),
    value: css({
      fontFamily: 'mono',
      color: 'white',
    }),
    boundsLabel: css({
      color: 'gray.500',
      fontSize: '0.75rem',
    }),
  }
 
  // Format bounds string
  let boundsText = ''
  if (bounds?.min !== undefined && bounds?.max !== undefined) {
    boundsText = `${bounds.min} – ${bounds.max}`
  } else if (bounds?.min !== undefined) {
    boundsText = `≥${bounds.min}`
  } else if (bounds?.max !== undefined) {
    boundsText = `≤${bounds.max}`
  }
 
  return (
    <div className={sectionStyles.container} data-element="complexity-section">
      <div className={sectionStyles.header}>
        <span>📊</span>
        <span>Complexity</span>
      </div>
      {showBounds && hasBounds && (
        <div className={sectionStyles.row}>
          <span className={sectionStyles.boundsLabel}>Required range:</span>
          <span className={sectionStyles.value}>{boundsText}</span>
        </div>
      )}
      {hasCost && (
        <div className={sectionStyles.row}>
          <span>Total cost:</span>
          <span className={sectionStyles.value}>{totalCost}</span>
        </div>
      )}
      {hasCost && stepCount && stepCount > 0 && (
        <div className={sectionStyles.row}>
          <span>Per term (avg):</span>
          <span className={sectionStyles.value}>{(totalCost! / stepCount).toFixed(1)}</span>
        </div>
      )}
    </div>
  )
}
 
/**
 * Term count section for purpose tooltip - shows dynamic term count scaling info
 */
function TermCountSection({ slot }: { slot?: ProblemSlot }) {
  const explanation = slot?.termCountExplanation
  if (!explanation) return null

  const { comfortLevel, factors, dynamicRange, override, finalRange } = explanation
  const modeLabel =
    factors.sessionMode === 'remediation'
      ? 'Remediation (shorter)'
      : factors.sessionMode === 'progression'
        ? 'Progression'
        : 'Maintenance'
 
  const sectionStyles = {
    container: css({
      marginTop: '0.5rem',
      padding: '0.5rem',
      backgroundColor: 'gray.800',
      borderRadius: '6px',
      fontSize: '0.8125rem',
    }),
    header: css({
      display: 'flex',
      alignItems: 'center',
      gap: '0.25rem',
      color: 'gray.400',
      fontWeight: '500',
      marginBottom: '0.375rem',
    }),
    row: css({
      display: 'flex',
      justifyContent: 'space-between',
      alignItems: 'center',
      color: 'gray.300',
      paddingY: '0.125rem',
    }),
    value: css({
      fontFamily: 'mono',
      color: 'white',
    }),
  }
 
  return (
    <div className={sectionStyles.container} data-element="term-count-section">
      <div className={sectionStyles.header}>
        <span>&#x1F4D0;</span>
        <span>Problem Length</span>
      </div>
      <div className={sectionStyles.row}>
        <span>Terms:</span>
        <span className={sectionStyles.value}>
          {finalRange.min}&ndash;{finalRange.max}
        </span>
      </div>
      <div className={sectionStyles.row}>
        <span>Comfort level:</span>
        <span className={sectionStyles.value}>{Math.round(comfortLevel * 100)}%</span>
      </div>
      <div className={sectionStyles.row}>
        <span>Session mode:</span>
        <span>{modeLabel}</span>
      </div>
      {factors.avgMastery !== null && (
        <div className={sectionStyles.row}>
          <span>Avg mastery:</span>
          <span className={sectionStyles.value}>{Math.round(factors.avgMastery * 100)}%</span>
        </div>
      )}
      {override && (
        <div className={sectionStyles.row}>
          <span>Override cap:</span>
          <span className={sectionStyles.value}>max {override.max}</span>
        </div>
      )}
    </div>
  )
}
 
const tooltipStyles = {
  container: css({
    display: 'flex',
    flexDirection: 'column',
    gap: '0.5rem',
  }),
  header: css({
    display: 'flex',
    alignItems: 'center',
    gap: '0.5rem',
    fontWeight: 'bold',
    fontSize: '0.9375rem',
  }),
  emoji: css({
    fontSize: '1.125rem',
  }),
  description: css({
    color: 'gray.300',
    lineHeight: '1.5',
  }),
  detail: css({
    display: 'flex',
    alignItems: 'center',
    gap: '0.375rem',
    padding: '0.375rem 0.5rem',
    backgroundColor: 'gray.800',
    borderRadius: '6px',
    fontSize: '0.8125rem',
  }),
  detailLabel: css({
    color: 'gray.400',
    fontWeight: '500',
  }),
  detailValue: css({
    color: 'white',
    fontFamily: 'mono',
  }),
}
 
const purposeInfo: Record<Purpose, { emoji: string; title: string; description: string }> = {
  focus: {
    emoji: '🎯',
    title: 'Focus Practice',
    description:
      "Building mastery of your current curriculum skills. These problems are at the heart of what you're learning right now.",
  },
  reinforce: {
    emoji: '💪',
    title: 'Reinforcement',
    description:
      'Extra practice for skills identified as needing more work. These problems target areas where mastery is still developing.',
  },
  review: {
    emoji: '🔄',
    title: 'Spaced Review',
    description:
      'Keeping mastered skills fresh through spaced repetition. Regular review prevents forgetting and strengthens long-term memory.',
  },
  challenge: {
    emoji: '⭐',
    title: 'Challenge',
    description:
      'Harder problems that require complement techniques for every term. These push your skills and build deeper fluency.',
  },
}
 
/**
 * Purpose tooltip content - rich explanatory content for each purpose
 */
function PurposeTooltipContent({
  purpose,
  slot,
  complexity,
}: {
  purpose: Purpose
  slot?: ProblemSlot
  complexity?: ComplexityData
}) {
  const info = purposeInfo[purpose]
  // Get skill name from slot or from simplified complexity data
  const skillName = slot ? extractTargetSkillName(slot) : (complexity?.targetSkillName ?? null)
 
  return (
    <div className={tooltipStyles.container}>
      <div className={tooltipStyles.header}>
        <span className={tooltipStyles.emoji}>{info.emoji}</span>
        <span>{info.title}</span>
      </div>
      <p className={tooltipStyles.description}>{info.description}</p>
 
      {/* Purpose-specific details */}
      {purpose === 'focus' && (
        <div className={tooltipStyles.detail}>
          <span className={tooltipStyles.detailLabel}>Distribution:</span>
          <span className={tooltipStyles.detailValue}>60% of session</span>
        </div>
      )}
 
      {purpose === 'reinforce' && skillName && (
        <div className={tooltipStyles.detail}>
          <span className={tooltipStyles.detailLabel}>Targeting:</span>
          <span className={tooltipStyles.detailValue}>{skillName}</span>
        </div>
      )}
 
      {purpose === 'review' && (
        <>
          {skillName && (
            <div className={tooltipStyles.detail}>
              <span className={tooltipStyles.detailLabel}>Reviewing:</span>
              <span className={tooltipStyles.detailValue}>{skillName}</span>
            </div>
          )}
          <div className={tooltipStyles.detail}>
            <span className={tooltipStyles.detailLabel}>Schedule:</span>
            <span className={tooltipStyles.detailValue}>
              Mastered: 14 days • Practicing: 7 days
            </span>
          </div>
        </>
      )}
 
      {purpose === 'challenge' && (
        <div className={tooltipStyles.detail}>
          <span className={tooltipStyles.detailLabel}>Requirement:</span>
          <span className={tooltipStyles.detailValue}>Every term uses complements</span>
        </div>
      )}
 
      {/* Complexity section when slot or complexity data is available */}
      {(slot || complexity) && <ComplexitySection slot={slot} complexity={complexity} />}
 
      {/* Term count section with comfort level details */}
      {slot && <TermCountSection slot={slot} />}
    </div>
  )
}
 
/**
 * Shared purpose badge component with tooltip
 *
 * Shows the slot's purpose (focus/reinforce/review/challenge) with
 * appropriate styling and a tooltip explaining what the purpose means.
 *
 * Used by both the student's ActiveSession and the teacher's SessionObserverModal.
 */
export function PurposeBadge({ purpose, slot, complexity }: PurposeBadgeProps) {
  const { resolvedTheme } = useTheme()
  const isDark = resolvedTheme === 'dark'
 
  const badgeStyles = css({
    position: 'relative',
    padding: '0.25rem 0.75rem',
    borderRadius: '20px',
    fontSize: '0.75rem',
    fontWeight: 'bold',
    textTransform: 'uppercase',
    cursor: 'help',
    transition: 'transform 0.15s ease, box-shadow 0.15s ease',
    _hover: {
      transform: 'scale(1.05)',
      boxShadow: 'sm',
    },
    backgroundColor:
      purpose === 'focus'
        ? isDark
          ? 'blue.900'
          : 'blue.100'
        : purpose === 'reinforce'
          ? isDark
            ? 'orange.900'
            : 'orange.100'
          : purpose === 'review'
            ? isDark
              ? 'green.900'
              : 'green.100'
            : isDark
              ? 'purple.900'
              : 'purple.100',
    color:
      purpose === 'focus'
        ? isDark
          ? 'blue.200'
          : 'blue.700'
        : purpose === 'reinforce'
          ? isDark
            ? 'orange.200'
            : 'orange.700'
          : purpose === 'review'
            ? isDark
              ? 'green.200'
              : 'green.700'
            : isDark
              ? 'purple.200'
              : 'purple.700',
  })
 
  return (
    <TooltipProvider>
      <Tooltip
        content={<PurposeTooltipContent purpose={purpose} slot={slot} complexity={complexity} />}
        side="bottom"
        delayDuration={300}
      >
        <div data-element="problem-purpose" data-purpose={purpose} className={badgeStyles}>
          {purpose}
        </div>
      </Tooltip>
    </TooltipProvider>
  )
}