All files / web/src/components/worksheet-parsing EditableProblemRow.tsx

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

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

/**
 * EditableProblemRow - Inline editor for parsed worksheet problems
 *
 * Allows users to correct:
 * - Problem terms (the addends/subtrahends)
 * - Student's answer
 * - Mark problem for exclusion
 */

import type { ReactNode } from 'react'
import { useState, useCallback, useRef, useEffect, useMemo } from 'react'
import { css } from '../../../styled-system/css'
import type { ParsedProblem } from '@/lib/worksheet-parsing'
import { Tooltip } from '@/components/ui/Tooltip'

export interface ProblemCorrection {
  problemNumber: number
  correctedTerms?: number[] | null
  correctedStudentAnswer?: number | null
  shouldExclude?: boolean
  shouldRestore?: boolean
}

export interface EditableProblemRowProps {
  /** The problem data */
  problem: ParsedProblem
  /** The 0-based index of this problem in the list */
  index: number
  /** Whether this problem is currently selected (highlighted on image) */
  isSelected: boolean
  /** Callback when this problem is clicked (for highlighting) */
  onSelect: () => void
  /** Callback when corrections are submitted */
  onSubmitCorrection: (correction: ProblemCorrection) => void
  /** Whether a correction is currently being saved */
  isSaving: boolean
  /** Dark mode styling */
  isDark?: boolean
  /** Whether any problems are selected (shows all checkboxes when true) */
  hasSelections?: boolean
  /** Whether this problem is checked for re-parsing */
  isCheckedForReparse?: boolean
  /** Callback when checkbox is toggled */
  onToggleReparse?: (index: number) => void
  /** Optional cropped thumbnail URL for this problem */
  thumbnailUrl?: string
}

/**
 * Parse a terms string like "45 + 27 - 12" into an array of numbers
 */
function parseTermsString(input: string): number[] | null {
  const cleaned = input.trim()
  if (!cleaned) return null

  // Split by + or - while keeping the operator
  const parts = cleaned.split(/([+-])/).filter((p) => p.trim())

  const terms: number[] = []
  let sign = 1

  for (const part of parts) {
    const trimmed = part.trim()
    if (trimmed === '+') {
      sign = 1
    } else if (trimmed === '-') {
      sign = -1
    } else {
      const num = parseInt(trimmed, 10)
      if (Number.isNaN(num)) return null
      terms.push(sign * num)
      sign = 1 // Reset sign after using
    }
  }

  return terms.length > 0 ? terms : null
}

/**
 * Format terms array into a string like "45 + 27 - 12"
 */
function formatTerms(terms: number[]): string {
  if (terms.length === 0) return ''
  if (terms.length === 1) return terms[0].toString()

  return terms
    .map((term, i) => {
      if (i === 0) return term.toString()
      if (term >= 0) return `+ ${term}`
      return `- ${Math.abs(term)}`
    })
    .join(' ')
}

/**
 * Tooltip content showing confidence details and LLM notes
 */
function ConfidenceTooltipContent({
  termsConfidence,
  answerConfidence,
  notes,
}: {
  termsConfidence: number
  answerConfidence: number
  notes?: string | null
}): ReactNode {
  const minConfidence = Math.min(termsConfidence, answerConfidence)
  const confidencePercent = Math.round(minConfidence * 100)

  // Determine confidence level label and color
  const getConfidenceLevel = (pct: number) => {
    if (pct >= 80) return { label: 'High confidence', color: 'green.400' }
    if (pct >= 50) return { label: 'Uncertain', color: 'yellow.400' }
    return { label: 'Low confidence', color: 'red.400' }
  }

  const level = getConfidenceLevel(confidencePercent)

  return (
    <div
      className={css({
        display: 'flex',
        flexDirection: 'column',
        gap: 2,
        maxWidth: '280px',
      })}
    >
      {/* Confidence percentage and label */}
      <div className={css({ display: 'flex', alignItems: 'center', gap: 2 })}>
        <span
          className={css({
            fontSize: 'lg',
            fontWeight: 'bold',
            color: level.color,
          })}
        >
          {confidencePercent}%
        </span>
        <span className={css({ fontSize: 'sm', color: level.color })}>{level.label}</span>
      </div>

      {/* LLM notes if present */}
      {notes && (
        <div
          className={css({
            fontSize: 'sm',
            color: 'gray.300',
            borderLeft: '2px solid token(colors.yellow.600)',
            paddingLeft: 2,
            fontStyle: 'italic',
          })}
        >
          "{notes}"
        </div>
      )}

      {/* Confidence scale explanation */}
      <div
        className={css({
          fontSize: 'xs',
          color: 'gray.400',
          borderTop: '1px solid token(colors.gray.700)',
          paddingTop: 2,
          marginTop: 1,
        })}
      >
        <div className={css({ fontWeight: 'medium', marginBottom: 1 })}>What this means:</div>
        <div
          className={css({
            display: 'flex',
            flexDirection: 'column',
            gap: 0.5,
          })}
        >
          <span>
            <span className={css({ color: 'green.400' })}>●</span> 80%+ = Confident reading
          </span>
          <span>
            <span className={css({ color: 'yellow.400' })}>●</span> 50-79% = Unsure, check this
          </span>
          <span>
            <span className={css({ color: 'red.400' })}>●</span> &lt;50% = Likely wrong, verify
          </span>
        </div>
      </div>
    </div>
  )
}

export function EditableProblemRow({
  problem,
  index,
  isSelected,
  onSelect,
  onSubmitCorrection,
  isSaving,
  isDark = true,
  hasSelections = false,
  isCheckedForReparse = false,
  onToggleReparse,
  thumbnailUrl,
}: EditableProblemRowProps): ReactNode {
  const [isEditing, setIsEditing] = useState(false)
  const [isHovered, setIsHovered] = useState(false)
  const [termsInput, setTermsInput] = useState(formatTerms(problem.terms))
  const [studentAnswerInput, setStudentAnswerInput] = useState(
    problem.studentAnswer?.toString() ?? ''
  )
  const [termsError, setTermsError] = useState<string | null>(null)
  const [answerError, setAnswerError] = useState<string | null>(null)

  const termsInputRef = useRef<HTMLInputElement>(null)

  // Focus terms input when entering edit mode
  useEffect(() => {
    if (isEditing && termsInputRef.current) {
      termsInputRef.current.focus()
      termsInputRef.current.select()
    }
  }, [isEditing])

  // Reset form when problem changes
  useEffect(() => {
    setTermsInput(formatTerms(problem.terms))
    setStudentAnswerInput(problem.studentAnswer?.toString() ?? '')
    setTermsError(null)
    setAnswerError(null)
  }, [problem])

  // Check if form inputs are valid (for enabling Save button)
  const isFormValid = useMemo(() => {
    // Terms must parse and have at least 2 terms
    const parsedTerms = parseTermsString(termsInput)
    if (!parsedTerms || parsedTerms.length < 2) return false

    // Student answer must be empty or a valid number
    if (studentAnswerInput.trim()) {
      const parsed = parseInt(studentAnswerInput.trim(), 10)
      if (Number.isNaN(parsed)) return false
    }

    return true
  }, [termsInput, studentAnswerInput])

  const handleEdit = useCallback((e: React.MouseEvent) => {
    e.stopPropagation()
    setIsEditing(true)
  }, [])

  const handleCancel = useCallback(
    (e: React.MouseEvent) => {
      e.stopPropagation()
      setIsEditing(false)
      setTermsInput(formatTerms(problem.terms))
      setStudentAnswerInput(problem.studentAnswer?.toString() ?? '')
      setTermsError(null)
      setAnswerError(null)
    },
    [problem]
  )

  const handleSave = useCallback(
    (e: React.MouseEvent) => {
      e.stopPropagation()

      // Validate terms
      const parsedTerms = parseTermsString(termsInput)
      if (!parsedTerms || parsedTerms.length < 2) {
        setTermsError('Enter at least 2 terms (e.g., "45 + 27")')
        return
      }

      // Validate student answer (can be empty for "no answer")
      let parsedAnswer: number | null = null
      if (studentAnswerInput.trim()) {
        parsedAnswer = parseInt(studentAnswerInput.trim(), 10)
        if (Number.isNaN(parsedAnswer)) {
          setAnswerError('Enter a valid number or leave blank')
          return
        }
      }

      // Check if anything actually changed
      const termsChanged = JSON.stringify(parsedTerms) !== JSON.stringify(problem.terms)
      const answerChanged = parsedAnswer !== problem.studentAnswer

      if (!termsChanged && !answerChanged) {
        // Nothing changed, just exit edit mode
        setIsEditing(false)
        return
      }

      // Submit correction
      onSubmitCorrection({
        problemNumber: problem.problemNumber,
        correctedTerms: termsChanged ? parsedTerms : undefined,
        correctedStudentAnswer: answerChanged ? parsedAnswer : undefined,
      })

      setIsEditing(false)
    },
    [termsInput, studentAnswerInput, problem, onSubmitCorrection]
  )

  const handleKeyDown = useCallback(
    (e: React.KeyboardEvent) => {
      if (e.key === 'Enter') {
        handleSave(e as unknown as React.MouseEvent)
      } else if (e.key === 'Escape') {
        handleCancel(e as unknown as React.MouseEvent)
      }
    },
    [handleSave, handleCancel]
  )

  const handleCheckboxClick = useCallback(
    (e: React.MouseEvent) => {
      e.stopPropagation()
      onToggleReparse?.(index)
    },
    [index, onToggleReparse]
  )

  const isExcluded = problem.excluded === true
  const isCorrect =
    problem.studentAnswer !== null && problem.studentAnswer === problem.correctAnswer
  const isIncorrect =
    problem.studentAnswer !== null && problem.studentAnswer !== problem.correctAnswer
  const isLowConfidence = Math.min(problem.termsConfidence, problem.studentAnswerConfidence) < 0.7

  // Edit mode UI
  if (isEditing) {
    return (
      <div
        data-element="problem-row-editing"
        data-problem-index={index}
        className={css({
          padding: 3,
          backgroundColor: isDark ? 'blue.900' : 'blue.50',
          borderRadius: 'lg',
          border: '2px solid token(colors.blue.500)',
        })}
        onClick={(e) => e.stopPropagation()}
      >
        <div
          className={css({
            display: 'flex',
            alignItems: 'center',
            gap: 2,
            marginBottom: 3,
          })}
        >
          <span
            className={css({
              fontSize: 'sm',
              fontWeight: 'medium',
              color: isDark ? 'gray.400' : 'gray.600',
            })}
          >
            #{index + 1}
          </span>
          <span
            className={css({
              fontSize: 'xs',
              px: 2,
              py: 0.5,
              borderRadius: 'md',
              backgroundColor: isDark ? 'blue.800' : 'blue.100',
              color: isDark ? 'blue.300' : 'blue.700',
            })}
          >
            Editing
          </span>
        </div>

        {/* Terms input */}
        <div className={css({ marginBottom: 3 })}>
          <label
            className={css({
              display: 'block',
              fontSize: 'xs',
              fontWeight: 'medium',
              color: isDark ? 'gray.400' : 'gray.600',
              marginBottom: 1,
            })}
          >
            Problem terms (e.g., "45 + 27 - 12")
          </label>
          <input
            ref={termsInputRef}
            type="text"
            value={termsInput}
            onChange={(e) => {
              setTermsInput(e.target.value)
              setTermsError(null)
            }}
            onKeyDown={handleKeyDown}
            className={css({
              width: '100%',
              px: 3,
              py: 2,
              fontSize: 'sm',
              fontFamily: 'mono',
              backgroundColor: isDark ? 'gray.800' : 'white',
              color: isDark ? 'white' : 'gray.900',
              border: '1px solid',
              borderColor: termsError ? 'red.500' : isDark ? 'gray.600' : 'gray.300',
              borderRadius: 'md',
              _focus: {
                outline: 'none',
                borderColor: 'blue.500',
                boxShadow: '0 0 0 2px token(colors.blue.500/20)',
              },
            })}
            placeholder="45 + 27 - 12"
          />
          {termsError && (
            <p
              className={css({
                fontSize: 'xs',
                color: 'red.400',
                marginTop: 1,
              })}
            >
              {termsError}
            </p>
          )}
        </div>

        {/* Student answer input */}
        <div className={css({ marginBottom: 3 })}>
          <label
            className={css({
              display: 'block',
              fontSize: 'xs',
              fontWeight: 'medium',
              color: isDark ? 'gray.400' : 'gray.600',
              marginBottom: 1,
            })}
          >
            Student's answer (leave blank if no answer)
          </label>
          <input
            type="text"
            value={studentAnswerInput}
            onChange={(e) => {
              setStudentAnswerInput(e.target.value)
              setAnswerError(null)
            }}
            onKeyDown={handleKeyDown}
            className={css({
              width: '100px',
              px: 3,
              py: 2,
              fontSize: 'sm',
              fontFamily: 'mono',
              backgroundColor: isDark ? 'gray.800' : 'white',
              color: isDark ? 'white' : 'gray.900',
              border: '1px solid',
              borderColor: answerError ? 'red.500' : isDark ? 'gray.600' : 'gray.300',
              borderRadius: 'md',
              _focus: {
                outline: 'none',
                borderColor: 'blue.500',
                boxShadow: '0 0 0 2px token(colors.blue.500/20)',
              },
            })}
            placeholder="60"
          />
          {answerError && (
            <p
              className={css({
                fontSize: 'xs',
                color: 'red.400',
                marginTop: 1,
              })}
            >
              {answerError}
            </p>
          )}
        </div>

        {/* Correct answer display */}
        <div
          className={css({
            fontSize: 'xs',
            color: isDark ? 'gray.500' : 'gray.500',
            marginBottom: 3,
          })}
        >
          Correct answer (from terms):{' '}
          <span className={css({ fontFamily: 'mono', fontWeight: 'medium' })}>
            {parseTermsString(termsInput)?.reduce((a, b) => a + b, 0) ?? '?'}
          </span>
        </div>

        {/* Action buttons */}
        <div
          className={css({
            display: 'flex',
            alignItems: 'center',
            gap: 2,
          })}
        >
          <button
            type="button"
            onClick={handleSave}
            disabled={isSaving || !isFormValid}
            className={css({
              px: 3,
              py: 1.5,
              fontSize: 'sm',
              fontWeight: 'medium',
              backgroundColor: 'green.600',
              color: 'white',
              border: 'none',
              borderRadius: 'md',
              cursor: 'pointer',
              _hover: { backgroundColor: 'green.700' },
              _disabled: { opacity: 0.5, cursor: 'not-allowed' },
            })}
          >
            {isSaving ? 'Saving...' : 'Save'}
          </button>
          <button
            type="button"
            onClick={handleCancel}
            disabled={isSaving}
            className={css({
              px: 3,
              py: 1.5,
              fontSize: 'sm',
              fontWeight: 'medium',
              backgroundColor: isDark ? 'gray.700' : 'gray.200',
              color: isDark ? 'white' : 'gray.700',
              border: 'none',
              borderRadius: 'md',
              cursor: 'pointer',
              _hover: { backgroundColor: isDark ? 'gray.600' : 'gray.300' },
              _disabled: { opacity: 0.5, cursor: 'not-allowed' },
            })}
          >
            Cancel
          </button>
        </div>
      </div>
    )
  }

  // Show checkbox if hovered, has any selections, or this is checked
  const showCheckbox = isHovered || hasSelections || isCheckedForReparse

  // Determine the background color based on state
  const bgColor = isExcluded
    ? isDark
      ? 'gray.800'
      : 'gray.200'
    : isSelected
      ? isDark
        ? 'blue.900'
        : 'blue.50'
      : isCheckedForReparse
        ? isDark
          ? 'blue.900/50'
          : 'blue.50'
        : isLowConfidence
          ? isDark
            ? 'yellow.900/30'
            : 'yellow.50'
          : isDark
            ? 'gray.700'
            : 'gray.100'

  const hoverBgColor = isExcluded
    ? isDark
      ? 'gray.700'
      : 'gray.300'
    : isSelected
      ? isDark
        ? 'blue.900'
        : 'blue.100'
      : isDark
        ? 'gray.600'
        : 'gray.200'

  // Display mode UI
  return (
    <div
      data-element="problem-row-container"
      data-problem-index={index}
      data-selected={isSelected}
      data-checked={isCheckedForReparse}
      data-excluded={isExcluded}
      className={css({
        display: 'flex',
        alignItems: 'stretch',
        gap: 0,
        borderRadius: 'lg',
        backgroundColor: bgColor,
        border: isSelected
          ? '2px solid token(colors.blue.500)'
          : isCheckedForReparse
            ? '2px solid token(colors.blue.500/50)'
            : '2px solid transparent',
        cursor: 'pointer',
        transition: 'all 0.15s',
        _hover: {
          backgroundColor: hoverBgColor,
        },
      })}
      onMouseEnter={() => setIsHovered(true)}
      onMouseLeave={() => setIsHovered(false)}
    >
      {/* Checkbox - always takes up space when onToggleReparse is provided, but only visible on hover/selection */}
      {onToggleReparse && (
        <button
          type="button"
          data-action="toggle-reparse"
          onClick={handleCheckboxClick}
          className={css({
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            width: '40px',
            flexShrink: 0,
            backgroundColor: 'transparent',
            borderRadius: 'lg 0 0 lg',
            border: 'none',
            cursor: 'pointer',
            transition: 'opacity 0.15s',
            // Hide checkbox visually but keep space reserved
            opacity: showCheckbox ? (isCheckedForReparse || isHovered ? 1 : 0.5) : 0,
            pointerEvents: showCheckbox ? 'auto' : 'none',
          })}
        >
          <div
            className={css({
              width: '20px',
              height: '20px',
              borderRadius: 'sm',
              border: '2px solid',
              borderColor: isCheckedForReparse ? 'blue.400' : isDark ? 'gray.500' : 'gray.400',
              backgroundColor: isCheckedForReparse ? 'blue.500' : 'transparent',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              color: 'white',
              fontSize: 'xs',
              fontWeight: 'bold',
            })}
          >
            {isCheckedForReparse && '✓'}
          </div>
        </button>
      )}
      <div
        role="button"
        tabIndex={0}
        data-element="problem-row"
        onClick={onSelect}
        onKeyDown={(e) => {
          if (e.key === 'Enter' || e.key === ' ') {
            e.preventDefault()
            onSelect()
          }
        }}
        className={css({
          flex: 1,
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between',
          gap: 3,
          padding: 3,
          backgroundColor: 'transparent',
          borderRadius: onToggleReparse ? '0 lg lg 0' : 'lg',
          border: 'none',
          cursor: 'pointer',
          textAlign: 'left',
        })}
      >
        {/* Small thumbnail of cropped problem region - fixed size container */}
        <div
          className={css({
            width: '48px',
            height: '32px',
            flexShrink: 0,
            borderRadius: 'sm',
            overflow: 'hidden',
            backgroundColor: 'gray.900',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
          })}
        >
          {thumbnailUrl && (
            <img
              src={thumbnailUrl}
              alt=""
              className={css({
                maxWidth: '100%',
                maxHeight: '100%',
                objectFit: 'contain',
              })}
            />
          )}
        </div>
        <div
          className={css({
            display: 'flex',
            flexDirection: 'column',
            gap: 1,
            flex: 1,
            opacity: isExcluded ? 0.5 : 1,
          })}
        >
          {/* Problem expression */}
          <div
            className={css({
              fontFamily: 'mono',
              fontSize: 'sm',
              color: isExcluded
                ? isDark
                  ? 'gray.500'
                  : 'gray.500'
                : isDark
                  ? 'white'
                  : 'gray.900',
              textDecoration: isExcluded ? 'line-through' : 'none',
            })}
          >
            #{index + 1}: {formatTerms(problem.terms)} ={' '}
            <span
              className={css({
                color:
                  problem.studentAnswer === null
                    ? isDark
                      ? 'gray.500'
                      : 'gray.400'
                    : isCorrect
                      ? isDark
                        ? 'green.400'
                        : 'green.600'
                      : isDark
                        ? 'red.400'
                        : 'red.600',
              })}
            >
              {problem.studentAnswer ?? '?'}
            </span>
          </div>

          {/* Correct answer and status */}
          <div
            className={css({
              fontSize: 'xs',
              color: isCorrect
                ? isDark
                  ? 'green.400'
                  : 'green.600'
                : problem.studentAnswer == null
                  ? isDark
                    ? 'gray.500'
                    : 'gray.500'
                  : isDark
                    ? 'red.400'
                    : 'red.600',
            })}
          >
            {isCorrect
              ? '✓ Correct'
              : problem.studentAnswer == null
                ? 'No answer detected'
                : `✗ Incorrect (correct: ${problem.correctAnswer})`}
          </div>
        </div>

        <div
          className={css({
            display: 'flex',
            alignItems: 'center',
            gap: 2,
          })}
        >
          {/* Low confidence warning with tooltip */}
          {isLowConfidence && (
            <Tooltip
              side="left"
              content={
                <ConfidenceTooltipContent
                  termsConfidence={problem.termsConfidence}
                  answerConfidence={problem.studentAnswerConfidence}
                  notes={problem.notes}
                />
              }
            >
              <span
                className={css({
                  fontSize: 'sm',
                  cursor: 'help',
                })}
              >
                ⚠️
              </span>
            </Tooltip>
          )}

          {/* Excluded badge or Edit button */}
          {isExcluded ? (
            <span
              className={css({
                px: 2,
                py: 1,
                fontSize: 'xs',
                fontWeight: 'medium',
                borderRadius: 'md',
                backgroundColor: isDark ? 'gray.700' : 'gray.300',
                color: isDark ? 'gray.400' : 'gray.600',
              })}
            >
              Excluded
            </span>
          ) : (
            <button
              type="button"
              data-action="edit-problem"
              onClick={handleEdit}
              className={css({
                px: 2,
                py: 1,
                fontSize: 'xs',
                fontWeight: 'medium',
                backgroundColor: isDark ? 'gray.600' : 'gray.200',
                color: isDark ? 'white' : 'gray.700',
                border: 'none',
                borderRadius: 'md',
                cursor: 'pointer',
                _hover: {
                  backgroundColor: isDark ? 'gray.500' : 'gray.300',
                },
              })}
            >
              ✏️ Edit
            </button>
          )}
        </div>
      </div>
    </div>
  )
}

export default EditableProblemRow