import { CornerDownLeft, PanelRightClose, Sparkles, Square } from 'lucide-react'; import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState, type ReactNode } from 'react'; import { createPortal } from 'react-dom'; import { errorMessage, streamEvents } from '@/lib/api'; import type { ToolActivity } from '@/lib/types'; import { cx } from '@/lib/util'; import { GenUiContext, Markdown } from '@/ui/Markdown'; import { Button, Callout, IconButton, Spinner } from '@/ui'; import { ToolSteps } from './ToolSteps'; type ExplainBody = | { kind: 'question'; stem: string; options: { text: string; correct: boolean }[]; selected?: string[]; rationale?: string; quizId?: string } | { kind: 'card'; front: string; back: string } | { kind: 'text'; text: string } // On a share link the item is named by id; the server loads its content. | { kind: 'question'; quizId: string; questionId: string; selected?: string[] } | { kind: 'card'; deckId: string; cardId: string }; type Event = { type: 'text'; delta: string } | { type: 'tool'; tool: ToolActivity } | { type: 'error'; message: string } | { type: 'done' }; interface Turn { ask?: string; text: string; tools: ToolActivity[]; } /** * Set by the quiz runner: on wide screens the explanation opens in the empty space to the right * of the question instead of below it. */ export const ExplainSideContext = createContext(false); /** Width available beside a centred 48rem column, or 0 when there is not enough room. */ function useSideRoom(enabled: boolean): number { const measure = () => (typeof window === 'undefined' ? 0 : Math.floor((window.innerWidth - 768) / 2 - 44)); const [room, setRoom] = useState(measure); useEffect(() => { if (!enabled) return; const onResize = () => setRoom(measure()); window.addEventListener('resize', onResize); return () => window.removeEventListener('resize', onResize); }, [enabled]); return enabled && room >= 300 ? Math.min(room, 520) : 0; } /** "Explain with AI": streams a short explanation and accepts follow-up questions. */ export function Explain({ body, label = 'Explain with AI', className, url = '/api/ai/explain' }: { body: ExplainBody; label?: string; className?: string; url?: string }) { const [open, setOpen] = useState(false); const [turns, setTurns] = useState([]); const [busy, setBusy] = useState(false); const [error, setError] = useState(''); const [ask, setAsk] = useState(''); const abort = useRef(null); const key = JSON.stringify(body); const sideWidth = useSideRoom(useContext(ExplainSideContext)); useEffect(() => { // A different question: start over. abort.current?.abort(); setOpen(false); setTurns([]); setError(''); setAsk(''); }, [key]); useEffect(() => () => abort.current?.abort(), []); const run = useCallback( async (question?: string) => { setOpen(true); setBusy(true); setError(''); setTurns((t) => [...t, { ask: question, text: '', tools: [] }]); const controller = new AbortController(); abort.current = controller; const patchLast = (fn: (t: Turn) => Turn) => setTurns((t) => t.map((x, i) => (i === t.length - 1 ? fn(x) : x))); try { await streamEvents( url, { ...body, ask: question }, (e) => { if (e.type === 'text') patchLast((x) => ({ ...x, text: x.text + e.delta })); else if (e.type === 'tool') patchLast((x) => ({ ...x, tools: x.tools.some((t) => t.id === e.tool.id) ? x.tools.map((t) => (t.id === e.tool.id ? e.tool : t)) : [...x.tools, e.tool] })); else if (e.type === 'error') setError(e.message); }, controller.signal, ); } catch (e) { if ((e as Error)?.name !== 'AbortError') setError(errorMessage(e)); } finally { setBusy(false); } }, // eslint-disable-next-line react-hooks/exhaustive-deps [key, url], ); const onSend = useCallback((text: string) => !busy && void run(text.slice(0, 500)), [busy, run]); const genUi = useMemo(() => ({ streaming: busy, onSend }), [busy, onSend]); if (!open) { return ( ); } const panel: ReactNode = (
0 ? 'flex max-h-full flex-col bg-surface shadow-2' : 'bg-accent-soft/50')}>
AI explanation {sideWidth > 0 && ( setOpen(false)} className="-my-1 text-ink-3"> )}
0 && 'min-h-0 flex-1 overflow-y-auto pr-1')}> {turns.map((t, i) => (
{t.ask &&
{t.ask}
} {t.tools.length > 0 && } {t.text ? {t.text} : busy && i === turns.length - 1 && !t.tools.some((x) => x.status === 'running') ? : null}
))}
{error && ( {error} )}
{ e.preventDefault(); if (busy) return abort.current?.abort(); const question = ask.trim(); if (!question) return; setAsk(''); void run(question); }} > setAsk(e.target.value)} placeholder="Ask a follow-up…" aria-label="Follow-up question" className="h-9 min-w-0 flex-1 rounded-[9px] border border-line-strong bg-surface px-3 text-sm outline-none focus:border-accent" />

AI can be wrong. Check anything important against your course material.

); if (sideWidth > 0) { // Wide screens: the explanation sits in the free space right of the question. return ( <>
Explanation is open on the right
{createPortal( , document.body, )} ); } return
{panel}
; }