All files / web/src/app/admin/practice-config PracticeConfigClient.tsx

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

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

import { useCallback, useMemo, useState } from 'react'
import { PageWithNav } from '@/components/PageWithNav'
import { AdminNav } from '@/components/AdminNav'
import { useTheme } from '@/contexts/ThemeContext'
import {
  usePracticeConfig,
  useUpdatePracticeConfig,
  useResetPracticeConfig,
} from '@/hooks/usePracticeConfig'
import {
  computeTermCountRange,
  DEFAULT_TERM_COUNT_SCALING,
  validateTermCountScaling,
  type TermCountScalingConfig,
  type ModeScalingConfig,
} from '@/lib/curriculum/config/term-count-scaling'
import type { SessionPartType } from '@/db/schema/session-plans'
import { css } from '../../../../styled-system/css'

const MODE_LABELS: Record<SessionPartType, { emoji: string; label: string }> = {
  abacus: { emoji: '\u{1F9EE}', label: 'Abacus' },
  visualization: { emoji: '\u{1F9E0}', label: 'Visualization' },
  linear: { emoji: '\u{1F4AD}', label: 'Linear' },
}

const MODES: SessionPartType[] = ['abacus', 'visualization', 'linear']

export function PracticeConfigClient() {
  const { resolvedTheme } = useTheme()
  const isDark = resolvedTheme === 'dark'

  const { data, isLoading } = usePracticeConfig()
  const updateMutation = useUpdatePracticeConfig()
  const resetMutation = useResetPracticeConfig()

  // Local draft state for editing
  const [draft, setDraft] = useState<TermCountScalingConfig | null>(null)
  const [comfortSlider, setComfortSlider] = useState(30)

  // When data loads and we have no draft, initialize from server
  const serverConfig = data?.config ?? DEFAULT_TERM_COUNT_SCALING
  const editConfig = draft ?? serverConfig

  // Track if there are unsaved changes
  const hasChanges = draft !== null && JSON.stringify(draft) !== JSON.stringify(serverConfig)

  // Validation
  const validationError = useMemo(() => {
    if (!draft) return null
    return validateTermCountScaling(draft)
  }, [draft])

  // Comfort as 0-1 scale
  const comfort = comfortSlider / 100

  // Compute preview ranges for all modes at current comfort
  const previewRanges = useMemo(() => {
    const result: Record<SessionPartType, { min: number; max: number }> = {} as Record<
      SessionPartType,
      { min: number; max: number }
    >
    for (const mode of MODES) {
      result[mode] = computeTermCountRange(mode, comfort, editConfig)
    }
    return result
  }, [comfort, editConfig])

  // Floor/ceiling ranges from config (for display)
  const floorRanges = useMemo(() => {
    const result: Record<SessionPartType, { min: number; max: number }> = {} as Record<
      SessionPartType,
      { min: number; max: number }
    >
    for (const mode of MODES) {
      result[mode] = computeTermCountRange(mode, 0, editConfig)
    }
    return result
  }, [editConfig])

  const ceilingRanges = useMemo(() => {
    const result: Record<SessionPartType, { min: number; max: number }> = {} as Record<
      SessionPartType,
      { min: number; max: number }
    >
    for (const mode of MODES) {
      result[mode] = computeTermCountRange(mode, 1, editConfig)
    }
    return result
  }, [editConfig])

  const updateField = useCallback(
    (mode: SessionPartType, level: 'floor' | 'ceiling', bound: 'min' | 'max', value: number) => {
      const base = draft ?? { ...serverConfig }
      const updated: TermCountScalingConfig = {
        ...base,
        [mode]: {
          ...base[mode],
          [level]: {
            ...base[mode][level],
            [bound]: value,
          },
        },
      }
      setDraft(updated)
    },
    [draft, serverConfig]
  )

  const handleSave = useCallback(() => {
    if (!draft || validationError) return
    updateMutation.mutate(draft, {
      onSuccess: () => setDraft(null),
    })
  }, [draft, validationError, updateMutation])

  const handleReset = useCallback(() => {
    resetMutation.mutate(undefined, {
      onSuccess: () => setDraft(null),
    })
  }, [resetMutation])

  const handleRevertDraft = useCallback(() => {
    setDraft(null)
  }, [])

  // Styles
  const cardBg = isDark ? '#161b22' : '#f6f8fa'
  const cardBorder = isDark ? '#30363d' : '#d0d7de'
  const textPrimary = isDark ? '#f0f6fc' : '#1f2328'
  const textSecondary = isDark ? '#8b949e' : '#656d76'
  const accentBlue = '#58a6ff'
  const errorRed = '#f85149'

  if (isLoading) {
    return (
      <PageWithNav>
        <AdminNav />
        <div
          className={css({ padding: '24px', color: textSecondary })}
          data-component="practice-config-loading"
        >
          Loading practice config...
        </div>
      </PageWithNav>
    )
  }

  return (
    <PageWithNav>
      <AdminNav />
      <div
        className={css({
          maxWidth: '900px',
          margin: '0 auto',
          padding: '24px',
        })}
        data-component="practice-config-page"
      >
        {/* Header */}
        <h1
          className={css({
            fontSize: '24px',
            fontWeight: '600',
            color: textPrimary,
            marginBottom: '8px',
          })}
        >
          Term Count Scaling
        </h1>
        <p className={css({ fontSize: '14px', color: textSecondary, marginBottom: '24px' })}>
          Controls how many terms per problem (e.g. 2+3+4 = 3 terms) a student gets based on their
          comfort level per mode.
        </p>

        {/* Pipeline Visualization */}
        <PipelineVisualization
          isDark={isDark}
          textPrimary={textPrimary}
          textSecondary={textSecondary}
          cardBg={cardBg}
          cardBorder={cardBorder}
        />

        {/* Interactive Preview */}
        <div
          className={css({
            background: cardBg,
            border: `1px solid ${cardBorder}`,
            borderRadius: '8px',
            padding: '20px',
            marginBottom: '24px',
          })}
          data-component="comfort-preview"
        >
          <h2
            className={css({
              fontSize: '16px',
              fontWeight: '600',
              color: textPrimary,
              marginBottom: '16px',
            })}
          >
            Interactive Preview
          </h2>

          {/* Comfort Slider */}
          <div className={css({ marginBottom: '16px' })}>
            <label
              className={css({
                fontSize: '13px',
                fontWeight: '500',
                color: textSecondary,
                display: 'flex',
                alignItems: 'center',
                gap: '8px',
                marginBottom: '8px',
              })}
            >
              Comfort Level:
              <input
                type="range"
                min={0}
                max={100}
                value={comfortSlider}
                onChange={(e) => setComfortSlider(Number(e.target.value))}
                className={css({ flex: '1', cursor: 'pointer' })}
                data-element="comfort-slider"
              />
              <span className={css({ fontWeight: '700', color: textPrimary, minWidth: '40px' })}>
                {comfortSlider}%
              </span>
            </label>
          </div>

          {/* Results Table */}
          <table
            className={css({
              width: '100%',
              borderCollapse: 'collapse',
              fontSize: '13px',
            })}
          >
            <thead>
              <tr>
                <th
                  className={css({
                    textAlign: 'left',
                    padding: '8px',
                    color: textSecondary,
                    fontWeight: '500',
                  })}
                />
                <th
                  className={css({
                    textAlign: 'center',
                    padding: '8px',
                    color: textSecondary,
                    fontWeight: '500',
                  })}
                >
                  Struggling (0%)
                </th>
                <th
                  className={css({
                    textAlign: 'center',
                    padding: '8px',
                    color: accentBlue,
                    fontWeight: '600',
                  })}
                >
                  At {comfortSlider}%
                </th>
                <th
                  className={css({
                    textAlign: 'center',
                    padding: '8px',
                    color: textSecondary,
                    fontWeight: '500',
                  })}
                >
                  Mastered (100%)
                </th>
              </tr>
            </thead>
            <tbody>
              {MODES.map((mode) => (
                <tr key={mode}>
                  <td className={css({ padding: '8px', fontWeight: '500', color: textPrimary })}>
                    {MODE_LABELS[mode].emoji} {MODE_LABELS[mode].label}
                  </td>
                  <td
                    className={css({ textAlign: 'center', padding: '8px', color: textSecondary })}
                  >
                    {floorRanges[mode].min}–{floorRanges[mode].max}
                  </td>
                  <td
                    className={css({
                      textAlign: 'center',
                      padding: '8px',
                      fontWeight: '700',
                      color: accentBlue,
                    })}
                  >
                    {previewRanges[mode].min}–{previewRanges[mode].max}
                  </td>
                  <td
                    className={css({ textAlign: 'center', padding: '8px', color: textSecondary })}
                  >
                    {ceilingRanges[mode].min}–{ceilingRanges[mode].max}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>

          {/* Interpolation bars */}
          <div
            className={css({
              marginTop: '16px',
              display: 'flex',
              flexDirection: 'column',
              gap: '8px',
            })}
          >
            {MODES.map((mode) => (
              <InterpolationBar
                key={mode}
                mode={mode}
                comfort={comfort}
                floor={editConfig[mode].floor}
                ceiling={editConfig[mode].ceiling}
                preview={previewRanges[mode]}
                isDark={isDark}
                textSecondary={textSecondary}
              />
            ))}
          </div>
        </div>

        {/* Per-Mode Config Cards */}
        <div
          className={css({
            display: 'flex',
            flexDirection: 'column',
            gap: '16px',
            marginBottom: '24px',
          })}
        >
          {MODES.map((mode) => (
            <ModeConfigCard
              key={mode}
              mode={mode}
              config={editConfig[mode]}
              onChange={(level, bound, value) => updateField(mode, level, bound, value)}
              comfort={comfort}
              preview={previewRanges[mode]}
              isDark={isDark}
              cardBg={cardBg}
              cardBorder={cardBorder}
              textPrimary={textPrimary}
              textSecondary={textSecondary}
              accentBlue={accentBlue}
              errorRed={errorRed}
            />
          ))}
        </div>

        {/* Validation Error */}
        {validationError && (
          <div
            className={css({
              padding: '12px 16px',
              borderRadius: '6px',
              background: isDark ? '#2d1215' : '#ffebe9',
              border: `1px solid ${errorRed}`,
              color: errorRed,
              fontSize: '13px',
              marginBottom: '16px',
            })}
            data-element="validation-error"
          >
            {validationError}
          </div>
        )}

        {/* Save Controls */}
        <div
          className={css({
            display: 'flex',
            alignItems: 'center',
            gap: '12px',
            flexWrap: 'wrap',
          })}
          data-component="save-controls"
        >
          <button
            onClick={handleSave}
            disabled={!hasChanges || !!validationError || updateMutation.isPending}
            className={css({
              padding: '8px 20px',
              borderRadius: '6px',
              border: 'none',
              background: hasChanges && !validationError ? '#238636' : '#21262d',
              color: hasChanges && !validationError ? '#fff' : '#8b949e',
              fontSize: '14px',
              fontWeight: '500',
              cursor: hasChanges && !validationError ? 'pointer' : 'not-allowed',
              opacity: updateMutation.isPending ? '0.7' : '1',
            })}
            data-action="save"
          >
            {updateMutation.isPending ? 'Saving...' : 'Save Changes'}
          </button>

          <button
            onClick={handleReset}
            disabled={resetMutation.isPending || (!data?.isCustom && !hasChanges)}
            className={css({
              padding: '8px 20px',
              borderRadius: '6px',
              border: `1px solid ${cardBorder}`,
              background: 'transparent',
              color: textSecondary,
              fontSize: '14px',
              fontWeight: '500',
              cursor: data?.isCustom || hasChanges ? 'pointer' : 'not-allowed',
              opacity: data?.isCustom || hasChanges ? '1' : '0.5',
            })}
            data-action="reset-defaults"
          >
            {resetMutation.isPending ? 'Resetting...' : 'Reset to Defaults'}
          </button>

          {hasChanges && (
            <button
              onClick={handleRevertDraft}
              className={css({
                padding: '8px 20px',
                borderRadius: '6px',
                border: `1px solid ${cardBorder}`,
                background: 'transparent',
                color: textSecondary,
                fontSize: '14px',
                fontWeight: '500',
                cursor: 'pointer',
              })}
              data-action="discard"
            >
              Discard Changes
            </button>
          )}

          {hasChanges && (
            <span className={css({ fontSize: '13px', color: '#d29922' })}>
              You have unsaved changes
            </span>
          )}

          {data?.isCustom && !hasChanges && (
            <span className={css({ fontSize: '13px', color: textSecondary })}>
              Using custom config
            </span>
          )}
        </div>

        {/* How It Works Section */}
        <HowItWorks
          isDark={isDark}
          cardBg={cardBg}
          cardBorder={cardBorder}
          textPrimary={textPrimary}
          textSecondary={textSecondary}
        />
      </div>
    </PageWithNav>
  )
}

// =============================================================================
// Pipeline Visualization
// =============================================================================

function PipelineVisualization({
  isDark,
  textPrimary,
  textSecondary,
  cardBg,
  cardBorder,
}: {
  isDark: boolean
  textPrimary: string
  textSecondary: string
  cardBg: string
  cardBorder: string
}) {
  const steps = [
    { title: 'BKT Mastery', detail: 'per-skill pKnown\nweighted avg' },
    { title: 'Comfort Level', detail: '0–1 scale\n× mode mult.' },
    { title: 'This Config', detail: 'floor ↔ ceiling\nlinear interp.' },
    { title: 'Term Count', detail: 'per problem\nrandom in range' },
  ]

  return (
    <div
      className={css({
        display: 'flex',
        alignItems: 'center',
        gap: '8px',
        marginBottom: '24px',
        overflowX: 'auto',
        paddingBottom: '4px',
      })}
      data-component="pipeline-viz"
    >
      {steps.map((step, i) => (
        <div
          key={step.title}
          className={css({ display: 'flex', alignItems: 'center', gap: '8px' })}
        >
          <div
            className={css({
              background: cardBg,
              border: `1px solid ${i === 2 ? '#58a6ff' : cardBorder}`,
              borderRadius: '8px',
              padding: '12px 16px',
              minWidth: '130px',
              textAlign: 'center',
            })}
          >
            <div
              className={css({
                fontSize: '13px',
                fontWeight: '600',
                color: textPrimary,
                marginBottom: '4px',
              })}
            >
              {step.title}
            </div>
            <div
              className={css({
                fontSize: '11px',
                color: textSecondary,
                whiteSpace: 'pre-line',
                lineHeight: '1.4',
              })}
            >
              {step.detail}
            </div>
          </div>
          {i < steps.length - 1 && (
            <span className={css({ color: textSecondary, fontSize: '16px', flexShrink: '0' })}>

            </span>
          )}
        </div>
      ))}
    </div>
  )
}

// =============================================================================
// Interpolation Bar
// =============================================================================

function InterpolationBar({
  mode,
  comfort,
  floor,
  ceiling,
  preview,
  isDark,
  textSecondary,
}: {
  mode: SessionPartType
  comfort: number
  floor: { min: number; max: number }
  ceiling: { min: number; max: number }
  preview: { min: number; max: number }
  isDark: boolean
  textSecondary: string
}) {
  const { emoji, label } = MODE_LABELS[mode]
  const pct = Math.round(comfort * 100)

  return (
    <div className={css({ display: 'flex', alignItems: 'center', gap: '8px' })}>
      <span className={css({ fontSize: '12px', color: textSecondary, minWidth: '100px' })}>
        {emoji} {label}
      </span>
      <div
        className={css({
          flex: '1',
          height: '12px',
          borderRadius: '6px',
          background: isDark
            ? 'linear-gradient(to right, #1a3a2a, #0d4429, #238636)'
            : 'linear-gradient(to right, #ffebe9, #fff8c5, #dafbe1)',
          position: 'relative',
        })}
      >
        {/* Marker at comfort position */}
        <div
          className={css({
            position: 'absolute',
            top: '-2px',
            width: '4px',
            height: '16px',
            borderRadius: '2px',
            background: '#58a6ff',
            transition: 'left 0.15s ease',
          })}
          style={{ left: `calc(${pct}% - 2px)` }}
        />
      </div>
      <span
        className={css({
          fontSize: '11px',
          color: textSecondary,
          minWidth: '50px',
          textAlign: 'right',
        })}
      >
        {preview.min}–{preview.max}
      </span>
    </div>
  )
}

// =============================================================================
// Mode Config Card
// =============================================================================

function ModeConfigCard({
  mode,
  config,
  onChange,
  comfort,
  preview,
  isDark,
  cardBg,
  cardBorder,
  textPrimary,
  textSecondary,
  accentBlue,
  errorRed,
}: {
  mode: SessionPartType
  config: ModeScalingConfig
  onChange: (level: 'floor' | 'ceiling', bound: 'min' | 'max', value: number) => void
  comfort: number
  preview: { min: number; max: number }
  isDark: boolean
  cardBg: string
  cardBorder: string
  textPrimary: string
  textSecondary: string
  accentBlue: string
  errorRed: string
}) {
  const { emoji, label } = MODE_LABELS[mode]

  // Per-field validation
  const errors: string[] = []
  if (config.floor.min > config.floor.max) errors.push('Floor min must be ≤ floor max')
  if (config.ceiling.min > config.ceiling.max) errors.push('Ceiling min must be ≤ ceiling max')
  if (config.floor.min > config.ceiling.min) errors.push('Floor min must be ≤ ceiling min')
  if (config.floor.max > config.ceiling.max) errors.push('Floor max must be ≤ ceiling max')

  return (
    <div
      className={css({
        background: cardBg,
        border: `1px solid ${errors.length > 0 ? errorRed : cardBorder}`,
        borderRadius: '8px',
        padding: '20px',
      })}
      data-component={`mode-card-${mode}`}
    >
      <h3
        className={css({
          fontSize: '15px',
          fontWeight: '600',
          color: textPrimary,
          marginBottom: '16px',
        })}
      >
        {emoji} {label}
      </h3>

      <div className={css({ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '24px' })}>
        {/* Floor (Struggling) */}
        <div>
          <div
            className={css({
              fontSize: '12px',
              fontWeight: '600',
              color: textSecondary,
              marginBottom: '12px',
            })}
          >
            Struggling (0% comfort)
          </div>
          <NumberStepper
            label="Min terms"
            value={config.floor.min}
            onChange={(v) => onChange('floor', 'min', v)}
            isDark={isDark}
            textPrimary={textPrimary}
            textSecondary={textSecondary}
            cardBorder={cardBorder}
          />
          <NumberStepper
            label="Max terms"
            value={config.floor.max}
            onChange={(v) => onChange('floor', 'max', v)}
            isDark={isDark}
            textPrimary={textPrimary}
            textSecondary={textSecondary}
            cardBorder={cardBorder}
          />
        </div>

        {/* Ceiling (Mastered) */}
        <div>
          <div
            className={css({
              fontSize: '12px',
              fontWeight: '600',
              color: textSecondary,
              marginBottom: '12px',
            })}
          >
            Mastered (100% comfort)
          </div>
          <NumberStepper
            label="Min terms"
            value={config.ceiling.min}
            onChange={(v) => onChange('ceiling', 'min', v)}
            isDark={isDark}
            textPrimary={textPrimary}
            textSecondary={textSecondary}
            cardBorder={cardBorder}
          />
          <NumberStepper
            label="Max terms"
            value={config.ceiling.max}
            onChange={(v) => onChange('ceiling', 'max', v)}
            isDark={isDark}
            textPrimary={textPrimary}
            textSecondary={textSecondary}
            cardBorder={cardBorder}
          />
        </div>
      </div>

      {/* Preview bar */}
      <div
        className={css({ marginTop: '16px', display: 'flex', alignItems: 'center', gap: '8px' })}
      >
        <span className={css({ fontSize: '11px', color: textSecondary })}>
          {config.floor.min}–{config.floor.max}
        </span>
        <div
          className={css({
            flex: '1',
            height: '8px',
            borderRadius: '4px',
            background: isDark
              ? 'linear-gradient(to right, #1a3a2a, #238636)'
              : 'linear-gradient(to right, #ffebe9, #dafbe1)',
            position: 'relative',
          })}
        >
          <div
            className={css({
              position: 'absolute',
              top: '-4px',
              width: '3px',
              height: '16px',
              borderRadius: '2px',
              background: accentBlue,
              transition: 'left 0.15s ease',
            })}
            style={{ left: `calc(${Math.round(comfort * 100)}% - 1.5px)` }}
          />
        </div>
        <span className={css({ fontSize: '11px', color: textSecondary })}>
          {config.ceiling.min}–{config.ceiling.max}
        </span>
        <span
          className={css({
            fontSize: '12px',
            fontWeight: '600',
            color: accentBlue,
            marginLeft: '4px',
          })}
        >
          {preview.min}–{preview.max}
        </span>
      </div>

      {/* Errors */}
      {errors.length > 0 && (
        <div className={css({ marginTop: '12px', fontSize: '12px', color: errorRed })}>
          {errors.map((err) => (
            <div key={err}>{err}</div>
          ))}
        </div>
      )}
    </div>
  )
}

// =============================================================================
// Number Stepper
// =============================================================================

function NumberStepper({
  label,
  value,
  onChange,
  isDark,
  textPrimary,
  textSecondary,
  cardBorder,
}: {
  label: string
  value: number
  onChange: (value: number) => void
  isDark: boolean
  textPrimary: string
  textSecondary: string
  cardBorder: string
}) {
  return (
    <div
      className={css({
        display: 'flex',
        alignItems: 'center',
        gap: '8px',
        marginBottom: '8px',
      })}
    >
      <span className={css({ fontSize: '12px', color: textSecondary, minWidth: '70px' })}>
        {label}:
      </span>
      <div className={css({ display: 'flex', alignItems: 'center', gap: '0' })}>
        <button
          onClick={() => onChange(Math.max(2, value - 1))}
          className={css({
            width: '28px',
            height: '28px',
            border: `1px solid ${cardBorder}`,
            borderRadius: '4px 0 0 4px',
            background: isDark ? '#21262d' : '#f6f8fa',
            color: textPrimary,
            fontSize: '14px',
            cursor: value <= 2 ? 'not-allowed' : 'pointer',
            opacity: value <= 2 ? '0.4' : '1',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
          })}
          disabled={value <= 2}
          data-action="decrement"
        >

        </button>
        <input
          type="number"
          min={2}
          value={value}
          onChange={(e) => {
            const v = parseInt(e.target.value, 10)
            if (!isNaN(v)) onChange(Math.max(2, v))
          }}
          className={css({
            width: '44px',
            height: '28px',
            border: `1px solid ${cardBorder}`,
            borderLeft: 'none',
            borderRight: 'none',
            background: isDark ? '#0d1117' : '#fff',
            color: textPrimary,
            textAlign: 'center',
            fontSize: '13px',
            fontWeight: '600',
            outline: 'none',
            appearance: 'textfield',
          })}
          data-element="stepper-input"
        />
        <button
          onClick={() => onChange(value + 1)}
          className={css({
            width: '28px',
            height: '28px',
            border: `1px solid ${cardBorder}`,
            borderRadius: '0 4px 4px 0',
            background: isDark ? '#21262d' : '#f6f8fa',
            color: textPrimary,
            fontSize: '14px',
            cursor: 'pointer',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
          })}
          data-action="increment"
        >
          +
        </button>
      </div>
    </div>
  )
}

// =============================================================================
// How It Works
// =============================================================================

function HowItWorks({
  isDark,
  cardBg,
  cardBorder,
  textPrimary,
  textSecondary,
}: {
  isDark: boolean
  cardBg: string
  cardBorder: string
  textPrimary: string
  textSecondary: string
}) {
  const [open, setOpen] = useState(false)

  return (
    <div className={css({ marginTop: '32px' })} data-component="how-it-works">
      <button
        onClick={() => setOpen(!open)}
        className={css({
          display: 'flex',
          alignItems: 'center',
          gap: '8px',
          padding: '0',
          border: 'none',
          background: 'none',
          color: textSecondary,
          fontSize: '14px',
          fontWeight: '500',
          cursor: 'pointer',
        })}
        data-action="toggle-how-it-works"
      >
        <span
          style={{
            transform: open ? 'rotate(90deg)' : 'rotate(0deg)',
            transition: 'transform 0.15s',
          }}
        >

        </span>
        How It Works
      </button>

      {open && (
        <div
          className={css({
            marginTop: '12px',
            padding: '20px',
            background: cardBg,
            border: `1px solid ${cardBorder}`,
            borderRadius: '8px',
            fontSize: '13px',
            lineHeight: '1.7',
            color: textSecondary,
          })}
        >
          <ol
            className={css({
              paddingLeft: '20px',
              margin: '0',
              display: 'flex',
              flexDirection: 'column',
              gap: '8px',
            })}
          >
            <li>
              <strong className={css({ color: textPrimary })}>BKT</strong> tracks per-skill mastery
              (pKnown) from problem history, independently per mode.
            </li>
            <li>
              <strong className={css({ color: textPrimary })}>Comfort level</strong> (0–1)
              aggregates pKnown across practicing skills.
              <ul className={css({ paddingLeft: '20px', marginTop: '4px' })}>
                <li>Session mode scales: remediation ×0.6, progression ×0.85, maintenance ×1.0</li>
                <li>Problem length preference shifts: shorter −0.3, recommended ±0, longer +0.2</li>
              </ul>
            </li>
            <li>
              <strong className={css({ color: textPrimary })}>This config</strong> defines term
              counts at comfort=0 (floor) vs comfort=1 (ceiling).
            </li>
            <li>
              <strong className={css({ color: textPrimary })}>Linear interpolation</strong> between
              floor and ceiling:{' '}
              <code
                className={css({
                  fontSize: '12px',
                  background: isDark ? '#21262d' : '#f0f0f0',
                  padding: '1px 4px',
                  borderRadius: '3px',
                })}
              >
                round(floor + (ceiling - floor) × comfort)
              </code>
            </li>
            <li>
              Problem generator picks a random term count within the resulting {'{'} min, max {'}'}{' '}
              range.
            </li>
          </ol>
          <div
            className={css({
              marginTop: '16px',
              padding: '12px',
              background: isDark ? '#0d1117' : '#f6f8fa',
              borderRadius: '6px',
              fontSize: '12px',
              fontFamily: 'monospace',
            })}
          >
            <strong>Example at 30% comfort on Abacus (defaults):</strong>
            <br />
            min = round(2 + (4−2) × 0.3) = 3
            <br />
            max = round(3 + (8−3) × 0.3) = 5
            <br />→ problems have 3–5 terms
          </div>
        </div>
      )}
    </div>
  )
}