All files / web/src/components/toys/number-line/talkToNumber useRealtimeVoice.ts

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

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           
'use client'

/**
 * Number-line voice call hook — rebuilt on the shared voice framework.
 *
 * This hook wraps `useVoiceCall` from `@/lib/voice` and layers all the
 * number-line domain logic on top: conference calls, transfers,
 * explorations, games, story evolution, player identification, etc.
 *
 * The shared framework handles: WebRTC, audio, microphone, ring tone,
 * mode management, timer, data channel routing, and cleanup.
 *
 * This file handles: domain-specific tool dispatch (returning ToolCallResult),
 * conference/speaker state, transfer logic, exploration narration,
 * game state, session history, and the domain-specific public API.
 */

import { useCallback, useRef, useState, useMemo } from 'react'
import { createId } from '@paralleldrive/cuid2'
import { useVoiceCall } from '@/lib/voice/useVoiceCall'
import type {
  VoiceSessionConfig,
  ToolCallResult,
  CallState as BaseCallState,
  UseVoiceCallReturn,
} from '@/lib/voice/types'
import { sendSystemMessage as sendSystemMessageHelper } from '@/lib/voice/toolCallHelpers'
import type { GeneratedScenario, TranscriptEntry } from './generateScenario'
import type { ChildProfile } from './childProfile'
import { EXPLORATION_IDS, CONSTANT_IDS } from './explorationRegistry'
import { GAME_MAP } from './gameRegistry'
import { resolveMode, type ModeId, type ModeContext, type SessionActivity } from './sessionModes'
import { getTraitSummary } from './generateNumberPersonality'
import type {
  MomentSnapshot,
  PostcardManifest,
  RankedMoment,
} from '@/db/schema/number-line-postcards'

/** A moment bookmarked silently by the agent during the call. */
export interface MarkedMoment {
  caption: string
  category: 'question' | 'discovery' | 'game' | 'exploration' | 'conversation' | 'conference'
  significance: number
  snapshot: MomentSnapshot
  transcriptExcerpt: string
  timestampMs: number
}

export type CallState = BaseCallState | 'transferring'

// ── Levenshtein fuzzy matching for identify_caller ──────────────────────────

function levenshtein(a: string, b: string): number {
  const m = a.length
  const n = b.length
  const dp: number[] = Array.from({ length: n + 1 }, (_, i) => i)
  for (let i = 1; i <= m; i++) {
    let prev = dp[0]
    dp[0] = i
    for (let j = 1; j <= n; j++) {
      const temp = dp[j]
      dp[j] = a[i - 1] === b[j - 1] ? prev : 1 + Math.min(prev, dp[j], dp[j - 1])
      prev = temp
    }
  }
  return dp[n]
}

function fuzzyMatchPlayer(
  input: string,
  players: Array<{ id: string; name: string; emoji: string }>
): { id: string; name: string } | null {
  if (players.length === 0) return null
  const norm = input.toLowerCase().trim()
  if (!norm) return null
  const exact = players.find((p) => p.name.toLowerCase() === norm)
  if (exact) return exact
  const prefixMatches = players.filter((p) => p.name.toLowerCase().startsWith(norm))
  if (prefixMatches.length === 1) return prefixMatches[0]
  let bestDist = Infinity
  let bestPlayer: { id: string; name: string } | null = null
  for (const p of players) {
    const dist = levenshtein(norm, p.name.toLowerCase())
    if (dist < bestDist) {
      bestDist = dist
      bestPlayer = p
    }
  }
  if (bestPlayer) {
    const maxLen = Math.max(norm.length, bestPlayer.name.length)
    if (bestDist <= Math.ceil(maxLen * 0.4)) return bestPlayer
  }
  return null
}

/** A single mode transition recorded for debug overlay. */
export interface ModeTransition {
  from: ModeId | 'idle'
  to: ModeId
  action: string
  timestamp: number
  tools: string[]
}

/** Debug info exposed to the UI for the voice state machine overlay. */
export interface ModeDebugInfo {
  current: ModeId
  previous: ModeId | null
  transitions: ModeTransition[]
}

/** A record of a completed call, preserved across calls within a session. */
interface CallRecord {
  number: number
  conferenceNumbers: number[]
  transcripts: TranscriptEntry[]
  scenario: GeneratedScenario | null
  timestamp: number
}

function formatCallHistory(history: CallRecord[], currentNumber: number): string {
  const lines: string[] = [
    '[System — The child has had previous conversations this session. Here is what happened:\n',
  ]
  for (const record of history.slice(-5)) {
    const isSelf = record.number === currentNumber
    const header = isSelf
      ? `=== Your earlier call (you are ${record.number}) ===`
      : `=== Child's call with Number ${record.number} ===`
    lines.push(header)
    const transcripts = record.transcripts.slice(-10)
    for (const t of transcripts) {
      const speaker = t.role === 'child' ? 'Child' : `Number ${record.number}`
      lines.push(`${speaker}: "${t.text}"`)
    }
    lines.push('')
  }
  const calledBefore = history.some((r) => r.number === currentNumber)
  if (calledBefore) {
    lines.push(
      'The child is calling you AGAIN. Greet them warmly — "Hey, you\'re back!" ' +
        'Pick up where you left off naturally. Reference what you discussed before. ' +
        'If they talked to other numbers, you may have heard about it on the number line.]'
    )
  } else {
    lines.push(
      "This is a new call to a number the child hasn't called before. " +
        'If the child mentions talking to other numbers, you may have heard about it on the number line.]'
    )
  }
  return lines.join('\n')
}

const BASE_TIMEOUT_MS = 2 * 60 * 1000
const EXTENSION_MS = 2 * 60 * 1000
const WARNING_BEFORE_END_MS = 15 * 1000
const HANG_UP_DELAY_MS = 2000
const TRANSFER_DELAY_MS = 1500

interface UseRealtimeVoiceOptions {
  onTransfer?: (targetNumber: number) => void
  onStartExploration?: (constantId: string) => void
  onPauseExploration?: () => void
  onResumeExploration?: () => void
  onSeekExploration?: (segmentIndex: number) => void
  onEndExploration?: () => void
  onLookAt?: (center: number, range: number) => void
  onIndicate?: (
    numbers: number[],
    range?: { from: number; to: number },
    durationSeconds?: number,
    persistent?: boolean
  ) => void
  onGameStart?: (gameId: string, params: Record<string, unknown>) => void
  onGameEnd?: (gameId: string) => void
  onSetLabelStyle?: (scale: number, minOpacity: number) => void
  isExplorationActiveRef?: React.RefObject<boolean>
  onPlayerIdentified?: (playerId: string) => void
  /** Returns the current number line scene snapshot for moment capture. */
  getSceneSnapshot?: () => SceneSnapshot
}

export interface SceneSnapshot {
  viewport: { center: number; pixelsPerUnit: number }
  indicator?: { numbers: number[]; range?: { from: number; to: number } }
  gameTarget?: { value: number; emoji: string }
  activeExplorationId?: string | null
  demoProgress?: number
}

interface DialOptions {
  recommendedExplorations?: string[]
  playerId?: string
  availablePlayers?: Array<{ id: string; name: string; emoji: string }>
}

interface UseRealtimeVoiceReturn {
  state: CallState
  error: string | null
  errorCode: string | null
  dial: (number: number, options?: DialOptions) => void
  profileFailed: boolean
  hangUp: () => void
  timeRemaining: number | null
  isSpeaking: boolean
  transferTarget: number | null
  conferenceNumbers: number[]
  currentSpeaker: number | null
  removeFromCall: (numberToRemove: number) => void
  sendSystemMessage: (text: string, promptResponse?: boolean) => void
  setNarrationPlaying: (playing: boolean) => void
  currentInstructions: string | null
  modeDebug: ModeDebugInfo
}

export function useRealtimeVoice(options?: UseRealtimeVoiceOptions): UseRealtimeVoiceReturn {
  // Stable refs for callbacks
  const onTransferRef = useRef(options?.onTransfer)
  onTransferRef.current = options?.onTransfer
  const onStartExplorationRef = useRef(options?.onStartExploration)
  onStartExplorationRef.current = options?.onStartExploration
  const onPauseExplorationRef = useRef(options?.onPauseExploration)
  onPauseExplorationRef.current = options?.onPauseExploration
  const onResumeExplorationRef = useRef(options?.onResumeExploration)
  onResumeExplorationRef.current = options?.onResumeExploration
  const onSeekExplorationRef = useRef(options?.onSeekExploration)
  onSeekExplorationRef.current = options?.onSeekExploration
  const onEndExplorationRef = useRef(options?.onEndExploration)
  onEndExplorationRef.current = options?.onEndExploration
  const onLookAtRef = useRef(options?.onLookAt)
  onLookAtRef.current = options?.onLookAt
  const onIndicateRef = useRef(options?.onIndicate)
  onIndicateRef.current = options?.onIndicate
  const onGameStartRef = useRef(options?.onGameStart)
  onGameStartRef.current = options?.onGameStart
  const onGameEndRef = useRef(options?.onGameEnd)
  onGameEndRef.current = options?.onGameEnd
  const onSetLabelStyleRef = useRef(options?.onSetLabelStyle)
  onSetLabelStyleRef.current = options?.onSetLabelStyle
  const onPlayerIdentifiedRef = useRef(options?.onPlayerIdentified)
  onPlayerIdentifiedRef.current = options?.onPlayerIdentified
  const getSceneSnapshotRef = useRef(options?.getSceneSnapshot)
  getSceneSnapshotRef.current = options?.getSceneSnapshot
  const isExplorationActiveRef = options?.isExplorationActiveRef

  // ── Domain-specific state ──
  const [transferTarget, setTransferTarget] = useState<number | null>(null)
  const [profileFailed, setProfileFailed] = useState(false)
  const [conferenceNumbers, setConferenceNumbers] = useState<number[]>([])
  const conferenceNumbersRef = useRef<number[]>([])
  const [currentSpeaker, setCurrentSpeaker] = useState<number | null>(null)
  const currentSpeakerRef = useRef<number | null>(null)
  const pendingSpeakerRef = useRef<number | null>(null)
  const pendingSpeakerTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
  const activePlayerIdRef = useRef<string | undefined>(undefined)
  const availablePlayersRef = useRef<Array<{ id: string; name: string; emoji: string }>>([])
  const activeGameIdRef = useRef<string | null>(null)
  const gameStateRef = useRef<unknown>(null)
  const sessionActivityRef = useRef<SessionActivity>({ gamesPlayed: [], explorationsLaunched: [] })
  const markedMomentsRef = useRef<MarkedMoment[]>([])
  const postcardSentRef = useRef(false)
  const sessionIdRef = useRef<string>(createId())
  const sharedHistoryRef = useRef<import('@/lib/number-line/shared-history').SharedHistory | null>(
    null
  )
  const callStartTimeRef = useRef(0)
  const narrationPlayingRef = useRef(false)
  const lastResumeTimestampRef = useRef(0)
  const pendingExplorationRef = useRef<
    { type: 'start'; constantId: string } | { type: 'resume' } | null
  >(null)
  const responseCreatedMsRef = useRef(0)

  // Refs for voiceCall methods — set after hook is created (avoids circular dep with config)
  const extendTimerRef = useRef<(() => boolean) | null>(null)
  const voiceCallRef = useRef<UseVoiceCallReturn | null>(null)

  // Scenario + transcript + call state
  const childProfileRef = useRef<ChildProfile | undefined>(undefined)
  const profileFailedRef = useRef(false)
  const scenarioRef = useRef<GeneratedScenario | null>(null)
  const transcriptsRef = useRef<TranscriptEntry[]>([])
  const calledNumberRef = useRef<number>(0)
  const sessionHistoryRef = useRef<CallRecord[]>([])
  const extensionUsedRef = useRef(false) // Mirrors framework's extension state for ModeContext
  const windingDownRequestedRef = useRef(false)
  const goodbyeRequestedRef = useRef(false)
  const childHasSpokenRef = useRef(false)
  const familiarizingResponseCountRef = useRef(0)
  const momentNudgeSentRef = useRef(false)
  const defaultModeResponseCountRef = useRef(0)

  // Domain-specific call state (extends base CallState with 'transferring')
  const [domainState, setDomainState] = useState<'transferring' | null>(null)
  const transferTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)

  // Recommended explorations for the current dial
  const recommendedExplorationsRef = useRef<string[] | undefined>(undefined)

  const setPendingSpeaker = useCallback((speaker: number) => {
    pendingSpeakerRef.current = speaker
    if (pendingSpeakerTimerRef.current) clearTimeout(pendingSpeakerTimerRef.current)
    pendingSpeakerTimerRef.current = setTimeout(() => {
      pendingSpeakerTimerRef.current = null
      if (pendingSpeakerRef.current === speaker) {
        pendingSpeakerRef.current = null
        currentSpeakerRef.current = speaker
        setCurrentSpeaker(speaker)
      }
    }, 1000)
  }, [])

  /** Build a ModeContext from current refs. */
  const buildModeContext = useCallback(
    (): ModeContext => ({
      calledNumber: calledNumberRef.current,
      scenario: scenarioRef.current,
      childProfile: childProfileRef.current,
      profileFailed: profileFailedRef.current,
      conferenceNumbers: conferenceNumbersRef.current,
      currentSpeaker: currentSpeakerRef.current,
      activeGameId: activeGameIdRef.current,
      gameState: gameStateRef.current,
      availablePlayers: availablePlayersRef.current,
      currentInstructions: null,
      sessionActivity: sessionActivityRef.current,
      extensionAvailable: !extensionUsedRef.current,
      momentCount: markedMomentsRef.current.length,
      postcardSent: postcardSentRef.current,
      sharedHistory: sharedHistoryRef.current,
    }),
    []
  )

  // ── Session end helper (triggers moment cull) ──
  const sessionEndedRef = useRef(false)
  const endVoiceSession = useCallback(() => {
    if (sessionEndedRef.current) return
    sessionEndedRef.current = true
    fetch('/api/number-line/sessions/end', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ sessionId: sessionIdRef.current }),
    }).catch((err) => console.warn('[moments] session end failed:', err))
  }, [])

  // ── Tool call handler ──
  // Returns ToolCallResult for each tool, or null for unhandled.
  // NOTE: Many number-line tools need direct data channel access for async patterns
  // (identify_caller, evolve_story). For these, we use the dc ref from the shared hook.
  const onToolCall = useCallback(
    (name: string, args: Record<string, unknown>, _ctx: ModeContext): ToolCallResult | null => {
      // request_more_time
      if (name === 'request_more_time') {
        const extended = extendTimerRef.current?.()
        if (!extended) {
          return { output: { success: false, error: 'No extension available.' } }
        }
        extensionUsedRef.current = true
        const shouldExitMode = windingDownRequestedRef.current
        windingDownRequestedRef.current = false
        return {
          output: {
            success: true,
            message:
              'Time extended. Do NOT mention this to the child — just keep the conversation going naturally.',
          },
          exitMode: shouldExitMode || undefined,
        }
      }

      // hang_up — route through farewell mode if there are unsent moments
      if (name === 'hang_up') {
        if (markedMomentsRef.current.length > 0 && !postcardSentRef.current) {
          return {
            output: {
              success: true,
              message: 'Before you go, you have a chance to send the child a postcard.',
            },
            enterMode: 'farewell',
          }
        }
        endVoiceSession()
        return { output: { success: true }, isHangUp: true }
      }

      // skip_postcard — child declined or call wasn't postcard-worthy
      if (name === 'skip_postcard') {
        return {
          output: { success: true },
          enterMode: 'hanging_up',
        }
      }

      // transfer_call
      if (name === 'transfer_call') {
        const targetNumber = Number(args.target_number)
        if (!isFinite(targetNumber)) {
          return { output: { success: false, error: 'Invalid number' } }
        }
        return {
          output: { success: true, message: `Transferring to ${targetNumber}` },
          isTransfer: true,
          transferTarget: targetNumber,
          promptResponse: false,
        }
      }

      // add_to_call (conference)
      if (name === 'add_to_call') {
        const raw = args.target_numbers
        if (!Array.isArray(raw) || raw.length === 0) {
          return { output: { success: false, error: 'Invalid target_numbers array' } }
        }
        const targetNumbers = raw.map((v: unknown) => Number(v)).filter(isFinite)
        if (targetNumbers.length === 0) {
          return { output: { success: false, error: 'Invalid target_numbers array' } }
        }

        const existing = new Set(conferenceNumbersRef.current)
        const newNumbers = targetNumbers.filter((n) => !existing.has(n))
        if (newNumbers.length === 0) {
          return {
            output: { success: true, message: 'All those numbers are already on the call!' },
          }
        }

        const updated = [...conferenceNumbersRef.current, ...newNumbers]
        conferenceNumbersRef.current = updated
        setConferenceNumbers(updated)
        setPendingSpeaker(newNumbers[0])
        currentSpeakerRef.current = newNumbers[0]

        return {
          output: { success: true, message: `${newNumbers.join(', ')} joined the call!` },
          enterMode: 'conference',
          promptResponse: false, // We'll prompt manually after injecting intro text
        }
      }

      // switch_speaker
      if (name === 'switch_speaker') {
        const targetNumber = Number(args.number)
        if (!isFinite(targetNumber)) {
          return { output: { success: false, error: 'Invalid number' } }
        }
        if (!conferenceNumbersRef.current.includes(targetNumber)) {
          return { output: { success: false, error: `${targetNumber} is not on the call` } }
        }
        setPendingSpeaker(targetNumber)
        currentSpeakerRef.current = targetNumber
        return { output: { success: true, now_speaking_as: targetNumber } }
      }

      // start_exploration
      if (name === 'start_exploration') {
        const constantId = String(args.constant_id)
        if (!EXPLORATION_IDS.has(constantId)) {
          return { output: { success: false, error: 'Invalid constant_id' } }
        }

        // Tour explorations — auto-hang-up
        if (!CONSTANT_IDS.has(constantId)) {
          onStartExplorationRef.current?.(constantId)
          endVoiceSession()
          return { output: { success: true }, isHangUp: true }
        }

        sessionActivityRef.current.explorationsLaunched.push(constantId)
        pendingExplorationRef.current = { type: 'start', constantId }
        return {
          output: {
            success: true,
            message: `Exploration of ${constantId} is ready but PAUSED. Give the child a brief intro — match their energy level — then call resume_exploration to start.`,
            companion_rules:
              'Once the animation is playing: a pre-recorded narrator tells the story. You stay SILENT during playback. ' +
              'You will receive context messages showing what the narrator is saying. ' +
              'If the child speaks, the animation pauses automatically — answer their question, then call resume_exploration. ' +
              'If the child seems disengaged, offer choices: keep watching, see a different one, or do something else. ' +
              'One brief reaction when it finishes, then move on. Do NOT narrate, announce segments, or repeat what the narrator says.',
          },
          enterMode: 'exploration',
        }
      }

      // pause_exploration
      if (name === 'pause_exploration') {
        narrationPlayingRef.current = false
        onPauseExplorationRef.current?.()
        return { output: { success: true, message: 'Exploration paused' } }
      }

      // resume_exploration
      if (name === 'resume_exploration') {
        pendingExplorationRef.current = { type: 'resume' }
        return {
          output: {
            success: true,
            message:
              'Exploration resumed. The narrator is speaking now — stay completely silent until the child speaks or the exploration ends.',
          },
          promptResponse: false,
        }
      }

      // seek_exploration
      if (name === 'seek_exploration') {
        const segNum = Number(args.segment_number)
        if (!isFinite(segNum) || segNum < 1) {
          return { output: { success: false, error: 'Invalid segment_number' } }
        }
        onSeekExplorationRef.current?.(segNum - 1)
        return { output: { success: true, message: `Jumped to segment ${segNum} (paused)` } }
      }

      // end_exploration
      if (name === 'end_exploration') {
        narrationPlayingRef.current = false
        onEndExplorationRef.current?.()
        return {
          output: {
            success: true,
            message:
              "Exploration stopped. You're back in conversation mode — full tools available.",
          },
          exitMode: true,
        }
      }

      // look_at
      if (name === 'look_at') {
        const center = Number(args.center)
        if (!isFinite(center)) {
          return { output: { success: false, error: 'Invalid center value' } }
        }
        const range = Number(args.range) || 20
        onLookAtRef.current?.(center, Math.abs(range))
        return { output: { success: true, message: `Looking at ${center} (range ${range})` } }
      }

      // evolve_story
      if (name === 'evolve_story') {
        if (!scenarioRef.current) {
          return { output: { success: false, error: 'No active scenario to evolve' } }
        }
        const recent = transcriptsRef.current.slice(-10)
        const asyncResult = fetch('/api/realtime/evolve', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            number: calledNumberRef.current,
            scenario: scenarioRef.current,
            recentTranscripts: recent,
            conferenceNumbers: conferenceNumbersRef.current,
          }),
        })
          .then((res) =>
            res.ok ? res.json() : Promise.reject(new Error(`API error ${res.status}`))
          )
          .then((data) => {
            if (!data.evolution) {
              return {
                text: '[System: The story is flowing well — no twist needed right now. Keep going with the current thread.]',
              }
            }
            const { development, newTension, suggestion } = data.evolution
            return {
              text: `[System: Story evolution — Development: ${development}. New tension: ${newTension}. Suggestion: ${suggestion}. Weave this in naturally.]`,
            }
          })
        return {
          output: { success: true, message: 'Generating story evolution...' },
          asyncResult,
          promptResponse: false,
        }
      }

      // identify_caller
      if (name === 'identify_caller') {
        const inputName = args.name as string | undefined
        const inputId = args.player_id as string | undefined
        let playerId: string | undefined

        if (inputName && typeof inputName === 'string') {
          const match = fuzzyMatchPlayer(inputName, availablePlayersRef.current)
          if (!match) {
            return {
              output: {
                success: false,
                error: `No matching player found for "${inputName}". Known names: ${availablePlayersRef.current.map((p) => p.name).join(', ')}. Ask the child to repeat their name.`,
              },
            }
          }
          playerId = match.id
        } else if (inputId && typeof inputId === 'string') {
          playerId = inputId
        } else {
          return { output: { success: false, error: 'Pass the name you heard from the child.' } }
        }

        activePlayerIdRef.current = playerId

        const asyncResult = fetch('/api/realtime/profile', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ playerId }),
        })
          .then((res) =>
            res.ok ? res.json() : Promise.reject(new Error(`API error ${res.status}`))
          )
          .then((data) => {
            if (data.failed || !data.profile) {
              return {
                text: "[System: Couldn't load their profile, but that's okay — continue naturally.]",
              }
            }
            const profile = data.profile as ChildProfile
            childProfileRef.current = profile
            const namePart = profile.name ? `This is ${profile.name}` : 'Identified the caller'
            const agePart = profile.age != null ? `, age ${profile.age}` : ''
            const focusPart = profile.currentFocus
              ? `. Currently learning: ${profile.currentFocus}`
              : ''
            onPlayerIdentifiedRef.current?.(playerId!)
            return {
              text: `[System: ${namePart}${agePart}${focusPart}. Personalize the conversation for them!]`,
            }
          })

        return {
          output: { success: true, message: 'Looking up the caller...' },
          asyncResult,
          promptResponse: false,
        }
      }

      // indicate
      if (name === 'indicate') {
        const numbers: number[] = Array.isArray(args.numbers)
          ? ((args.numbers as unknown[]).filter(
              (v) => typeof v === 'number' && isFinite(v as number)
            ) as number[])
          : []
        let range: { from: number; to: number } | undefined
        if (args.range && typeof args.range === 'object') {
          const r = args.range as Record<string, unknown>
          if (isFinite(Number(r.from)) && isFinite(Number(r.to))) {
            range = { from: Number(r.from), to: Number(r.to) }
          }
        }
        if (numbers.length === 0 && !range) {
          return {
            output: {
              success: false,
              error: 'Must provide at least numbers (array) or range ({ from, to })',
            },
          }
        }
        const durationSeconds =
          typeof args.duration_seconds === 'number' &&
          isFinite(args.duration_seconds) &&
          args.duration_seconds > 0
            ? args.duration_seconds
            : undefined
        const persistent = args.persistent === true
        onIndicateRef.current?.(numbers, range, durationSeconds, persistent)
        return {
          output: {
            success: true,
            message: `Indicating ${numbers.length} numbers${range ? ` and range ${range.from}–${range.to}` : ''}${persistent ? ' (persistent)' : durationSeconds ? ` for ${durationSeconds}s` : ''}`,
          },
        }
      }

      // start_game
      if (name === 'start_game') {
        const gameId = String(args.game_id)
        const game = GAME_MAP.get(gameId)
        if (!game) {
          return {
            output: {
              success: false,
              error: `Unknown game: ${gameId}. Valid games: ${[...GAME_MAP.keys()].join(', ')}`,
            },
          }
        }
        if (activeGameIdRef.current) {
          return {
            output: {
              success: false,
              error: `A game is already active (${activeGameIdRef.current}). End it first with end_game.`,
            },
          }
        }
        const result = game.onStart?.(args as Record<string, unknown>) ?? {
          agentMessage: `${game.name} started!`,
        }
        activeGameIdRef.current = gameId
        gameStateRef.current = result.state ?? null
        sessionActivityRef.current.gamesPlayed.push(gameId)
        onGameStartRef.current?.(gameId, args)
        if (result.indicate) {
          onIndicateRef.current?.(
            result.indicate.numbers,
            undefined,
            undefined,
            result.indicate.persistent
          )
        }
        return {
          output: { success: true, message: result.agentMessage },
          enterMode: 'game',
        }
      }

      // end_game
      if (name === 'end_game') {
        const gameId = activeGameIdRef.current
        if (!gameId) {
          return { output: { success: true, message: 'No game is currently active.' } }
        }
        const game = GAME_MAP.get(gameId)
        activeGameIdRef.current = null
        gameStateRef.current = null
        onGameEndRef.current?.(gameId)
        return {
          output: { success: true, message: `${game?.name ?? gameId} game ended.` },
          exitMode: true,
        }
      }

      // set_number_line_style
      if (name === 'set_number_line_style') {
        const scale = Math.max(
          0.5,
          Math.min(
            3,
            typeof args.label_scale === 'number' && isFinite(args.label_scale)
              ? args.label_scale
              : 1
          )
        )
        const minOpacity = Math.max(
          0,
          Math.min(
            1,
            typeof args.label_min_opacity === 'number' && isFinite(args.label_min_opacity)
              ? args.label_min_opacity
              : 0
          )
        )
        onSetLabelStyleRef.current?.(scale, minOpacity)
        return {
          output: {
            success: true,
            message: `Label style set: scale=${scale}, minOpacity=${minOpacity}`,
          },
        }
      }

      // Game session tools (delegated to game handler)
      if (activeGameIdRef.current) {
        const game = GAME_MAP.get(activeGameIdRef.current)
        if (game?.onToolCall && game.sessionTools?.some((t) => t.name === name)) {
          try {
            const result = game.onToolCall(gameStateRef.current, name, args)
            gameStateRef.current = result.state
            if (result.indicate) {
              onIndicateRef.current?.(
                result.indicate.numbers,
                undefined,
                undefined,
                result.indicate.persistent
              )
            }
            return { output: { success: true, message: result.agentMessage } }
          } catch (err) {
            return {
              output: {
                success: false,
                error: err instanceof Error ? err.message : 'Game tool call failed',
              },
            }
          }
        }
      }

      // mark_moment — silently bookmark a memorable moment
      if (name === 'mark_moment') {
        console.log('[postcard] mark_moment called:', args)
        const caption = String(args.caption ?? '')
        const category = String(args.category ?? 'conversation') as MarkedMoment['category']
        const significance = typeof args.significance === 'number' ? args.significance : 5

        // Capture full scene snapshot (viewport + indicator + game target + exploration)
        const scene = getSceneSnapshotRef.current?.() ?? {
          viewport: { center: 0, pixelsPerUnit: 50 },
        }

        // Capture recent transcript excerpt (last 4 lines)
        const recentTranscripts = transcriptsRef.current.slice(-4)
        const transcriptExcerpt = recentTranscripts
          .map((t) => `${t.role === 'child' ? 'Child' : 'Number'}: "${t.text}"`)
          .join('\n')

        const moment: MarkedMoment = {
          caption,
          category,
          significance,
          snapshot: {
            viewport: scene.viewport,
            highlights: scene.indicator?.numbers,
            indicatorRange: scene.indicator?.range,
            activeGameId: activeGameIdRef.current,
            activeExplorationId: scene.activeExplorationId,
            demoProgress: scene.demoProgress,
            gameTarget: scene.gameTarget,
            conferenceNumbers:
              conferenceNumbersRef.current.length > 1
                ? [...conferenceNumbersRef.current]
                : undefined,
            timestamp: Date.now() - callStartTimeRef.current,
          },
          transcriptExcerpt,
          timestampMs: Date.now() - callStartTimeRef.current,
        }

        markedMomentsRef.current.push(moment)

        // Persist moment server-side (fire-and-forget for relationship history)
        const playerId = activePlayerIdRef.current
        if (playerId) {
          fetch('/api/number-line/moments', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
              playerId,
              callerNumber: calledNumberRef.current,
              sessionId: sessionIdRef.current,
              moment: {
                caption,
                category,
                significance,
                snapshot: moment.snapshot,
                transcriptExcerpt,
              },
            }),
          }).catch((err) => console.warn('[moments] persist failed:', err))
        }

        return { output: { success: true }, promptResponse: false }
      }

      // send_postcard — assemble manifest and POST to API
      if (name === 'send_postcard') {
        console.log(
          '[postcard] send_postcard called:',
          args,
          'moments:',
          markedMomentsRef.current.length
        )
        const sessionSummary = String(args.session_summary ?? '')
        const moments = markedMomentsRef.current
        if (moments.length === 0) {
          return {
            output: { success: false, error: 'No moments have been marked.' },
          }
        }

        // Rank by significance, take top 4
        const ranked: RankedMoment[] = [...moments]
          .sort((a, b) => b.significance - a.significance)
          .slice(0, 4)
          .map((m, i) => ({
            rank: i + 1,
            caption: m.caption,
            category: m.category,
            snapshot: m.snapshot,
            transcriptExcerpt: m.transcriptExcerpt,
          }))

        const child = childProfileRef.current
        const manifest: PostcardManifest = {
          callerNumber: calledNumberRef.current,
          callerPersonality: getTraitSummary(calledNumberRef.current),
          childName: child?.name ?? 'Friend',
          childAge: child?.age,
          childEmoji: child?.emoji ?? '',
          moments: ranked,
          sessionSummary,
        }

        postcardSentRef.current = true

        // Fire and forget — POST to API (userId resolved server-side via session)
        const playerId = activePlayerIdRef.current
        fetch('/api/postcards', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ playerId, sessionId: sessionIdRef.current, manifest }),
        }).catch((err) => {
          console.warn('[postcard] POST failed:', err)
        })

        return {
          output: { sent: true, message: 'Postcard is on its way!' },
          enterMode: 'hanging_up',
        }
      }

      return null // unhandled
    },
    [setPendingSpeaker, endVoiceSession]
  )

  const onResponseDone = useCallback((_ctx: ModeContext, currentModeId: string): string | null => {
    if (currentModeId === 'answering' && childHasSpokenRef.current) {
      if (childProfileRef.current) {
        console.log('[postcard] transitioning answering → default (has profile)')
        return 'default'
      }
      console.log('[postcard] transitioning answering → familiarizing')
      return 'familiarizing'
    }
    if (currentModeId === 'familiarizing') {
      familiarizingResponseCountRef.current++
      if (familiarizingResponseCountRef.current >= 4) {
        console.log('[postcard] transitioning familiarizing → default')
        return 'default'
      }
    }
    return null
  }, [])

  const onChildSpeech = useCallback(
    (transcript: string) => {
      childHasSpokenRef.current = true
      const buf = transcriptsRef.current
      buf.push({ role: 'child', text: transcript })
      if (buf.length > 12) buf.shift()

      // Auto-pause exploration
      if (isExplorationActiveRef?.current && Date.now() - lastResumeTimestampRef.current > 3000) {
        narrationPlayingRef.current = false
        onPauseExplorationRef.current?.()
      }
    },
    [isExplorationActiveRef]
  )

  const onModelSpeech = useCallback((transcript: string) => {
    const buf = transcriptsRef.current
    buf.push({ role: 'number', text: transcript })
    if (buf.length > 12) buf.shift()
  }, [])

  // Build the modes map from the number-line session modes
  // We need to wrap them as VoiceMode<ModeContext>
  const modes = useMemo(() => {
    const modeIds: ModeId[] = [
      'answering',
      'familiarizing',
      'default',
      'conference',
      'exploration',
      'game',
      'winding_down',
      'farewell',
      'hanging_up',
    ]
    const map: Record<
      string,
      {
        id: string
        getInstructions: (ctx: ModeContext) => string
        getTools: (ctx: ModeContext) => {
          type: 'function'
          name: string
          description: string
          parameters: { type: 'object'; properties: Record<string, unknown>; required?: string[] }
        }[]
      }
    > = {}
    for (const id of modeIds) {
      map[id] = {
        id,
        getInstructions: (ctx: ModeContext) => resolveMode(id, ctx).instructions,
        getTools: (ctx: ModeContext) => resolveMode(id, ctx).tools,
      }
    }
    return map
  }, [])

  const config = useMemo(
    (): VoiceSessionConfig<ModeContext> => ({
      sessionEndpoint: '/api/realtime/session',
      buildContext: buildModeContext,
      initialModeId: 'answering',
      modes,
      onToolCall,
      onResponseDone,
      onChildSpeech,
      onModelSpeech,
      getSessionBody: () => ({
        number: calledNumberRef.current,
        ...(activePlayerIdRef.current && { playerId: activePlayerIdRef.current }),
        ...(sessionHistoryRef.current.some((r) => r.number === calledNumberRef.current) && {
          previousScenario: sessionHistoryRef.current
            .filter((r) => r.number === calledNumberRef.current)
            .pop()?.scenario,
        }),
        ...(recommendedExplorationsRef.current?.length && {
          recommendedExplorations: recommendedExplorationsRef.current,
        }),
        ...(availablePlayersRef.current.length > 0 && {
          availablePlayers: availablePlayersRef.current,
        }),
      }),
      onSessionCreated: (data) => {
        scenarioRef.current = (data.scenario as GeneratedScenario) ?? null
        childProfileRef.current = (data.childProfile as ChildProfile) ?? undefined
        if (data.profileFailed) {
          setProfileFailed(true)
          profileFailedRef.current = true
        }
      },
      onSessionEstablished: (dc) => {
        const history = sessionHistoryRef.current
        if (history.length > 0) {
          const historyText = formatCallHistory(history, calledNumberRef.current)
          sendSystemMessageHelper(dc, historyText)
        }
        // Set conference state
        const num = calledNumberRef.current
        conferenceNumbersRef.current = [num]
        setConferenceNumbers([num])
        currentSpeakerRef.current = num
        setCurrentSpeaker(num)
      },
      timer: {
        baseDurationMs: BASE_TIMEOUT_MS,
        extensionMs: EXTENSION_MS,
        warningBeforeEndMs: WARNING_BEFORE_END_MS,
        hangUpDelayMs: HANG_UP_DELAY_MS,
      },
      onTimeWarning: (dc) => {
        dc.send(
          JSON.stringify({
            type: 'conversation.item.create',
            item: {
              type: 'message',
              role: 'user',
              content: [
                {
                  type: 'input_text',
                  text: '[System: Only 15 seconds left. If the conversation is going well, silently call request_more_time. Otherwise give a gentle in-character hint that you might have to go soon — but do NOT mention timers, countdowns, or the time system directly.]',
                },
              ],
            },
          })
        )
        dc.send(JSON.stringify({ type: 'response.create' }))
      },
      onTimeExpired: (dc) => {
        if (!windingDownRequestedRef.current) {
          windingDownRequestedRef.current = true
          // Enter winding_down mode
          dc.send(
            JSON.stringify({
              type: 'session.update',
              session: resolveMode('winding_down', buildModeContext()),
            })
          )
          dc.send(JSON.stringify({ type: 'response.create' }))
        } else if (!goodbyeRequestedRef.current) {
          goodbyeRequestedRef.current = true
          // Route through farewell if there are moments and no postcard sent
          const ctx = buildModeContext()
          const nextMode = ctx.momentCount > 0 && !ctx.postcardSent ? 'farewell' : 'hanging_up'
          dc.send(
            JSON.stringify({
              type: 'session.update',
              session: resolveMode(nextMode, ctx),
            })
          )
          dc.send(JSON.stringify({ type: 'response.create' }))
        }
        // Phase 3 handled by the framework (force hangup)
      },
      onResponseDoneRaw: (dc, msg, currentModeId) => {
        // Nudge the model to use mark_moment after a few exchanges in default mode
        if (currentModeId === 'default' && !momentNudgeSentRef.current) {
          defaultModeResponseCountRef.current++
          if (defaultModeResponseCountRef.current >= 3 && markedMomentsRef.current.length === 0) {
            momentNudgeSentRef.current = true
            sendSystemMessageHelper(
              dc,
              '[System: REMINDER — You have not called mark_moment yet. You MUST call mark_moment to bookmark memorable moments during the conversation. Call it now for the most recent noteworthy exchange, and continue calling it throughout the call. The child will not hear or see this tool call.]'
            )
            console.log(
              '[postcard] sent mark_moment nudge after %d responses with 0 moments',
              defaultModeResponseCountRef.current
            )
          }
        }

        const pending = pendingExplorationRef.current
        if (!pending) return
        pendingExplorationRef.current = null

        if (pending.type === 'start') {
          // Wait for agent audio to finish (sustained silence) before starting exploration
          const SUSTAINED_SILENCE_MS = 300
          const startedWaiting = Date.now()
          let silenceStartMs = voiceCallRef.current?.agentAudioPlayingRef.current ? 0 : Date.now()
          const waitForSilence = () => {
            if (Date.now() - startedWaiting > 3000) {
              onStartExplorationRef.current?.(pending.constantId)
              return
            }
            if (voiceCallRef.current?.agentAudioPlayingRef.current) {
              silenceStartMs = 0
              requestAnimationFrame(waitForSilence)
              return
            }
            if (silenceStartMs === 0) silenceStartMs = Date.now()
            if (Date.now() - silenceStartMs < SUSTAINED_SILENCE_MS) {
              requestAnimationFrame(waitForSilence)
              return
            }
            onStartExplorationRef.current?.(pending.constantId)
          }
          requestAnimationFrame(waitForSilence)
        } else if (pending.type === 'resume') {
          // Truncate agent's buffered audio so narrator takes over immediately
          const response = (msg as Record<string, unknown>).response as
            | Record<string, unknown>
            | undefined
          const output = response?.output as Array<{ type: string; id?: string }> | undefined
          const audioItem = output?.find((item) => item.type === 'message')
          if (audioItem?.id) {
            const audioEndMs = Math.max(0, Date.now() - responseCreatedMsRef.current)
            dc.send(
              JSON.stringify({
                type: 'conversation.item.truncate',
                item_id: audioItem.id,
                content_index: 0,
                audio_end_ms: audioEndMs,
              })
            )
          }
          narrationPlayingRef.current = true
          if (voiceCallRef.current?.audioElRef.current) {
            voiceCallRef.current.audioElRef.current.volume = 0
          }
          lastResumeTimestampRef.current = Date.now()
          onResumeExplorationRef.current?.()
        }
      },
      onResponseCreated: (dc) => {
        // Track response creation time for audio truncation
        responseCreatedMsRef.current = Date.now()

        // During narration, cancel any VAD-triggered response
        if (narrationPlayingRef.current) {
          if (!isExplorationActiveRef?.current) {
            // Exploration ended — allow agent to speak
            narrationPlayingRef.current = false
            if (voiceCallRef.current?.audioElRef.current) {
              voiceCallRef.current.audioElRef.current.volume = 1
            }
          } else {
            dc.send(JSON.stringify({ type: 'response.cancel' }))
          }
        }
      },
      onTransfer: (targetNumber, cleanupFn, _redialFn) => {
        setTransferTarget(targetNumber)
        setDomainState('transferring')
        onTransferRef.current?.(targetNumber)

        transferTimerRef.current = setTimeout(() => {
          transferTimerRef.current = null
          cleanupFn()
          setTransferTarget(null)
          setDomainState(null)
          // Re-dial the new number (preserves playerId via activePlayerIdRef)
          calledNumberRef.current = targetNumber
          // Reset for new call
          windingDownRequestedRef.current = false
          goodbyeRequestedRef.current = false
          childHasSpokenRef.current = false
          familiarizingResponseCountRef.current = 0
          scenarioRef.current = null
          transcriptsRef.current = []
          voiceCallRef.current?.dial()
        }, TRANSFER_DELAY_MS)
      },
      suppressErrorCodes: [
        'response_cancel_not_active',
        'conversation_already_has_active_response',
        'item_truncation_failed',
        'invalid_value',
      ],
      usageFeature: 'number-line:voice',
    }),
    [
      buildModeContext,
      modes,
      onToolCall,
      onResponseDone,
      onChildSpeech,
      onModelSpeech,
      isExplorationActiveRef,
    ]
  )

  const voiceCall = useVoiceCall(config)

  // Store voiceCall in a ref for use in callbacks that can't directly reference it
  voiceCallRef.current = voiceCall

  // Wire up the extendTimer ref
  extendTimerRef.current = voiceCall.extendTimer

  /**
   * Fetch shared history for this player-number pair and store it in the ref.
   *
   * If prior sessions have pending background culls (e.g. from dirty disconnects),
   * schedules a 15-second delayed re-fetch. If the re-fetch surfaces new moments,
   * injects them as a system message so the number "remembers" mid-conversation
   * without delaying the initial call connection.
   */
  const fetchSharedHistory = useCallback(
    (playerId: string, callerNumber: number) => {
      const url = `/api/number-line/shared-history?playerId=${encodeURIComponent(playerId)}&callerNumber=${callerNumber}`
      fetch(url)
        .then((r) => r.json())
        .then((data) => {
          if (!data.history) return
          sharedHistoryRef.current = data.history

          if (!data.history.pendingCulls) return
          // Delayed re-fetch: background culls may finish within ~15s
          setTimeout(() => {
            fetch(url)
              .then((r) => r.json())
              .then((fresh) => {
                if (!fresh.history) return
                const prevCount = data.history.moments?.length ?? 0
                if (fresh.history.moments.length <= prevCount) return

                sharedHistoryRef.current = fresh.history
                const lines = (
                  fresh.history.moments as Array<{ caption: string; recencyLabel: string }>
                )
                  .map(
                    (m: { caption: string; recencyLabel: string }) =>
                      `- ${m.caption} (${m.recencyLabel})`
                  )
                  .join('\n')
                voiceCall.sendSystemMessage(
                  `[System update — you just remembered some things about this child from past calls:\n${lines}\nWeave these in naturally if relevant. Don't announce that you "just remembered" — act like you always knew.]`
                )
              })
              .catch(() => {})
          }, 15_000)
        })
        .catch((err) => console.warn('[moments] shared history fetch failed:', err))
    },
    [voiceCall]
  )

  // ── Domain-specific dial that accepts number + options ──
  const dial = useCallback(
    (number: number, dialOptions?: DialOptions) => {
      // Set refs before calling the framework's dial
      calledNumberRef.current = number
      if (dialOptions?.playerId !== undefined) {
        activePlayerIdRef.current = dialOptions.playerId
      }
      availablePlayersRef.current = dialOptions?.availablePlayers ?? []
      recommendedExplorationsRef.current = dialOptions?.recommendedExplorations

      // Reset domain state
      setProfileFailed(false)
      profileFailedRef.current = false
      extensionUsedRef.current = false
      windingDownRequestedRef.current = false
      goodbyeRequestedRef.current = false
      childHasSpokenRef.current = false
      familiarizingResponseCountRef.current = 0
      momentNudgeSentRef.current = false
      defaultModeResponseCountRef.current = 0
      scenarioRef.current = null
      transcriptsRef.current = []
      markedMomentsRef.current = []
      postcardSentRef.current = false
      sessionIdRef.current = createId()
      sessionEndedRef.current = false
      sharedHistoryRef.current = null
      callStartTimeRef.current = Date.now()
      setTransferTarget(null)
      setDomainState(null)

      // Load shared history — non-blocking, fills in ref before default mode starts.
      // If prior sessions have pending culls (dirty disconnects being processed),
      // schedules a delayed re-fetch and injects late-arriving memories mid-call.
      const playerId = dialOptions?.playerId ?? activePlayerIdRef.current
      if (playerId) {
        fetchSharedHistory(playerId, number)
      }

      voiceCall.dial()
    },
    [voiceCall]
  )

  const hangUp = useCallback(() => {
    // Save call record
    if (calledNumberRef.current && transcriptsRef.current.length > 0) {
      sessionHistoryRef.current.push({
        number: calledNumberRef.current,
        conferenceNumbers: [...conferenceNumbersRef.current],
        transcripts: [...transcriptsRef.current],
        scenario: scenarioRef.current ? { ...scenarioRef.current } : null,
        timestamp: Date.now(),
      })
    }
    // Clean up domain state
    conferenceNumbersRef.current = []
    setConferenceNumbers([])
    currentSpeakerRef.current = null
    setCurrentSpeaker(null)
    pendingSpeakerRef.current = null
    if (pendingSpeakerTimerRef.current) {
      clearTimeout(pendingSpeakerTimerRef.current)
      pendingSpeakerTimerRef.current = null
    }
    if (transferTimerRef.current) {
      clearTimeout(transferTimerRef.current)
      transferTimerRef.current = null
    }
    setTransferTarget(null)
    setDomainState(null)
    voiceCall.hangUp()
  }, [voiceCall])

  const removeFromCall = useCallback(
    (numberToRemove: number) => {
      const updated = conferenceNumbersRef.current.filter((n) => n !== numberToRemove)
      if (updated.length === 0) {
        hangUp()
        return
      }
      conferenceNumbersRef.current = updated
      setConferenceNumbers(updated)
      if (currentSpeakerRef.current === numberToRemove) {
        currentSpeakerRef.current = updated[0]
        setCurrentSpeaker(updated[0])
      }
      if (updated.length === 1) {
        voiceCall.enterMode('default', 'removeFromCall → solo')
      } else {
        voiceCall.updateSession('removeFromCall → conference')
      }
      voiceCall.sendSystemMessage(`[System: ${numberToRemove} has left the call.]`, true)
    },
    [hangUp, voiceCall]
  )

  const setNarrationPlaying = useCallback(
    (playing: boolean) => {
      narrationPlayingRef.current = playing
      if (voiceCall.audioElRef.current) {
        voiceCall.audioElRef.current.volume = playing ? 0 : 1
      }
    },
    [voiceCall.audioElRef]
  )

  // Compute effective call state (overlay 'transferring' on base)
  const effectiveState: CallState =
    domainState === 'transferring' ? 'transferring' : voiceCall.state

  return {
    state: effectiveState,
    error: voiceCall.error,
    errorCode: voiceCall.errorCode,
    dial,
    hangUp,
    timeRemaining: voiceCall.timeRemaining,
    isSpeaking: voiceCall.isSpeaking,
    transferTarget,
    conferenceNumbers,
    currentSpeaker,
    removeFromCall,
    sendSystemMessage: voiceCall.sendSystemMessage,
    setNarrationPlaying,
    profileFailed,
    currentInstructions: voiceCall.currentInstructions,
    modeDebug: voiceCall.modeDebug as ModeDebugInfo,
  }
}