All files / web/src/app/practice AddStudentModal.tsx

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

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

import Link from 'next/link'
import { useCallback, useEffect, useState } from 'react'
import { EmojiPicker } from '@/components/EmojiPicker'
import { LinkChildForm } from '@/components/family'
import { PLAYER_EMOJIS } from '@/constants/playerEmojis'
import { useDirectEnrollStudent } from '@/hooks/useClassroom'
import { ApiError, useCreatePlayer } from '@/hooks/useUserPlayers'
import { css } from '../../../styled-system/css'

// Available colors for student avatars
const AVAILABLE_COLORS = [
  '#FFB3BA', // light pink
  '#FFDFBA', // light orange
  '#FFFFBA', // light yellow
  '#BAFFC9', // light green
  '#BAE1FF', // light blue
  '#DCC6E0', // light purple
  '#F0E68C', // khaki
  '#98D8C8', // mint
  '#F7DC6F', // gold
  '#BB8FCE', // orchid
  '#85C1E9', // sky blue
  '#F8B500', // amber
]

interface AddStudentModalProps {
  isOpen: boolean
  onClose: () => void
  isDark: boolean
  /** If provided, student will be auto-enrolled in this classroom */
  classroomId?: string
  /** Name of the classroom for display */
  classroomName?: string
}

/**
 * Modal for adding a new student
 * Uses React Query mutation for proper cache management
 */
export function AddStudentModal({
  isOpen,
  onClose,
  isDark,
  classroomId,
  classroomName,
}: AddStudentModalProps) {
  // Form state
  const [formName, setFormName] = useState('')
  const [formEmoji, setFormEmoji] = useState(PLAYER_EMOJIS[0])
  const [formColor, setFormColor] = useState(AVAILABLE_COLORS[0])
  const [showEmojiPicker, setShowEmojiPicker] = useState(false)
  const [showLinkForm, setShowLinkForm] = useState(false)

  // React Query mutations
  const createPlayer = useCreatePlayer()
  const directEnroll = useDirectEnrollStudent()

  // Reset form and pick random emoji/color when opened
  useEffect(() => {
    if (isOpen) {
      setFormName('')
      setFormEmoji(PLAYER_EMOJIS[Math.floor(Math.random() * PLAYER_EMOJIS.length)])
      setFormColor(AVAILABLE_COLORS[Math.floor(Math.random() * AVAILABLE_COLORS.length)])
      setShowEmojiPicker(false)
      setShowLinkForm(false)
    }
  }, [isOpen])

  // Handle form submission
  const handleSubmit = useCallback(() => {
    if (!formName.trim()) return

    createPlayer.mutate(
      {
        name: formName.trim(),
        emoji: formEmoji,
        color: formColor,
      },
      {
        onSuccess: (player) => {
          // If classroomId is provided, auto-enroll the new student
          if (classroomId && player) {
            directEnroll.mutate(
              { classroomId, playerId: player.id },
              {
                onSettled: () => {
                  onClose()
                },
              }
            )
          } else {
            onClose()
          }
        },
      }
    )
  }, [formName, formEmoji, formColor, createPlayer, classroomId, directEnroll, onClose])

  const isPending = createPlayer.isPending || directEnroll.isPending

  // Handle keyboard events
  const handleKeyDown = useCallback(
    (e: React.KeyboardEvent) => {
      if (e.key === 'Escape') {
        if (showEmojiPicker) {
          setShowEmojiPicker(false)
        } else {
          onClose()
        }
      } else if (e.key === 'Enter' && formName.trim() && !isPending && !showEmojiPicker) {
        handleSubmit()
      }
    },
    [formName, isPending, handleSubmit, onClose, showEmojiPicker]
  )

  if (!isOpen) return null

  // Show the shared EmojiPicker as a full-screen overlay when picking emoji
  if (showEmojiPicker) {
    return (
      <EmojiPicker
        currentEmoji={formEmoji}
        onEmojiSelect={(emoji) => {
          setFormEmoji(emoji)
          setShowEmojiPicker(false)
        }}
        onClose={() => setShowEmojiPicker(false)}
        title="Choose Avatar"
        accentColor="green"
        isDark={isDark}
      />
    )
  }

  return (
    <div
      data-component="add-student-modal"
      role="dialog"
      aria-modal="true"
      aria-labelledby="add-student-title"
      onKeyDown={handleKeyDown}
      className={css({
        position: 'fixed',
        inset: 0,
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        backgroundColor: 'rgba(0, 0, 0, 0.5)',
        zIndex: 1000,
        padding: '1rem',
      })}
    >
      {/* Backdrop click to close */}
      <button
        type="button"
        data-element="modal-backdrop"
        onClick={onClose}
        className={css({
          position: 'absolute',
          inset: 0,
          background: 'none',
          border: 'none',
          cursor: 'pointer',
        })}
        aria-label="Close modal"
      />

      {/* Modal content */}
      <div
        data-element="modal-content"
        className={css({
          position: 'relative',
          width: '100%',
          maxWidth: '400px',
          maxHeight: '90vh',
          overflowY: 'auto',
          padding: '1.5rem',
          backgroundColor: isDark ? 'gray.800' : 'white',
          borderRadius: '16px',
          boxShadow: 'lg',
        })}
      >
        {/* Header */}
        <div
          className={css({
            display: 'flex',
            justifyContent: 'space-between',
            alignItems: 'center',
            marginBottom: classroomId ? '0.75rem' : '1.5rem',
          })}
        >
          <h2
            id="add-student-title"
            className={css({
              fontSize: '1.25rem',
              fontWeight: 'bold',
              color: isDark ? 'gray.100' : 'gray.800',
            })}
          >
            {classroomId ? 'Add Student to Classroom' : 'Add New Student'}
          </h2>
          <button
            type="button"
            data-action="close-modal"
            onClick={onClose}
            className={css({
              width: '32px',
              height: '32px',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              fontSize: '1.25rem',
              color: isDark ? 'gray.400' : 'gray.500',
              backgroundColor: 'transparent',
              border: 'none',
              borderRadius: '6px',
              cursor: 'pointer',
              _hover: {
                backgroundColor: isDark ? 'gray.700' : 'gray.100',
              },
            })}
            aria-label="Close"
          >
            ×
          </button>
        </div>

        {/* Classroom notice - shown when adding to a classroom */}
        {classroomId && (
          <div
            data-element="classroom-enrollment-notice"
            className={css({
              display: 'flex',
              alignItems: 'center',
              gap: '8px',
              padding: '10px 12px',
              marginBottom: '1rem',
              backgroundColor: isDark ? 'blue.900/50' : 'blue.50',
              border: '1px solid',
              borderColor: isDark ? 'blue.700' : 'blue.200',
              borderRadius: '8px',
            })}
          >
            <span className={css({ fontSize: '16px', flexShrink: 0 })}>📚</span>
            <p
              className={css({
                fontSize: '0.875rem',
                color: isDark ? 'blue.200' : 'blue.700',
                lineHeight: '1.4',
              })}
            >
              This student will be automatically enrolled in{' '}
              <strong>{classroomName || 'your classroom'}</strong>.
            </p>
          </div>
        )}

        {/* Avatar Preview - clickable to open full picker */}
        <div
          className={css({
            display: 'flex',
            flexDirection: 'column',
            alignItems: 'center',
            gap: '8px',
            marginBottom: '1.5rem',
          })}
        >
          <button
            type="button"
            onClick={() => setShowEmojiPicker(true)}
            data-element="avatar-preview"
            className={css({
              width: '80px',
              height: '80px',
              borderRadius: '50%',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              fontSize: '2.5rem',
              boxShadow: 'md',
              border: '3px solid',
              borderColor: isDark ? 'gray.600' : 'gray.300',
              cursor: 'pointer',
              transition: 'all 0.15s',
              _hover: {
                borderColor: 'blue.500',
                transform: 'scale(1.05)',
              },
            })}
            style={{ backgroundColor: formColor }}
            title="Click to choose avatar"
          >
            {formEmoji}
          </button>
          <span
            className={css({
              fontSize: '0.75rem',
              color: isDark ? 'gray.500' : 'gray.400',
            })}
          >
            Tap to change avatar
          </span>
        </div>

        {/* Name input */}
        <div className={css({ marginBottom: '1.25rem' })}>
          <label
            htmlFor="new-student-name"
            className={css({
              display: 'block',
              fontSize: '0.875rem',
              fontWeight: 'bold',
              color: isDark ? 'gray.300' : 'gray.700',
              marginBottom: '0.5rem',
            })}
          >
            Name
          </label>
          <input
            id="new-student-name"
            type="text"
            value={formName}
            onChange={(e) => setFormName(e.target.value)}
            placeholder="Enter student name"
            // biome-ignore lint/a11y/noAutofocus: Modal just opened, focusing input is expected UX
            autoFocus
            className={css({
              width: '100%',
              padding: '0.75rem',
              fontSize: '1rem',
              borderRadius: '8px',
              border: '1px solid',
              borderColor: isDark ? 'gray.600' : 'gray.300',
              backgroundColor: isDark ? 'gray.700' : 'white',
              color: isDark ? 'gray.100' : 'gray.800',
              _focus: {
                outline: 'none',
                borderColor: 'blue.500',
                boxShadow: '0 0 0 2px rgba(59, 130, 246, 0.3)',
              },
            })}
          />
        </div>

        {/* Color selector */}
        <div className={css({ marginBottom: '1.5rem' })}>
          <label
            className={css({
              display: 'block',
              fontSize: '0.875rem',
              fontWeight: 'bold',
              color: isDark ? 'gray.300' : 'gray.700',
              marginBottom: '0.5rem',
            })}
          >
            Color
          </label>
          <div
            className={css({
              display: 'flex',
              flexWrap: 'wrap',
              gap: '0.5rem',
            })}
          >
            {AVAILABLE_COLORS.map((color) => (
              <button
                key={color}
                type="button"
                onClick={() => setFormColor(color)}
                className={css({
                  width: '36px',
                  height: '36px',
                  borderRadius: '50%',
                  border: '3px solid',
                  borderColor: formColor === color ? 'blue.500' : 'transparent',
                  cursor: 'pointer',
                  transition: 'all 0.15s',
                  _hover: {
                    transform: 'scale(1.1)',
                  },
                })}
                style={{ backgroundColor: color }}
              />
            ))}
          </div>
        </div>

        {/* Player limit error */}
        {createPlayer.error instanceof ApiError &&
          createPlayer.error.code === 'PRACTICE_STUDENT_LIMIT_REACHED' && (
            <div
              data-element="player-limit-error"
              className={css({
                padding: '0.75rem',
                marginBottom: '1rem',
                borderRadius: '8px',
                textAlign: 'center',
                backgroundColor: isDark ? 'rgba(251, 191, 36, 0.12)' : 'rgba(251, 191, 36, 0.08)',
                border: '1px solid',
                borderColor: isDark ? 'rgba(251, 191, 36, 0.25)' : 'rgba(251, 191, 36, 0.15)',
              })}
            >
              <p
                className={css({
                  fontSize: '0.875rem',
                  color: isDark ? '#fcd34d' : '#b45309',
                  marginBottom: '0.5rem',
                })}
              >
                Student limit reached
              </p>
              <p
                className={css({
                  fontSize: '0.75rem',
                  color: isDark ? '#d4d4d4' : '#525252',
                  marginBottom: '0.5rem',
                })}
              >
                Upgrade to Family for unlimited students.
              </p>
              <Link
                href="/pricing"
                data-action="upgrade-for-students"
                className={css({
                  display: 'inline-block',
                  padding: '0.375rem 0.75rem',
                  fontSize: '0.8125rem',
                  fontWeight: '600',
                  color: 'white',
                  backgroundColor: isDark ? '#7c3aed' : '#8b5cf6',
                  borderRadius: '6px',
                  textDecoration: 'none',
                  _hover: {
                    backgroundColor: isDark ? '#6d28d9' : '#7c3aed',
                  },
                })}
              >
                View Plans
              </Link>
            </div>
          )}

        {/* Form actions */}
        <div
          className={css({
            display: 'flex',
            gap: '0.75rem',
          })}
        >
          <button
            type="button"
            data-action="cancel"
            onClick={onClose}
            disabled={isPending}
            className={css({
              flex: 1,
              padding: '0.75rem',
              fontSize: '1rem',
              color: isDark ? 'gray.300' : 'gray.600',
              backgroundColor: isDark ? 'gray.700' : 'gray.200',
              borderRadius: '8px',
              border: 'none',
              cursor: 'pointer',
              _hover: {
                backgroundColor: isDark ? 'gray.600' : 'gray.300',
              },
              _disabled: {
                opacity: 0.5,
                cursor: 'not-allowed',
              },
            })}
          >
            Cancel
          </button>
          <button
            type="button"
            data-action="add-student"
            onClick={handleSubmit}
            disabled={isPending || !formName.trim()}
            className={css({
              flex: 2,
              padding: '0.75rem',
              fontSize: '1rem',
              fontWeight: 'bold',
              color: 'white',
              backgroundColor: isPending ? 'gray.400' : 'green.500',
              borderRadius: '8px',
              border: 'none',
              cursor: isPending ? 'not-allowed' : 'pointer',
              _hover: {
                backgroundColor: isPending ? 'gray.400' : 'green.600',
              },
              _disabled: {
                opacity: 0.5,
                cursor: 'not-allowed',
              },
            })}
          >
            {isPending
              ? classroomId
                ? 'Adding & Enrolling...'
                : 'Adding...'
              : classroomId
                ? 'Add & Enroll'
                : 'Add Student'}
          </button>
        </div>

        {/* Link existing child option - only show in parent mode (not classroom mode) */}
        {!classroomId && (
          <div
            className={css({
              marginTop: '1.5rem',
              paddingTop: '1.5rem',
              borderTop: '1px solid',
              borderColor: isDark ? 'gray.700' : 'gray.200',
              textAlign: 'center',
            })}
          >
            <p
              className={css({
                fontSize: '0.875rem',
                color: isDark ? 'gray.400' : 'gray.500',
                marginBottom: '0.5rem',
              })}
            >
              Have a family code from another parent?
            </p>
            <button
              type="button"
              onClick={() => setShowLinkForm(true)}
              data-action="show-link-form"
              className={css({
                padding: '8px 16px',
                fontSize: '0.875rem',
                color: isDark ? 'blue.400' : 'blue.600',
                backgroundColor: 'transparent',
                border: '1px solid',
                borderColor: isDark ? 'blue.700' : 'blue.300',
                borderRadius: '8px',
                cursor: 'pointer',
                transition: 'all 0.15s ease',
                _hover: {
                  backgroundColor: isDark ? 'blue.900/50' : 'blue.50',
                  borderColor: isDark ? 'blue.600' : 'blue.400',
                },
              })}
            >
              Link Existing Child
            </button>
          </div>
        )}
      </div>

      {/* Link Child Form Modal - only used in parent mode */}
      {!classroomId && (
        <LinkChildForm
          isOpen={showLinkForm}
          onClose={() => setShowLinkForm(false)}
          onSuccess={onClose}
        />
      )}
    </div>
  )
}