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

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

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 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     
'use client'

import * as DropdownMenu from '@radix-ui/react-dropdown-menu'
import { animated, useSpring } from '@react-spring/web'
import { useRouter } from 'next/navigation'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { EnrollChildModal } from '@/components/classroom/EnrollChildModal'
import { FamilyCodeDisplay } from '@/components/family'
import { Z_INDEX } from '@/constants/zIndex'
import { usePageTransition } from '@/contexts/PageTransitionContext'
import { useTheme } from '@/contexts/ThemeContext'
import { usePlayerCurriculumQuery } from '@/hooks/usePlayerCurriculum'
import { useSessionMode } from '@/hooks/useSessionMode'
import { useStudentActions, type StudentActionData } from '@/hooks/useStudentActions'
import { useStudentStakeholders } from '@/hooks/useStudentStakeholders'
import { useUpdatePlayer } from '@/hooks/useUserPlayers'
import type { StudentActivity, StudentRelationship, UnifiedStudent } from '@/types/student'
import { css } from '../../../styled-system/css'
import { MiniStartPracticeBanner } from './MiniStartPracticeBanner'
import { RelationshipCard } from './RelationshipCard'
import { RelationshipSummary } from './RelationshipBadge'
import { ACTION_DEFINITIONS } from './studentActions'

// ============================================================================
// Types
// ============================================================================

/** Base student fields required for the modal */
interface BaseStudentFields {
  id: string
  name: string
  emoji: string
  color: string
  notes?: string | null
  isArchived?: boolean
}

/** Full student type with relationship and activity data */
type FullStudent = UnifiedStudent

/** Accept any object with the required base fields, plus optional unified student fields */
type StudentProp = BaseStudentFields &
  Partial<Pick<FullStudent, 'relationship' | 'activity' | 'intervention'>>

interface NotesModalProps {
  /** Whether the modal is open */
  isOpen: boolean
  /** Student to display - accepts simple or UnifiedStudent */
  student: StudentProp
  /** Bounding rect of the source tile for zoom animation */
  sourceBounds: DOMRect | null
  /** Called when the modal should close */
  onClose: () => void
  /** Callback when "Watch Session" is clicked - handled by parent to avoid z-index issues */
  onObserveSession?: (sessionId: string) => void
}

type TabId = 'overview' | 'notes' | 'relationships'

// ============================================================================
// Helper functions
// ============================================================================

function formatLastPracticed(date: Date | string | null | undefined): string {
  if (!date) return 'Never'
  const d = typeof date === 'string' ? new Date(date) : date
  const now = new Date()
  const diffMs = now.getTime() - d.getTime()
  const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24))

  if (diffDays === 0) return 'Today'
  if (diffDays === 1) return 'Yesterday'
  if (diffDays < 7) return `${diffDays} days ago`
  if (diffDays < 30) return `${Math.floor(diffDays / 7)} weeks ago`
  return `${Math.floor(diffDays / 30)} months ago`
}

function calculateMasteryPercent(skills: Array<{ attempts: number; correct: number }>): number {
  if (skills.length === 0) return 0
  const totalAttempts = skills.reduce((sum, s) => sum + s.attempts, 0)
  const totalCorrect = skills.reduce((sum, s) => sum + s.correct, 0)
  if (totalAttempts === 0) return 0
  return Math.round((totalCorrect / totalAttempts) * 100)
}

/** Build StudentActionData from StudentProp */
function buildStudentActionData(student: StudentProp): StudentActionData {
  return {
    id: student.id,
    name: student.name,
    isArchived: student.isArchived,
    relationship: student.relationship
      ? {
          isMyChild: student.relationship.isMyChild,
          isEnrolled: student.relationship.isEnrolled,
          isPresent: student.relationship.isPresent,
          enrollmentStatus: student.relationship.enrollmentStatus,
        }
      : undefined,
    activity: student.activity
      ? {
          status: student.activity.status,
          sessionId: student.activity.sessionId,
        }
      : undefined,
  }
}

// ============================================================================
// Main Component
// ============================================================================

/**
 * NotesModal - Student quick-look modal with tabs
 *
 * Features:
 * - Overview tab: Stats, badges, intervention
 * - Notes tab: View/edit student notes
 * - Overflow menu: All student actions (uses shared useStudentActions hook)
 * - Zoom animation from source tile
 */
export function NotesModal({
  isOpen,
  student,
  sourceBounds,
  onClose,
  onObserveSession,
}: NotesModalProps) {
  const router = useRouter()
  const { resolvedTheme } = useTheme()
  const isDark = resolvedTheme === 'dark'
  const { startTransition } = usePageTransition()

  // ========== Internal state (notes editing only) ==========
  const [activeTab, setActiveTab] = useState<TabId>('overview')
  const [isEditing, setIsEditing] = useState(false)
  const [editedNotes, setEditedNotes] = useState(student.notes ?? '')
  const [isSaving, setIsSaving] = useState(false)
  const [isHiddenForTransition, setIsHiddenForTransition] = useState(false)

  const modalRef = useRef<HTMLDivElement>(null)
  const textareaRef = useRef<HTMLTextAreaElement>(null)

  // ========== Use shared student actions hook ==========
  const studentActionData = buildStudentActionData(student)
  const { actions, handlers, modals } = useStudentActions(studentActionData, {
    // Session observer is rendered at parent level to avoid z-index issues
    // Close this modal first so the observer modal appears on top
    onObserveSession:
      onObserveSession && student.activity?.sessionId
        ? () => {
            onClose()
            onObserveSession(student.activity!.sessionId!)
          }
        : undefined,
  })

  // ========== Additional data for Overview tab ==========
  const { data: curriculumData } = usePlayerCurriculumQuery(student.id)
  const { data: sessionModeData } = useSessionMode(student.id)
  const sessionMode = sessionModeData?.sessionMode ?? null
  const updatePlayer = useUpdatePlayer() // For notes only

  // ========== Stakeholder data for Relationships tab ==========
  const { data: stakeholdersData } = useStudentStakeholders(student.id)
  const viewerRelationship = stakeholdersData?.viewerRelationship ?? null
  const stakeholders = stakeholdersData?.stakeholders ?? null

  // Count other stakeholders for the summary line
  const otherStakeholders = useMemo(() => {
    if (!stakeholders) return undefined
    const otherParents = stakeholders.parents.filter((p) => !p.isMe).length
    const teacherCount = stakeholders.enrolledClassrooms.length
    if (otherParents === 0 && teacherCount === 0) return undefined
    return { parents: otherParents, teachers: teacherCount }
  }, [stakeholders])

  // ========== Derived data ==========
  const relationship: StudentRelationship | null = student.relationship ?? null
  const activity: StudentActivity | null = student.activity ?? null
  const intervention = student.intervention ?? null

  const currentLevel = curriculumData?.curriculum?.currentLevel ?? null
  const masteryPercent = curriculumData?.skills
    ? calculateMasteryPercent(curriculumData.skills)
    : null
  const lastPracticedAt = curriculumData?.recentSessions?.[0]?.startedAt ?? null

  // Determine if Overview tab has content
  const hasOverviewContent = !!(
    currentLevel ||
    masteryPercent !== null ||
    intervention ||
    activity?.status === 'practicing' ||
    relationship?.isPresent
  )

  // Default tab based on content
  const defaultTab: TabId = hasOverviewContent ? 'overview' : 'notes'

  // ========== Mini Banner Handlers ==========

  const handleBannerStartPractice = useCallback(() => {
    // Navigate to dashboard with startPractice param to open the modal there
    // This ensures all required data (avgSecondsPerProblem, problemHistory, etc.) is available
    onClose()
    router.push(`/practice/${student.id}/dashboard?startPractice=true`)
  }, [onClose, router, student.id])

  const handleBannerResumePractice = useCallback(() => {
    // Navigate to the active practice session
    onClose()
    router.push(`/practice/${student.id}`)
  }, [onClose, router, student.id])

  // ========== Effects ==========

  // Reset state when modal opens/closes or student changes
  useEffect(() => {
    if (isOpen) {
      setEditedNotes(student.notes ?? '')
      setIsEditing(false)
      setActiveTab(defaultTab)
      setIsHiddenForTransition(false)
    }
  }, [isOpen, student.id, student.notes, defaultTab])

  // Focus textarea when entering edit mode
  useEffect(() => {
    if (isEditing && textareaRef.current) {
      textareaRef.current.focus()
    }
  }, [isEditing])

  // Handle escape key
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === 'Escape') {
        if (isEditing) {
          setIsEditing(false)
          setEditedNotes(student.notes ?? '')
        } else {
          onClose()
        }
      }
    }
    if (isOpen) {
      window.addEventListener('keydown', handleKeyDown)
      return () => window.removeEventListener('keydown', handleKeyDown)
    }
  }, [isOpen, isEditing, student.notes, onClose])

  // ========== Animation ==========
  const wasOpenRef = useRef(false)
  const isOpening = !wasOpenRef.current && isOpen

  useEffect(() => {
    wasOpenRef.current = isOpen
  }, [isOpen])

  const windowWidth = typeof window !== 'undefined' ? window.innerWidth : 800
  const windowHeight = typeof window !== 'undefined' ? window.innerHeight : 600

  // Responsive modal dimensions
  const modalWidth = Math.min(420, windowWidth - 32)
  const modalHeight = Math.min(400, windowHeight - 100) // Leave room for virtual keyboard on mobile
  const targetX = (windowWidth - modalWidth) / 2
  const targetY = (windowHeight - modalHeight) / 2

  const sourceX = sourceBounds?.left ?? targetX
  const sourceY = sourceBounds?.top ?? targetY
  const sourceWidth = sourceBounds?.width ?? modalWidth
  const sourceHeight = sourceBounds?.height ?? modalHeight

  const springProps = useSpring({
    from: {
      x: sourceX,
      y: sourceY,
      width: sourceWidth,
      height: sourceHeight,
      opacity: 0,
      scale: 0.95,
    },
    to: {
      x: isOpen ? targetX : sourceX,
      y: isOpen ? targetY : sourceY,
      width: isOpen ? modalWidth : sourceWidth,
      height: isOpen ? modalHeight : sourceHeight,
      opacity: isOpen ? 1 : 0,
      scale: isOpen ? 1 : 0.95,
    },
    reset: isOpening,
    config: { tension: 300, friction: 30 },
  })

  const backdropSpring = useSpring({
    opacity: isOpen ? 1 : 0,
    config: { tension: 300, friction: 30 },
  })

  // ========== Handlers (notes only - actions use hook) ==========
  const handleSaveNotes = useCallback(async () => {
    setIsSaving(true)
    try {
      await updatePlayer.mutateAsync({
        id: student.id,
        updates: { notes: editedNotes || null },
      })
      setIsEditing(false)
    } catch (error) {
      console.error('Failed to save notes:', error)
    } finally {
      setIsSaving(false)
    }
  }, [student.id, editedNotes, updatePlayer])

  // Wrap startPractice to also close modal
  const handleStartPractice = useCallback(() => {
    handlers.startPractice()
    onClose()
  }, [handlers, onClose])

  // Handle fullscreen transition to dashboard
  const handleFullscreen = useCallback(() => {
    if (!modalRef.current) return

    const bounds = modalRef.current.getBoundingClientRect()

    // Hide the modal instantly (no close animation) - overlay will take over
    setIsHiddenForTransition(true)

    startTransition({
      studentId: student.id,
      studentName: student.name,
      studentEmoji: student.emoji,
      studentColor: student.color,
      originBounds: {
        left: bounds.left,
        top: bounds.top,
        width: bounds.width,
        height: bounds.height,
      },
    })
    // Note: Don't call onClose() - it triggers the shrink animation
    // The modal will be unmounted when we navigate away
  }, [student, startTransition])

  // ========== Render ==========
  return (
    <>
      {/* Backdrop - fades out when doing fullscreen transition */}
      <animated.div
        data-component="notes-modal-backdrop"
        onClick={onClose}
        style={{
          opacity: isHiddenForTransition ? 0 : backdropSpring.opacity,
          pointerEvents: isOpen && !isHiddenForTransition ? 'auto' : 'none',
          transition: isHiddenForTransition ? 'opacity 150ms ease-out' : undefined,
        }}
        className={css({
          position: 'fixed',
          inset: 0,
          backgroundColor: 'rgba(0, 0, 0, 0.6)',
          zIndex: Z_INDEX.MODAL_BACKDROP,
        })}
      />

      {/* Modal - fades out when doing fullscreen transition (cross-fade with overlay) */}
      <animated.div
        ref={modalRef}
        data-component="notes-modal"
        style={{
          position: 'fixed',
          left: springProps.x,
          top: springProps.y,
          width: springProps.width,
          height: springProps.height,
          opacity: isHiddenForTransition ? 0 : springProps.opacity,
          transform: springProps.scale.to((s) => `scale(${s})`),
          transformOrigin: 'center center',
          zIndex: Z_INDEX.MODAL,
          pointerEvents: isOpen && !isHiddenForTransition ? 'auto' : 'none',
          transition: isHiddenForTransition ? 'opacity 150ms ease-out' : undefined,
        }}
        className={css({
          display: 'flex',
          flexDirection: 'column',
          borderRadius: '16px',
          overflow: 'hidden',
          boxShadow: '0 25px 50px -12px rgba(0, 0, 0, 0.5)',
          backgroundColor: isDark ? 'gray.800' : 'white',
        })}
      >
        {/* Header */}
        <div
          data-section="header"
          className={css({
            padding: '16px',
            display: 'flex',
            alignItems: 'center',
            gap: '12px',
            borderBottom: '1px solid',
            borderColor: isDark ? 'gray.700' : 'gray.200',
          })}
          style={{ backgroundColor: student.color }}
        >
          {/* Avatar */}
          <div
            className={css({
              width: '48px',
              height: '48px',
              borderRadius: '12px',
              backgroundColor: 'rgba(255, 255, 255, 0.3)',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              fontSize: '1.75rem',
              flexShrink: 0,
            })}
          >
            {student.emoji}
          </div>

          {/* Name and relationship summary */}
          <div className={css({ flex: 1, minWidth: 0 })}>
            <h2
              className={css({
                fontSize: '1.25rem',
                fontWeight: 'bold',
                color: 'white',
                textShadow: '0 1px 2px rgba(0, 0, 0, 0.2)',
                whiteSpace: 'nowrap',
                overflow: 'hidden',
                textOverflow: 'ellipsis',
              })}
            >
              {student.name}
            </h2>
            {/* Relationship summary line */}
            {viewerRelationship && viewerRelationship.type !== 'none' && (
              <div
                className={css({
                  marginTop: '2px',
                  opacity: 0.9,
                })}
              >
                <RelationshipSummary
                  type={viewerRelationship.type}
                  classroomName={viewerRelationship.classroomName}
                  otherStakeholders={otherStakeholders}
                  className={css({ color: 'rgba(255, 255, 255, 0.9)' })}
                />
              </div>
            )}
          </div>

          {/* Fullscreen button - expands to dashboard */}
          <button
            type="button"
            data-action="fullscreen"
            onClick={handleFullscreen}
            title="Open full dashboard"
            className={css({
              width: '32px',
              height: '32px',
              borderRadius: '8px',
              border: 'none',
              backgroundColor: 'rgba(255, 255, 255, 0.2)',
              color: 'white',
              fontSize: '1rem',
              cursor: 'pointer',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              flexShrink: 0,
              _hover: { backgroundColor: 'rgba(255, 255, 255, 0.3)' },
            })}
          >

          </button>

          {/* Overflow menu - uses shared actions hook */}
          <DropdownMenu.Root>
            <DropdownMenu.Trigger asChild>
              <button
                type="button"
                data-action="overflow-menu"
                className={css({
                  width: '32px',
                  height: '32px',
                  borderRadius: '8px',
                  border: 'none',
                  backgroundColor: 'rgba(255, 255, 255, 0.2)',
                  color: 'white',
                  fontSize: '1rem',
                  cursor: 'pointer',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  flexShrink: 0,
                  _hover: { backgroundColor: 'rgba(255, 255, 255, 0.3)' },
                })}
              >

              </button>
            </DropdownMenu.Trigger>

            <DropdownMenu.Portal>
              <DropdownMenu.Content
                className={css({
                  minWidth: '180px',
                  backgroundColor: isDark ? 'gray.800' : 'white',
                  borderRadius: '8px',
                  padding: '4px',
                  boxShadow: '0 10px 38px -10px rgba(0,0,0,0.35)',
                  border: '1px solid',
                  borderColor: isDark ? 'gray.700' : 'gray.200',
                  zIndex: Z_INDEX.TOOLTIP,
                })}
                sideOffset={5}
              >
                {/* Primary actions */}
                {actions.startPractice && (
                  <DropdownMenu.Item
                    className={menuItemStyle(isDark)}
                    onSelect={handleStartPractice}
                  >
                    <span>{ACTION_DEFINITIONS.startPractice.icon}</span>
                    <span>{ACTION_DEFINITIONS.startPractice.label}</span>
                  </DropdownMenu.Item>
                )}

                {actions.watchSession && (
                  <DropdownMenu.Item
                    className={menuItemStyle(isDark)}
                    onSelect={handlers.watchSession}
                  >
                    <span>{ACTION_DEFINITIONS.watchSession.icon}</span>
                    <span>{ACTION_DEFINITIONS.watchSession.label}</span>
                  </DropdownMenu.Item>
                )}

                {actions.enterClassroom && (
                  <DropdownMenu.Item
                    className={menuItemStyle(isDark)}
                    onSelect={handlers.enterClassroom}
                  >
                    <span>{ACTION_DEFINITIONS.enterClassroom.icon}</span>
                    <span>{ACTION_DEFINITIONS.enterClassroom.label}</span>
                  </DropdownMenu.Item>
                )}

                {actions.leaveClassroom && (
                  <DropdownMenu.Item
                    className={menuItemStyle(isDark)}
                    onSelect={handlers.leaveClassroom}
                  >
                    <span>{ACTION_DEFINITIONS.leaveClassroom.icon}</span>
                    <span>{ACTION_DEFINITIONS.leaveClassroom.label}</span>
                  </DropdownMenu.Item>
                )}

                {actions.promptToEnter && (
                  <DropdownMenu.Item
                    className={menuItemStyle(isDark)}
                    onSelect={handlers.promptToEnter}
                  >
                    <span>{ACTION_DEFINITIONS.promptToEnter.icon}</span>
                    <span>{ACTION_DEFINITIONS.promptToEnter.label}</span>
                  </DropdownMenu.Item>
                )}

                <DropdownMenu.Separator className={separatorStyle(isDark)} />

                {/* Management actions */}
                {actions.archive && (
                  <DropdownMenu.Item
                    className={menuItemStyle(isDark)}
                    onSelect={handlers.toggleArchive}
                  >
                    <span>{ACTION_DEFINITIONS.archive.icon}</span>
                    <span>{ACTION_DEFINITIONS.archive.label}</span>
                  </DropdownMenu.Item>
                )}

                {actions.unarchive && (
                  <DropdownMenu.Item
                    className={menuItemStyle(isDark)}
                    onSelect={handlers.toggleArchive}
                  >
                    <span>{ACTION_DEFINITIONS.unarchive.icon}</span>
                    <span>{ACTION_DEFINITIONS.unarchive.label}</span>
                  </DropdownMenu.Item>
                )}

                {actions.shareAccess && (
                  <DropdownMenu.Item
                    className={menuItemStyle(isDark)}
                    onSelect={handlers.openShareAccess}
                  >
                    <span>{ACTION_DEFINITIONS.shareAccess.icon}</span>
                    <span>{ACTION_DEFINITIONS.shareAccess.label}</span>
                  </DropdownMenu.Item>
                )}

                {actions.enrollInClassroom && (
                  <DropdownMenu.Item
                    className={menuItemStyle(isDark)}
                    onSelect={handlers.openEnrollModal}
                  >
                    <span>{ACTION_DEFINITIONS.enrollInClassroom.icon}</span>
                    <span>{ACTION_DEFINITIONS.enrollInClassroom.label}</span>
                  </DropdownMenu.Item>
                )}
              </DropdownMenu.Content>
            </DropdownMenu.Portal>
          </DropdownMenu.Root>

          {/* Close button */}
          <button
            type="button"
            data-action="close"
            onClick={onClose}
            className={css({
              width: '32px',
              height: '32px',
              borderRadius: '8px',
              border: 'none',
              backgroundColor: 'rgba(255, 255, 255, 0.2)',
              color: 'white',
              fontSize: '1.25rem',
              cursor: 'pointer',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              flexShrink: 0,
              _hover: { backgroundColor: 'rgba(255, 255, 255, 0.3)' },
            })}
          >
            ×
          </button>
        </div>

        {/* Mini Start Practice Banner - shows session mode or active session */}
        <MiniStartPracticeBanner
          sessionMode={sessionMode ?? null}
          activity={activity}
          onStartPractice={handleBannerStartPractice}
          onResumePractice={handleBannerResumePractice}
        />

        {/* Tab bar - show if Overview has content or if we have stakeholder data */}
        {(hasOverviewContent || stakeholdersData) && (
          <div
            data-section="tabs"
            className={css({
              display: 'flex',
              borderBottom: '1px solid',
              borderColor: isDark ? 'gray.700' : 'gray.200',
              backgroundColor: isDark ? 'gray.800' : 'gray.50',
            })}
          >
            {hasOverviewContent && (
              <TabButton
                label="Overview"
                isActive={activeTab === 'overview'}
                onClick={() => setActiveTab('overview')}
                isDark={isDark}
              />
            )}
            <TabButton
              label="Notes"
              isActive={activeTab === 'notes'}
              onClick={() => setActiveTab('notes')}
              isDark={isDark}
            />
            <TabButton
              label="Relationships"
              isActive={activeTab === 'relationships'}
              onClick={() => setActiveTab('relationships')}
              isDark={isDark}
            />
          </div>
        )}

        {/* Tab content */}
        <div
          data-section="content"
          className={css({
            flex: 1,
            overflow: 'hidden',
            display: 'flex',
            flexDirection: 'column',
            minHeight: 0,
          })}
        >
          {activeTab === 'overview' && hasOverviewContent ? (
            <OverviewTab
              currentLevel={currentLevel}
              masteryPercent={masteryPercent}
              lastPracticedAt={lastPracticedAt}
              intervention={intervention}
              relationship={relationship}
              activity={activity}
              isDark={isDark}
            />
          ) : activeTab === 'relationships' ? (
            <RelationshipsTab playerId={student.id} playerName={student.name} editable />
          ) : (
            <NotesTab
              notes={student.notes ?? null}
              isEditing={isEditing}
              editedNotes={editedNotes}
              isSaving={isSaving}
              textareaRef={textareaRef}
              onEditedNotesChange={setEditedNotes}
              onStartEditing={() => setIsEditing(true)}
              onCancel={() => {
                setIsEditing(false)
                setEditedNotes(student.notes ?? '')
              }}
              onSave={handleSaveNotes}
              isDark={isDark}
            />
          )}
        </div>
      </animated.div>

      {/* Sub-modals - managed by shared hook */}
      <FamilyCodeDisplay
        playerId={student.id}
        playerName={student.name}
        isOpen={modals.shareAccess.isOpen}
        onClose={modals.shareAccess.close}
      />

      <EnrollChildModal
        isOpen={modals.enroll.isOpen}
        onClose={modals.enroll.close}
        playerId={student.id}
        playerName={student.name}
      />
    </>
  )
}

// ============================================================================
// Tab Button Component
// ============================================================================

interface TabButtonProps {
  label: string
  isActive: boolean
  onClick: () => void
  isDark: boolean
}

function TabButton({ label, isActive, onClick, isDark }: TabButtonProps) {
  return (
    <button
      type="button"
      onClick={onClick}
      className={css({
        flex: 1,
        padding: '12px 16px',
        border: 'none',
        backgroundColor: 'transparent',
        color: isActive ? (isDark ? 'blue.400' : 'blue.600') : isDark ? 'gray.400' : 'gray.600',
        fontSize: '0.875rem',
        fontWeight: isActive ? 'semibold' : 'normal',
        cursor: 'pointer',
        borderBottom: '2px solid',
        borderColor: isActive ? (isDark ? 'blue.400' : 'blue.600') : 'transparent',
        marginBottom: '-1px',
        transition: 'all 0.15s ease',
        _hover: {
          color: isDark ? 'blue.300' : 'blue.500',
        },
      })}
    >
      {label}
    </button>
  )
}

// ============================================================================
// Overview Tab Component
// ============================================================================

interface OverviewTabProps {
  currentLevel: number | null
  masteryPercent: number | null
  lastPracticedAt: Date | string | null
  intervention: UnifiedStudent['intervention'] | null
  relationship: StudentRelationship | null
  activity: StudentActivity | null
  isDark: boolean
}

function OverviewTab({
  currentLevel,
  masteryPercent,
  lastPracticedAt,
  intervention,
  relationship,
  activity,
  isDark,
}: OverviewTabProps) {
  const hasStats = currentLevel !== null || masteryPercent !== null

  return (
    <div
      className={css({
        flex: 1,
        padding: '16px',
        display: 'flex',
        flexDirection: 'column',
        gap: '16px',
        overflow: 'auto',
      })}
    >
      {/* Status badges */}
      {(activity?.status === 'practicing' || relationship?.isPresent) && (
        <div
          data-element="status-badges"
          className={css({
            display: 'flex',
            flexWrap: 'wrap',
            gap: '8px',
          })}
        >
          {activity?.status === 'practicing' && (
            <span
              className={css({
                display: 'inline-flex',
                alignItems: 'center',
                gap: '4px',
                padding: '4px 10px',
                borderRadius: '12px',
                fontSize: '0.75rem',
                fontWeight: 'medium',
                bg: isDark ? 'blue.900' : 'blue.100',
                color: isDark ? 'blue.300' : 'blue.700',
              })}
            >
              📝 Practicing
            </span>
          )}
          {relationship?.isPresent && activity?.status !== 'practicing' && (
            <span
              className={css({
                display: 'inline-flex',
                alignItems: 'center',
                gap: '4px',
                padding: '4px 10px',
                borderRadius: '12px',
                fontSize: '0.75rem',
                fontWeight: 'medium',
                bg: isDark ? 'green.900' : 'green.100',
                color: isDark ? 'green.300' : 'green.700',
              })}
            >
              🟢 In Classroom
            </span>
          )}
        </div>
      )}

      {/* Stats grid */}
      {hasStats && (
        <div
          data-element="stats-grid"
          className={css({
            display: 'grid',
            gridTemplateColumns: 'repeat(3, 1fr)',
            gap: '12px',
          })}
        >
          <StatBox label="Level" value={currentLevel?.toString() ?? '—'} isDark={isDark} />
          <StatBox
            label="Mastery"
            value={masteryPercent !== null ? `${masteryPercent}%` : '—'}
            isDark={isDark}
          />
          <StatBox
            label="Last Practice"
            value={formatLastPracticed(lastPracticedAt)}
            isDark={isDark}
          />
        </div>
      )}

      {/* Intervention alert */}
      {intervention && (
        <div
          data-element="intervention"
          className={css({
            padding: '12px',
            borderRadius: '8px',
            backgroundColor:
              intervention.severity === 'high'
                ? isDark
                  ? 'red.900/40'
                  : 'red.50'
                : intervention.severity === 'medium'
                  ? isDark
                    ? 'orange.900/40'
                    : 'orange.50'
                  : isDark
                    ? 'blue.900/40'
                    : 'blue.50',
            border: '1px solid',
            borderColor:
              intervention.severity === 'high'
                ? isDark
                  ? 'red.800'
                  : 'red.200'
                : intervention.severity === 'medium'
                  ? isDark
                    ? 'orange.800'
                    : 'orange.200'
                  : isDark
                    ? 'blue.800'
                    : 'blue.200',
            display: 'flex',
            alignItems: 'flex-start',
            gap: '10px',
          })}
        >
          <span className={css({ fontSize: '1.25rem' })}>{intervention.icon}</span>
          <div>
            <div
              className={css({
                fontSize: '0.8125rem',
                fontWeight: 'semibold',
                color:
                  intervention.severity === 'high'
                    ? isDark
                      ? 'red.300'
                      : 'red.700'
                    : intervention.severity === 'medium'
                      ? isDark
                        ? 'orange.300'
                        : 'orange.700'
                      : isDark
                        ? 'blue.300'
                        : 'blue.700',
              })}
            >
              {intervention.severity === 'high'
                ? 'Needs Attention'
                : intervention.severity === 'medium'
                  ? 'Suggestion'
                  : 'Note'}
            </div>
            <div
              className={css({
                fontSize: '0.8125rem',
                color: isDark ? 'gray.300' : 'gray.600',
                marginTop: '2px',
              })}
            >
              {intervention.message}
            </div>
          </div>
        </div>
      )}
    </div>
  )
}

// ============================================================================
// Stats Box Component
// ============================================================================

interface StatBoxProps {
  label: string
  value: string
  isDark: boolean
}

function StatBox({ label, value, isDark }: StatBoxProps) {
  return (
    <div
      className={css({
        padding: '12px',
        borderRadius: '8px',
        backgroundColor: isDark ? 'gray.700' : 'gray.100',
        textAlign: 'center',
      })}
    >
      <div
        className={css({
          fontSize: '1.25rem',
          fontWeight: 'bold',
          color: isDark ? 'gray.100' : 'gray.800',
        })}
      >
        {value}
      </div>
      <div
        className={css({
          fontSize: '0.6875rem',
          color: isDark ? 'gray.400' : 'gray.500',
          marginTop: '2px',
        })}
      >
        {label}
      </div>
    </div>
  )
}

// ============================================================================
// Notes Tab Component
// ============================================================================

interface NotesTabProps {
  notes: string | null
  isEditing: boolean
  editedNotes: string
  isSaving: boolean
  textareaRef: React.RefObject<HTMLTextAreaElement>
  onEditedNotesChange: (notes: string) => void
  onStartEditing: () => void
  onCancel: () => void
  onSave: () => void
  isDark: boolean
}

function NotesTab({
  notes,
  isEditing,
  editedNotes,
  isSaving,
  textareaRef,
  onEditedNotesChange,
  onStartEditing,
  onCancel,
  onSave,
  isDark,
}: NotesTabProps) {
  return (
    <div
      className={css({
        flex: 1,
        display: 'flex',
        flexDirection: 'column',
        padding: '16px',
        gap: '12px',
        overflow: 'hidden',
        minHeight: 0,
      })}
    >
      {isEditing ? (
        <>
          <textarea
            ref={textareaRef}
            value={editedNotes}
            onChange={(e) => onEditedNotesChange(e.target.value)}
            placeholder="Add notes about this student..."
            className={css({
              flex: 1,
              width: '100%',
              padding: '12px',
              borderRadius: '8px',
              border: '1px solid',
              borderColor: isDark ? 'gray.600' : 'gray.300',
              backgroundColor: isDark ? 'gray.700' : 'white',
              color: isDark ? 'gray.100' : 'gray.900',
              fontSize: '0.875rem',
              lineHeight: '1.5',
              resize: 'none',
              fontFamily: 'inherit',
              _focus: {
                outline: 'none',
                borderColor: isDark ? 'blue.500' : 'blue.400',
              },
              _placeholder: {
                color: isDark ? 'gray.500' : 'gray.400',
              },
            })}
          />
          <div
            className={css({
              display: 'flex',
              gap: '8px',
              justifyContent: 'flex-end',
            })}
          >
            <button
              type="button"
              onClick={onCancel}
              disabled={isSaving}
              className={css({
                padding: '8px 16px',
                borderRadius: '6px',
                border: '1px solid',
                borderColor: isDark ? 'gray.600' : 'gray.300',
                backgroundColor: 'transparent',
                color: isDark ? 'gray.300' : 'gray.600',
                fontSize: '0.875rem',
                cursor: 'pointer',
                _hover: { backgroundColor: isDark ? 'gray.700' : 'gray.100' },
                _disabled: { opacity: 0.5, cursor: 'not-allowed' },
              })}
            >
              Cancel
            </button>
            <button
              type="button"
              onClick={onSave}
              disabled={isSaving}
              className={css({
                padding: '8px 16px',
                borderRadius: '6px',
                border: 'none',
                backgroundColor: isDark ? 'green.600' : 'green.500',
                color: 'white',
                fontSize: '0.875rem',
                fontWeight: 'medium',
                cursor: 'pointer',
                _hover: { backgroundColor: isDark ? 'green.500' : 'green.600' },
                _disabled: { opacity: 0.5, cursor: 'not-allowed' },
              })}
            >
              {isSaving ? 'Saving...' : 'Save'}
            </button>
          </div>
        </>
      ) : (
        <>
          <div
            className={css({
              flex: 1,
              padding: '12px',
              borderRadius: '8px',
              backgroundColor: isDark ? 'gray.700' : 'gray.100',
              overflow: 'auto',
              minHeight: 0,
            })}
          >
            {notes ? (
              <p
                className={css({
                  fontSize: '0.875rem',
                  lineHeight: '1.6',
                  color: isDark ? 'gray.200' : 'gray.700',
                  whiteSpace: 'pre-wrap',
                  margin: 0,
                })}
              >
                {notes}
              </p>
            ) : (
              <p
                className={css({
                  fontSize: '0.875rem',
                  color: isDark ? 'gray.500' : 'gray.400',
                  fontStyle: 'italic',
                  margin: 0,
                })}
              >
                No notes yet
              </p>
            )}
          </div>
          <button
            type="button"
            onClick={onStartEditing}
            className={css({
              alignSelf: 'flex-end',
              padding: '8px 16px',
              borderRadius: '6px',
              border: 'none',
              backgroundColor: isDark ? 'blue.600' : 'blue.500',
              color: 'white',
              fontSize: '0.875rem',
              fontWeight: 'medium',
              cursor: 'pointer',
              _hover: { backgroundColor: isDark ? 'blue.500' : 'blue.600' },
            })}
          >
            {notes ? 'Edit Notes' : 'Add Notes'}
          </button>
        </>
      )}
    </div>
  )
}

// ============================================================================
// Relationships Tab Component
// ============================================================================

interface RelationshipsTabProps {
  playerId: string
  playerName: string
  editable: boolean
}

function RelationshipsTab({ playerId, playerName, editable }: RelationshipsTabProps) {
  return (
    <div
      className={css({
        flex: 1,
        padding: '16px',
        overflow: 'auto',
      })}
    >
      <RelationshipCard playerId={playerId} playerName={playerName} editable={editable} compact />
    </div>
  )
}

// ============================================================================
// Style Helper Functions
// ============================================================================

function menuItemStyle(isDark: boolean) {
  return css({
    display: 'flex',
    alignItems: 'center',
    gap: '8px',
    padding: '8px 12px',
    borderRadius: '4px',
    fontSize: '0.8125rem',
    cursor: 'pointer',
    outline: 'none',
    color: isDark ? 'gray.200' : 'gray.700',
    _hover: { backgroundColor: isDark ? 'gray.700' : 'gray.100' },
    _focus: { backgroundColor: isDark ? 'gray.700' : 'gray.100' },
  })
}

function separatorStyle(isDark: boolean) {
  return css({
    height: '1px',
    backgroundColor: isDark ? 'gray.700' : 'gray.200',
    margin: '4px 0',
  })
}