"use client";
import { useMemo, useState } from "react";
import { ArrowDownIcon, ChevronRightIcon, PlayIcon } from "lucide-react";
import { Button } from "@/components/ui/button";
import { MessageResponse } from "@/components/ai-elements/message";
import { cn } from "@/lib/utils";
import {
buildAnswer,
coerceCorrectAnswer,
normalizeOptions,
resolveCorrect,
seededRandom,
shuffleOptions,
type AnswerRequest,
type AskToolInput,
type QuestionAnswerData,
type QuestionData,
type QuestionMode,
type QuizToolInput,
type Phase3,
} from "@/src/core";
/**
* The question dock — a pending quiz/ask REPLACES the chat composer: the
* persistent bottom blob morphs into the question. Two voices meet here:
* the teacher's (question, options, explanation) and the learner's —
* "Your thinking", a labeled composer-twin field for dumping reasoning,
* with Submit docked inside it exactly like the chat composer's send.
*
* The thinking field is the transfer channel of the whole product (wave-2):
* never called "optional", Enter makes a NEWLINE (it is for dumping — soon
* dictated, not typed), submission is the button only, and its size scales
* with the phase (probing stays quick; teaching invites depth). The
* "Other…" option is an editable option ROW — circle + inline input,
* styled like its siblings — so picking Other never displaces thinking.
*
* Collapse behavior (scroll-up → slim bar) is owned by the DockOverlay in the
* chat view, which also owns the persistent shell and its height morph. This
* component is content only. The expanded form stays MOUNTED while collapsed
* (hidden, not unmounted) so a half-made selection survives scrolling.
*/
export interface QuestionDockProps {
toolName: "quiz" | "ask_user_question";
toolCallId: string;
input: QuizToolInput | AskToolInput;
/** Collapse state, owned by the DockOverlay (it drives the shell's height morph). */
expanded: boolean;
/**
* Teach-phase check awaiting its reveal (vision §2, W5): while collapsed,
* the bar is the "Check your understanding" invitation instead of the
* scroll-collapse strip. Owned by the DockOverlay; false once the learner
* has revealed (afterwards the normal collapse machine rules apply).
*/
reveal?: boolean;
onExpand: () => void;
onSubmit: (output: QuestionAnswerData) => void;
/** Session phase at the question — scales the thinking field: probing
* stays quick (one row), teaching invites dumping (three rows). */
phase?: Phase3;
}
export function QuestionDock({
toolName,
toolCallId,
input,
expanded,
reveal = false,
onExpand,
onSubmit,
phase = "probe",
}: QuestionDockProps) {
return (
<>
{!expanded && (
)}
>
);
}
/** A plain-text teaser of a question for the collapsed bar: unwrap math, flatten common LaTeX. */
function teaserText(q: string): string {
return q
.replace(/\\\(([\s\S]*?)\\\)/g, "$1") // \(...\) inline math
.replace(/\\\[([\s\S]*?)\\\]/g, "$1") // \[...\] display math
.replace(/\$\$?([^$]*)\$\$?/g, "$1") // legacy $...$ (pre-switch sessions)
.replace(/\\frac\{([^{}]*)\}\{([^{}]*)\}/g, "$1/$2")
.replace(/\\([a-zA-Z]+)/g, "$1")
.replace(/[{}]/g, "")
.replace(/\s+/g, " ")
.trim();
}
/** The collapsed strip. Two species (W5): "collapsed" is the scroll minimization
* (kind chip + one-liner + Answer ↓); "reveal" is the teach-check invitation —
* a distinct, more inviting affordance, because it asks the learner to start
* something, not to resume something. */
export function QuestionDockBar({
toolName,
question,
onExpand,
variant = "collapsed",
}: {
toolName: "quiz" | "ask_user_question";
question: string;
onExpand: () => void;
variant?: "collapsed" | "reveal";
}) {
if (variant === "reveal") {
return (
);
}
return (
);
}
/** The expanded question: label, question, options, and the unified bottom row. */
function QuestionDockForm({
toolName,
toolCallId,
input,
phase = "probe",
onSubmit,
}: Omit) {
const kind = toolName === "quiz" ? ("quiz" as const) : ("ask" as const);
// Canonical QuestionData, built once per question. Quiz options are
// deterministically shuffled (seeded by toolCallId) so position never leaks
// correctness AND server/client render the same order (hydration-safe);
// the display order is snapshotted into the answer record at submit time.
const qd = useMemo(() => {
const quizInput = kind === "quiz" ? (input as QuizToolInput) : null;
const askInput = kind === "ask" ? (input as AskToolInput) : null;
const multi = input.multiSelect === true;
const mode: QuestionMode =
kind === "quiz"
? multi
? "multi-select"
: "single-select"
: askInput?.options?.length
? multi
? "multi-select"
: "single-select"
: "text";
const options = normalizeOptions(
(quizInput?.options ?? askInput?.options ?? []) as { label: string; value?: string }[],
);
const ordered = kind === "quiz" && options.length > 0 ? shuffleOptions(options, seededRandom(toolCallId)) : options;
const q: QuestionData = {
id: toolCallId,
kind,
question: input.question,
context: input.details,
mode,
options: ordered,
createdAt: new Date().toISOString(),
};
if (quizInput) {
const resolved = resolveCorrect(coerceCorrectAnswer(quizInput.correctAnswer), ordered);
if (resolved.error) console.error("[quiz] correctAnswer did not resolve:", resolved.error);
q.correctIndices = resolved.indices;
q.explanation = quizInput.explanation;
}
return q;
}, [toolCallId, kind, input]);
const [selected, setSelected] = useState>(new Set()); // 0-based indices
const [dontKnow, setDontKnow] = useState(false);
// "Other" is selected by typing into its inline input (or clicking its
// circle). Picking a sibling option deselects it, but the typed text
// survives — the learner's words are never thrown away.
const [otherSelected, setOtherSelected] = useState(false);
// The learner's transfer channel — thinking, never "a note".
const [thinking, setThinking] = useState("");
const [other, setOther] = useState("");
const [text, setText] = useState("");
const toggle = (idx: number) => {
setDontKnow(false);
setOtherSelected(false);
setSelected((prev) => {
if (qd.mode === "multi-select") {
const next = new Set(prev);
if (next.has(idx)) next.delete(idx);
else next.add(idx);
return next;
}
return new Set([idx]);
});
};
const canSubmit =
qd.mode === "text"
? text.trim().length > 0
: dontKnow || (otherSelected && other.trim().length > 0) || selected.size > 0;
const submit = () => {
if (!canSubmit) return;
const req: AnswerRequest = {
dontKnow,
values: [...selected].map((i) => qd.options[i]!.value),
other: otherSelected ? other : undefined,
text: qd.mode === "text" ? text : undefined,
note: qd.mode !== "text" ? thinking.trim() || undefined : undefined,
};
onSubmit(buildAnswer(qd, req));
};
// Selecting Other never clears the thinking field — two channels, the
// answer and the reasoning behind it, side by side.
const selectOther = () => {
setDontKnow(false);
setSelected(new Set());
setOtherSelected(true);
};
return (
{/* Question area — scrolls internally if very tall; the bottom row stays put. */}
{kind === "quiz" ? "Quiz" : "Question"}
{qd.mode === "multi-select" && " · select all that apply"}
{/* The learner's half of the dock — a composer TWIN: a labeled, bordered
field with Submit docked inside, exactly like the chat composer's
send. Select modes get "Your thinking" (Enter makes a newline — it
is for dumping, soon dictated; the button submits); text mode
keeps "Your answer" with Enter-to-submit. */}