"use client";
import { useMemo, useState } from "react";
import { ArrowDownIcon } from "lucide-react";
import { Button } from "@/components/ui/button";
import { MessageResponse } from "@/components/ai-elements/message";
import { cn } from "@/lib/utils";
import type { AskToolInput, QuizToolInput } from "@/src/agent/tools";
import {
buildAnswer,
coerceCorrectAnswer,
normalizeOptions,
resolveCorrect,
seededRandom,
shuffleOptions,
type AnswerRequest,
type QuestionAnswerData,
type QuestionData,
type QuestionMode,
} from "@/src/core/question-core";
/**
* The question dock — a pending quiz/ask REPLACES the chat composer: the
* persistent bottom blob morphs into the question. One unit, one action:
* the bottom field (note for select modes, the answer for free-text asks,
* "Other" text when Other is picked) plus the Submit button send together.
*
* 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;
onExpand: () => void;
onSubmit: (output: QuestionAnswerData) => void;
}
export function QuestionDock({ toolName, toolCallId, input, expanded, onExpand, onSubmit }: 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(/\$\$?([^$]*)\$\$?/g, "$1")
.replace(/\\frac\{([^{}]*)\}\{([^{}]*)\}/g, "$1/$2")
.replace(/\\([a-zA-Z]+)/g, "$1")
.replace(/[{}]/g, "")
.replace(/\s+/g, " ")
.trim();
}
/** The collapsed strip: kind chip + question one-liner; click to answer. */
export function QuestionDockBar({
toolName,
question,
onExpand,
}: {
toolName: "quiz" | "ask_user_question";
question: string;
onExpand: () => void;
}) {
return (
);
}
/** The expanded question: label, question, options, and the unified bottom row. */
function QuestionDockForm({ toolName, toolCallId, input, 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?.mode ?? (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);
const [showOther, setShowOther] = useState(false);
// The single free-text slot holds one of two values by mode.
const [note, setNote] = useState("");
const [other, setOther] = useState("");
const [text, setText] = useState("");
const toggle = (idx: number) => {
setDontKnow(false);
setShowOther(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 || (showOther && 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: showOther ? other : undefined,
text: qd.mode === "text" ? text : undefined,
note: qd.mode !== "text" ? note.trim() || undefined : undefined,
};
onSubmit(buildAnswer(qd, req));
};
// The bottom field: answer (text mode) / own answer (Other) / note.
const field =
qd.mode === "text"
? { value: text, set: setText, placeholder: "Type your answer…" }
: showOther
? { value: other, set: setOther, placeholder: "Type your own answer…" }
: { value: note, set: setNote, placeholder: "Add a note (optional) — anything you're unsure about" };
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"}