All files / web/src/components/debug SeedStudentsSection.tsx

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

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

import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import {
  AlertTriangle,
  ChevronDown,
  ChevronRight,
  Loader2,
  RefreshCw,
  Search,
  Share2,
} from 'lucide-react'
import { FamilyCodeDisplay } from '@/components/family/FamilyCodeDisplay'
import { useBackgroundTask } from '@/hooks/useBackgroundTask'
import {
  useSeedProfiles,
  useEmbeddingStatus,
  useSeededStudents,
  useSeedProfileSearch,
  useRegenerateEmbeddings,
  useSeedStudents,
} from '@/hooks/useDebugSeedStudents'
import type { ProfileInfo } from '@/lib/seed/types'
import { css } from '../../../styled-system/css'

interface ProfileGroup {
  id: string
  label: string
  description: string
  match: (p: ProfileInfo) => boolean
}

const PROFILE_GROUPS: ProfileGroup[] = [
  {
    id: 'mastery',
    label: 'Skill Mastery Levels',
    description: 'Students at different stages — from struggling to ready to advance',
    match: (p) => p.category === 'bkt',
  },
  {
    id: 'session-mode',
    label: 'Session Mode Triggers',
    description: 'Each triggers a specific session mode: remediation, progression, or maintenance',
    match: (p) => p.category === 'session',
  },
  {
    id: 'chart',
    label: 'Progress Chart',
    description: 'Different history sizes to test the skill progress chart rendering',
    match: (p) => p.tags.includes('chart-test'),
  },
  {
    id: 'data-edge',
    label: 'Data Robustness',
    description: 'Empty states, extreme data, stale skills, NaN handling',
    match: (p) => p.category === 'edge' && !p.tags.includes('chart-test'),
  },
]

interface StudentStatus {
  name: string
  status: 'pending' | 'seeding' | 'completed' | 'failed'
  playerId?: string
  classifications?: { weak: number; developing: number; strong: number }
  error?: string
  seededAt?: Date
}

function ProfileCard({
  profile,
  isDark,
  isSeeding,
  isSelected,
  isExpanded,
  studentStatus,
  similarity,
  onToggleSelect,
  onToggleExpand,
  onShareAccess,
}: {
  profile: ProfileInfo
  isDark: boolean
  isSeeding: boolean
  isSelected: boolean
  isExpanded: boolean
  studentStatus?: StudentStatus
  similarity?: number
  onToggleSelect: (name: string) => void
  onToggleExpand: (name: string) => void
  onShareAccess?: (playerId: string, name: string) => void
}) {
  return (
    <div
      data-element="profile-card"
      className={css({
        backgroundColor: isDark ? 'gray.800' : 'white',
        border: '1px solid',
        borderColor:
          studentStatus?.status === 'completed'
            ? isDark
              ? 'green.700'
              : 'green.300'
            : studentStatus?.status === 'failed'
              ? isDark
                ? 'red.700'
                : 'red.300'
              : isDark
                ? 'gray.700'
                : 'gray.200',
        borderRadius: '10px',
        padding: '10px 12px',
        transition: 'border-color 0.2s',
      })}
    >
      {/* Top row: checkbox, name, similarity badge, status */}
      <div
        className={css({
          display: 'flex',
          alignItems: 'center',
          gap: '10px',
        })}
      >
        <input
          type="checkbox"
          checked={isSelected}
          onChange={() => onToggleSelect(profile.name)}
          disabled={isSeeding}
          data-action="toggle-profile"
          className={css({
            width: '16px',
            height: '16px',
            cursor: isSeeding ? 'not-allowed' : 'pointer',
            flexShrink: 0,
          })}
        />

        <div className={css({ flex: 1, minWidth: 0 })}>
          <div
            className={css({
              fontWeight: '600',
              fontSize: '0.9rem',
              color: isDark ? 'white' : 'gray.800',
            })}
          >
            {profile.name}
          </div>
          <div
            className={css({
              fontSize: '0.8rem',
              color: isDark ? 'gray.400' : 'gray.600',
              overflow: 'hidden',
              textOverflow: 'ellipsis',
              whiteSpace: 'nowrap',
            })}
          >
            {profile.description}
          </div>
        </div>

        {/* Similarity score when searching */}
        {similarity !== undefined && (
          <span
            className={css({
              fontSize: '0.7rem',
              fontWeight: '500',
              padding: '2px 6px',
              borderRadius: '4px',
              flexShrink: 0,
              fontFamily: 'monospace',
              backgroundColor: isDark ? 'blue.900/50' : 'blue.50',
              color: isDark ? 'blue.300' : 'blue.600',
            })}
          >
            {Math.round(similarity * 100)}%
          </span>
        )}

        {/* Status indicator when seeding */}
        {studentStatus && (
          <span className={css({ flexShrink: 0, fontSize: '1rem' })}>
            {studentStatus.status === 'completed'
              ? '✅'
              : studentStatus.status === 'failed'
                ? '❌'
                : studentStatus.status === 'seeding'
                  ? '⏳'
                  : '○'}
          </span>
        )}
      </div>

      {/* Completed details */}
      {studentStatus?.status === 'completed' && (
        <div
          className={css({
            marginTop: '6px',
            marginLeft: '26px',
            fontSize: '0.75rem',
            color: isDark ? 'gray.400' : 'gray.500',
            display: 'flex',
            flexDirection: 'column',
            gap: '3px',
          })}
        >
          {studentStatus.classifications && (
            <div>
              🔴 {studentStatus.classifications.weak} weak, 📚{' '}
              {studentStatus.classifications.developing} dev, ✅{' '}
              {studentStatus.classifications.strong} strong
            </div>
          )}
          <div className={css({ display: 'flex', alignItems: 'center', gap: '10px' })}>
            {studentStatus.playerId && (
              <>
                <a
                  href={`/practice/${studentStatus.playerId}/dashboard`}
                  target="_blank"
                  rel="noopener noreferrer"
                  data-action="view-dashboard"
                  className={css({
                    color: isDark ? 'blue.400' : 'blue.600',
                    textDecoration: 'underline',
                    _hover: { color: isDark ? 'blue.300' : 'blue.500' },
                  })}
                >
                  View dashboard
                </a>
                <button
                  data-action="share-access"
                  onClick={() => onShareAccess?.(studentStatus.playerId!, profile.name)}
                  className={css({
                    display: 'inline-flex',
                    alignItems: 'center',
                    gap: '4px',
                    color: isDark ? 'blue.400' : 'blue.600',
                    textDecoration: 'underline',
                    background: 'none',
                    border: 'none',
                    padding: 0,
                    cursor: 'pointer',
                    fontSize: 'inherit',
                    _hover: { color: isDark ? 'blue.300' : 'blue.500' },
                  })}
                >
                  <Share2 size={11} />
                  Share
                </button>
              </>
            )}
            {studentStatus.seededAt && (
              <span className={css({ color: isDark ? 'gray.600' : 'gray.400' })}>
                Seeded {studentStatus.seededAt.toLocaleString()}
              </span>
            )}
          </div>
        </div>
      )}

      {/* Failed details */}
      {studentStatus?.status === 'failed' && (
        <div
          className={css({
            marginTop: '6px',
            marginLeft: '26px',
            fontSize: '0.75rem',
            color: isDark ? 'red.400' : 'red.600',
          })}
        >
          {studentStatus.error}
        </div>
      )}

      {/* Expandable details */}
      <button
        data-action="toggle-details"
        onClick={() => onToggleExpand(profile.name)}
        className={css({
          display: 'flex',
          alignItems: 'center',
          gap: '4px',
          marginTop: '6px',
          marginLeft: '26px',
          fontSize: '0.75rem',
          color: isDark ? 'gray.500' : 'gray.400',
          cursor: 'pointer',
          background: 'none',
          border: 'none',
          padding: 0,
          _hover: { color: isDark ? 'gray.300' : 'gray.600' },
        })}
      >
        {isExpanded ? <ChevronDown size={12} /> : <ChevronRight size={12} />}
        {isExpanded ? 'Hide details' : 'Show details'}
      </button>

      {isExpanded && (
        <pre
          className={css({
            marginTop: '8px',
            marginLeft: '26px',
            padding: '10px',
            backgroundColor: isDark ? 'gray.900' : 'gray.50',
            borderRadius: '6px',
            fontSize: '0.7rem',
            lineHeight: '1.4',
            color: isDark ? 'gray.300' : 'gray.700',
            whiteSpace: 'pre-wrap',
            wordBreak: 'break-word',
            maxHeight: '200px',
            overflowY: 'auto',
          })}
        >
          {profile.intentionNotes}
        </pre>
      )}
    </div>
  )
}

export function SeedStudentsSection({ isDark }: { isDark: boolean }) {
  // ── Server state via React Query ───────────────────────────────────────────
  const { data: profilesData, isLoading: profilesLoading, error: profilesError } = useSeedProfiles()
  const { data: embeddingStatus } = useEmbeddingStatus()
  const { data: seededData } = useSeededStudents()
  const regenerateEmbeddings = useRegenerateEmbeddings()
  const seedMutation = useSeedStudents()

  const profiles = profilesData?.profiles ?? []

  // ── Local UI state ─────────────────────────────────────────────────────────
  const [selected, setSelected] = useState<Set<string>>(new Set())
  const [expandedProfiles, setExpandedProfiles] = useState<Set<string>>(new Set())
  const [taskId, setTaskId] = useState<string | null>(null)
  const [studentStatuses, setStudentStatuses] = useState<Map<string, StudentStatus>>(new Map())
  const [classroomCode, setClassroomCode] = useState<string | null>(null)
  const [searchQuery, setSearchQuery] = useState('')
  const [debouncedSearchQuery, setDebouncedSearchQuery] = useState('')
  const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null)
  const [sharePlayer, setSharePlayer] = useState<{ playerId: string; name: string } | null>(null)

  // ── Search via React Query with debounced input ────────────────────────────
  const { data: searchResults, isFetching: searching } = useSeedProfileSearch(debouncedSearchQuery)

  // Show search results when we have a debounced query >= 3 chars
  const activeSearchResults = debouncedSearchQuery.trim().length >= 3 ? searchResults : null

  interface TaskOutput {
    seededCount: number
    failedCount: number
    classroomCode: string
    students: Array<{
      name: string
      status: 'completed' | 'failed'
      playerId?: string
      classifications?: { weak: number; developing: number; strong: number }
      error?: string
    }>
  }

  const { state: taskState } = useBackgroundTask<TaskOutput>(taskId)

  // ── Populate statuses from previously-seeded data ──────────────────────────
  const seededDataRef = useRef(seededData)
  useEffect(() => {
    // Only run when seededData first arrives (not on every render)
    if (seededData && seededData !== seededDataRef.current) {
      seededDataRef.current = seededData
      if (Object.keys(seededData).length === 0) return
      const statuses = new Map<string, StudentStatus>()
      for (const [profileName, info] of Object.entries(seededData)) {
        statuses.set(profileName, {
          name: profileName,
          status: 'completed',
          playerId: info.playerId,
          seededAt: new Date(info.seededAt),
        })
      }
      setStudentStatuses(statuses)
    }
  }, [seededData])

  // Process task events for per-student status (merge with existing)
  useEffect(() => {
    if (!taskState?.events) return

    const updates = new Map<string, StudentStatus>()

    for (const event of taskState.events) {
      const payload = event.payload as Record<string, unknown>

      switch (event.eventType) {
        case 'seed_started': {
          const names = payload.profileNames as string[]
          for (const name of names) {
            updates.set(name, { name, status: 'pending' })
          }
          break
        }
        case 'student_started': {
          const name = payload.name as string
          updates.set(name, { name, status: 'seeding' })
          break
        }
        case 'student_completed': {
          const name = payload.name as string
          updates.set(name, {
            name,
            status: 'completed',
            playerId: payload.playerId as string,
            classifications: payload.classifications as {
              weak: number
              developing: number
              strong: number
            },
            seededAt: new Date(),
          })
          break
        }
        case 'student_failed': {
          const name = payload.name as string
          updates.set(name, {
            name,
            status: 'failed',
            error: payload.error as string,
          })
          break
        }
        case 'seed_complete': {
          setClassroomCode(payload.classroomCode as string)
          break
        }
      }
    }

    if (updates.size > 0) {
      setStudentStatuses((prev) => {
        const merged = new Map(prev)
        for (const [name, status] of updates) {
          merged.set(name, status)
        }
        return merged
      })
    }
  }, [taskState?.events])

  // Populate from task output when events weren't received (fast-completing tasks)
  useEffect(() => {
    if (!taskState?.output) return
    // Skip if task events already populated statuses for this task
    if (taskState.events && taskState.events.length > 0) return

    const output = taskState.output
    setClassroomCode(output.classroomCode)

    setStudentStatuses((prev) => {
      const merged = new Map(prev)
      for (const student of output.students) {
        merged.set(student.name, {
          name: student.name,
          status: student.status === 'completed' ? 'completed' : 'failed',
          playerId: student.playerId,
          classifications: student.classifications,
          error: student.error,
          seededAt: new Date(),
        })
      }
      return merged
    })
  }, [taskState?.output, taskState?.events])

  const groupedProfiles = useMemo(
    () =>
      PROFILE_GROUPS.map((group) => ({
        ...group,
        profiles: profiles.filter(group.match),
      })),
    [profiles]
  )

  const toggleSelect = useCallback((name: string) => {
    setSelected((prev) => {
      const next = new Set(prev)
      if (next.has(name)) next.delete(name)
      else next.add(name)
      return next
    })
  }, [])

  const toggleExpand = useCallback((name: string) => {
    setExpandedProfiles((prev) => {
      const next = new Set(prev)
      if (next.has(name)) next.delete(name)
      else next.add(name)
      return next
    })
  }, [])

  const toggleGroup = useCallback((groupProfiles: ProfileInfo[]) => {
    setSelected((prev) => {
      const names = groupProfiles.map((p) => p.name)
      const allSelected = names.every((n) => prev.has(n))
      const next = new Set(prev)
      for (const name of names) {
        if (allSelected) next.delete(name)
        else next.add(name)
      }
      return next
    })
  }, [])

  const handleSearch = useCallback((query: string) => {
    setSearchQuery(query)

    if (debounceRef.current) clearTimeout(debounceRef.current)

    if (query.trim().length < 3) {
      setDebouncedSearchQuery('')
      return
    }

    debounceRef.current = setTimeout(() => {
      setDebouncedSearchQuery(query.trim())
    }, 400)
  }, [])

  const handleSeed = useCallback(
    (profileNames: string[]) => {
      setStudentStatuses(new Map())
      setClassroomCode(null)

      seedMutation.mutate(profileNames, {
        onSuccess: (data) => {
          setTaskId(data.taskId)
        },
      })
    },
    [seedMutation]
  )

  const isSeeding = taskState?.status === 'running' || taskState?.status === 'pending'
  const isComplete = taskState?.status === 'completed'
  const isFailed = taskState?.status === 'failed'

  const error = profilesError?.message ?? seedMutation.error?.message ?? null

  if (profilesLoading) {
    return (
      <div
        data-component="seed-students-loading"
        className={css({
          padding: '2rem',
          textAlign: 'center',
          color: isDark ? 'gray.500' : 'gray.400',
        })}
      >
        <Loader2
          size={24}
          className={css({ animation: 'spin 1s linear infinite', display: 'inline-block' })}
        />
      </div>
    )
  }

  return (
    <section data-component="seed-students-section" className={css({ marginTop: '2rem' })}>
      {/* Header */}
      <h2
        className={css({
          fontSize: '1.25rem',
          fontWeight: '600',
          color: isDark ? 'white' : 'gray.800',
          marginBottom: '0.75rem',
          paddingBottom: '0.5rem',
          borderBottom: '1px solid',
          borderColor: isDark ? 'gray.700' : 'gray.200',
        })}
      >
        Seed Test Students
      </h2>

      {/* Error banner */}
      {error && (
        <div
          data-element="seed-error"
          className={css({
            padding: '12px 16px',
            backgroundColor: isDark ? 'red.900/30' : 'red.50',
            color: isDark ? 'red.300' : 'red.700',
            borderRadius: '8px',
            marginBottom: '1rem',
            fontSize: '0.875rem',
            border: '1px solid',
            borderColor: isDark ? 'red.800' : 'red.200',
          })}
        >
          {error}
        </div>
      )}

      {/* Search input */}
      <div
        data-element="search-bar"
        className={css({
          position: 'relative',
          marginBottom: '1rem',
        })}
      >
        <Search
          size={16}
          className={css({
            position: 'absolute',
            left: '12px',
            top: '50%',
            transform: 'translateY(-50%)',
            color: isDark ? 'gray.500' : 'gray.400',
            pointerEvents: 'none',
          })}
        />
        <input
          type="text"
          placeholder="Search profiles... e.g. &quot;struggling student&quot; or &quot;chart with many sessions&quot;"
          value={searchQuery}
          onChange={(e) => handleSearch(e.target.value)}
          disabled={isSeeding}
          data-action="search-profiles"
          className={css({
            width: '100%',
            padding: '8px 12px 8px 36px',
            borderRadius: '8px',
            border: '1px solid',
            borderColor: isDark ? 'gray.700' : 'gray.300',
            backgroundColor: isDark ? 'gray.800' : 'white',
            color: isDark ? 'white' : 'gray.800',
            fontSize: '0.85rem',
            outline: 'none',
            _focus: {
              borderColor: isDark ? 'blue.500' : 'blue.400',
            },
            _placeholder: {
              color: isDark ? 'gray.600' : 'gray.400',
            },
          })}
        />
        {searching && (
          <Loader2
            size={14}
            className={css({
              position: 'absolute',
              right: '12px',
              top: '50%',
              transform: 'translateY(-50%)',
              animation: 'spin 1s linear infinite',
              color: isDark ? 'gray.500' : 'gray.400',
            })}
          />
        )}
      </div>

      {/* Embedding status indicator */}
      {embeddingStatus && (embeddingStatus.stale || !embeddingStatus.cached) && (
        <div
          data-element="embedding-status"
          className={css({
            display: 'flex',
            alignItems: 'center',
            gap: '8px',
            padding: '8px 12px',
            marginBottom: '0.75rem',
            borderRadius: '8px',
            fontSize: '0.8rem',
            backgroundColor: embeddingStatus.stale
              ? isDark
                ? 'yellow.900/30'
                : 'yellow.50'
              : isDark
                ? 'gray.800'
                : 'gray.100',
            border: '1px solid',
            borderColor: embeddingStatus.stale
              ? isDark
                ? 'yellow.800'
                : 'yellow.300'
              : isDark
                ? 'gray.700'
                : 'gray.300',
            color: embeddingStatus.stale
              ? isDark
                ? 'yellow.300'
                : 'yellow.800'
              : isDark
                ? 'gray.400'
                : 'gray.600',
          })}
        >
          {embeddingStatus.stale && <AlertTriangle size={14} className={css({ flexShrink: 0 })} />}
          <span className={css({ flex: 1 })}>
            {embeddingStatus.stale
              ? 'Search embeddings are stale — profile content has changed since they were generated.'
              : 'Search embeddings not yet generated.'}
          </span>
          <button
            data-action="regenerate-embeddings"
            onClick={() => regenerateEmbeddings.mutate()}
            disabled={regenerateEmbeddings.isPending}
            className={css({
              display: 'inline-flex',
              alignItems: 'center',
              gap: '4px',
              padding: '4px 10px',
              borderRadius: '6px',
              fontSize: '0.75rem',
              fontWeight: '600',
              border: 'none',
              cursor: regenerateEmbeddings.isPending ? 'not-allowed' : 'pointer',
              flexShrink: 0,
              backgroundColor: embeddingStatus.stale
                ? isDark
                  ? 'yellow.700'
                  : 'yellow.500'
                : isDark
                  ? 'blue.700'
                  : 'blue.500',
              color: 'white',
              _hover: regenerateEmbeddings.isPending
                ? {}
                : {
                    backgroundColor: embeddingStatus.stale
                      ? isDark
                        ? 'yellow.600'
                        : 'yellow.400'
                      : isDark
                        ? 'blue.600'
                        : 'blue.400',
                  },
            })}
          >
            <RefreshCw
              size={12}
              className={
                regenerateEmbeddings.isPending
                  ? css({ animation: 'spin 1s linear infinite' })
                  : undefined
              }
            />
            {regenerateEmbeddings.isPending ? 'Regenerating...' : 'Regenerate'}
          </button>
        </div>
      )}

      {/* Action bar — sticky above list */}
      {(selected.size > 0 || isComplete || isFailed) && (
        <div
          data-element="seed-actions"
          className={css({
            position: 'sticky',
            top: '73px',
            zIndex: 10,
            backgroundColor: isDark ? 'gray.900' : 'gray.50',
            padding: '8px 0',
            marginBottom: '4px',
            display: 'flex',
            alignItems: 'center',
            gap: '12px',
          })}
        >
          {isComplete ? (
            <button
              data-action="seed-more"
              onClick={() => {
                setTaskId(null)
                setClassroomCode(null)
              }}
              className={css({
                padding: '10px 20px',
                backgroundColor: isDark ? 'green.700' : 'green.600',
                color: 'white',
                borderRadius: '8px',
                fontWeight: '600',
                fontSize: '0.875rem',
                border: 'none',
                cursor: 'pointer',
                _hover: { backgroundColor: isDark ? 'green.600' : 'green.500' },
              })}
            >
              Seed More
            </button>
          ) : (
            <button
              data-action="seed-selected"
              onClick={() => handleSeed(Array.from(selected))}
              disabled={isSeeding || seedMutation.isPending || selected.size === 0}
              className={css({
                padding: '10px 20px',
                backgroundColor:
                  isSeeding || selected.size === 0
                    ? isDark
                      ? 'gray.700'
                      : 'gray.300'
                    : isDark
                      ? 'blue.600'
                      : 'blue.500',
                color: 'white',
                borderRadius: '8px',
                fontWeight: '600',
                fontSize: '0.875rem',
                border: 'none',
                cursor: isSeeding || selected.size === 0 ? 'not-allowed' : 'pointer',
                _hover:
                  isSeeding || selected.size === 0
                    ? {}
                    : { backgroundColor: isDark ? 'blue.500' : 'blue.600' },
              })}
            >
              {isSeeding ? 'Seeding...' : `Seed Selected (${selected.size})`}
            </button>
          )}
          {/* Inline progress */}
          {isSeeding && taskState?.progressMessage && (
            <span
              className={css({
                fontSize: '0.8rem',
                color: isDark ? 'gray.400' : 'gray.600',
              })}
            >
              {taskState.progressMessage}
            </span>
          )}
          {isComplete && classroomCode && (
            <span
              className={css({
                fontSize: '0.8rem',
                color: isDark ? 'green.400' : 'green.600',
              })}
            >
              Done — classroom code: {classroomCode}
            </span>
          )}
        </div>
      )}

      {/* Profile list — grouped view or search results */}
      <div data-element="profile-list" className={css({ marginBottom: '1rem' })}>
        {activeSearchResults ? (
          /* Search results: flat list ranked by similarity */
          <div
            data-element="search-results"
            className={css({ display: 'flex', flexDirection: 'column', gap: '6px' })}
          >
            {activeSearchResults.size === 0 && !searching && (
              <div
                className={css({
                  padding: '1rem',
                  textAlign: 'center',
                  fontSize: '0.85rem',
                  color: isDark ? 'gray.500' : 'gray.400',
                })}
              >
                No matching profiles found
              </div>
            )}
            {profiles
              .filter((p) => activeSearchResults.has(p.name))
              .sort(
                (a, b) =>
                  (activeSearchResults.get(b.name) ?? 0) - (activeSearchResults.get(a.name) ?? 0)
              )
              .map((profile) => (
                <ProfileCard
                  key={profile.name}
                  profile={profile}
                  isDark={isDark}
                  isSeeding={isSeeding}
                  isSelected={selected.has(profile.name)}
                  isExpanded={expandedProfiles.has(profile.name)}
                  studentStatus={studentStatuses.get(profile.name)}
                  similarity={activeSearchResults.get(profile.name)}
                  onToggleSelect={toggleSelect}
                  onToggleExpand={toggleExpand}
                  onShareAccess={(playerId, name) => setSharePlayer({ playerId, name })}
                />
              ))}
          </div>
        ) : (
          /* Grouped view */
          groupedProfiles.map((group) => {
            const groupNames = group.profiles.map((p) => p.name)
            const allGroupSelected =
              groupNames.length > 0 && groupNames.every((n) => selected.has(n))
            const someGroupSelected = !allGroupSelected && groupNames.some((n) => selected.has(n))

            return (
              <div
                key={group.id}
                data-element={`group-${group.id}`}
                className={css({ marginBottom: '1.25rem' })}
              >
                {/* Group header */}
                <div
                  className={css({
                    display: 'flex',
                    alignItems: 'baseline',
                    gap: '10px',
                    marginBottom: '8px',
                  })}
                >
                  <label
                    className={css({
                      display: 'flex',
                      alignItems: 'center',
                      gap: '8px',
                      cursor: isSeeding ? 'not-allowed' : 'pointer',
                    })}
                  >
                    <input
                      type="checkbox"
                      checked={allGroupSelected}
                      ref={(el) => {
                        if (el) el.indeterminate = someGroupSelected
                      }}
                      onChange={() => toggleGroup(group.profiles)}
                      disabled={isSeeding}
                      data-action={`toggle-group-${group.id}`}
                      className={css({
                        width: '14px',
                        height: '14px',
                        cursor: isSeeding ? 'not-allowed' : 'pointer',
                        flexShrink: 0,
                      })}
                    />
                    <span
                      className={css({
                        fontSize: '0.95rem',
                        fontWeight: '600',
                        color: isDark ? 'white' : 'gray.800',
                      })}
                    >
                      {group.label}
                    </span>
                  </label>
                  <span
                    className={css({
                      fontSize: '0.8rem',
                      color: isDark ? 'gray.500' : 'gray.500',
                    })}
                  >
                    {group.description}
                  </span>
                </div>

                {/* Group profiles */}
                <div
                  className={css({
                    display: 'flex',
                    flexDirection: 'column',
                    gap: '6px',
                    paddingLeft: '22px',
                  })}
                >
                  {group.profiles.map((profile) => (
                    <ProfileCard
                      key={profile.name}
                      profile={profile}
                      isDark={isDark}
                      isSeeding={isSeeding}
                      isSelected={selected.has(profile.name)}
                      isExpanded={expandedProfiles.has(profile.name)}
                      studentStatus={studentStatuses.get(profile.name)}
                      onToggleSelect={toggleSelect}
                      onToggleExpand={toggleExpand}
                      onShareAccess={(playerId, name) => setSharePlayer({ playerId, name })}
                    />
                  ))}
                </div>
              </div>
            )
          })
        )}
      </div>

      {/* Failed banner */}
      {isFailed && (
        <div
          data-element="seed-failed"
          className={css({
            padding: '12px 16px',
            backgroundColor: isDark ? 'red.900/20' : 'red.50',
            borderRadius: '8px',
            border: '1px solid',
            borderColor: isDark ? 'red.800' : 'red.200',
            fontSize: '0.85rem',
            color: isDark ? 'red.300' : 'red.700',
          })}
        >
          Seeding failed: {taskState?.error}
        </div>
      )}

      {/* Family share modal */}
      <FamilyCodeDisplay
        playerId={sharePlayer?.playerId ?? ''}
        playerName={sharePlayer?.name ?? ''}
        isOpen={sharePlayer !== null}
        onClose={() => setSharePlayer(null)}
      />
    </section>
  )
}