Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

26.1 KB
Raw Blame
"use client";

import { PageBarSlot } from "@/components/layout/PageChrome";
import { PageContainer, PAGE_DESCRIPTION_CLASS } from '@/components/layout/FeaturePage'
import { scopedUrl } from "@/lib/workspace-scope";
import { MASTERY_HOME, masterySessionRoute as existingMasterySessionRoute, masterySessionsRoute } from "@/lib/learning-routes";

import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import Link from "next/link";
import { useParams, useRouter } from "next/navigation";
import { useTranslation } from "react-i18next";
import {
  ArrowLeft,
  ArrowRight,
  BookOpen,
  Compass,
  LayoutGrid,
  List,
  Loader2,
  MoreHorizontal,
  PencilRuler,
  Radio,
  RotateCcw,
  Sparkles,
  Trash2,
} from "lucide-react";

import {
  MASTERY_OPENING_SCOPE,
  masteryOpeningMessage,
  masterySessionRoute,
} from "@/lib/mastery-mode";
import { LearnerProfileCard } from "@/components/space/learning/LearnerProfileCard";
import { ModuleOutline } from "@/components/space/learning/ModuleOutline";
import { ConfirmDialog } from "@/components/space/learning/ConfirmDialog";
import { EditTopicRouteDialog } from "@/components/space/learning/EditTopicRouteDialog";
import { LearningBoard } from "@/components/space/learning/LearningBoard";
import {
  topicDisplayName,
  type Translate,
} from "@/components/space/learning/format";
import { PathTitle } from "@/components/space/learning/PathTitle";
import { MasteryPathCrumb } from "@/components/layout/instance-crumbs";
import { ReviewTrail } from "@/components/space/learning/ReviewTrail";
import { SessionCamp } from "@/components/space/learning/SessionCamp";
import { useMasteryPathActivity } from "@/hooks/useMasteryPathActivity";
import {
  deleteProgress,
  fetchMasteryTopic,
  fetchMasteryTopicSessions,
  fetchLearningBoard,
  redoProgress,
  renameProgress,
  setMasteryObjectiveOverride,
  updateMasteryReviewSettings,
  type MasteryTopic,
  type BoardResult,
  type TopicSession,
} from "@/lib/learning-api";
import { setPendingPrompt } from "@/lib/pending-prompt";
import { NEXT_CTA_LABELS, NEXT_LABELS } from "@/components/space/learning/next-step-copy";

export default function MasteryTopicPage() {
  const params = useParams<{ pathId: string }>();
  const pathId = String(params.pathId || "");
  const router = useRouter();
  const { t, i18n } = useTranslation();
  const zh = Boolean(i18n.language?.toLowerCase().startsWith("zh"));
  const [topic, setTopic] = useState<MasteryTopic | null>(null);
  const [sessions, setSessions] = useState<TopicSession[]>([]);
  const [loading, setLoading] = useState(true);
  const [sessionsLoading, setSessionsLoading] = useState(true);
  const [sessionsError, setSessionsError] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [selectedId, setSelectedId] = useState<string | null>(null);
  const [editorOpen, setEditorOpen] = useState(false);
  const [confirmAction, setConfirmAction] = useState<"reset" | "delete" | null>(
    null,
  );
  const [topicView, setTopicView] = useState<"outline" | "board">("outline");
  const [board, setBoard] = useState<BoardResult | null>(null);
  const [boardError, setBoardError] = useState(false);
  const [boardRequestNonce, setBoardRequestNonce] = useState(0);
  const [mutationBusy, setMutationBusy] = useState(false);
  const [retentionBusy, setRetentionBusy] = useState(false);
  const [retentionError, setRetentionError] = useState<string | null>(null);
  const editorTriggerRef = useRef<HTMLElement | null>(null);
  const confirmTriggerRef = useRef<HTMLElement | null>(null);
  const activity = useMasteryPathActivity(pathId || null);

  const openEditor = (trigger: HTMLButtonElement) => {
    editorTriggerRef.current = trigger;
    setEditorOpen(true);
  };

  const openConfirmation = (
    action: "reset" | "delete",
    trigger: HTMLButtonElement,
  ) => {
    confirmTriggerRef.current = trigger;
    setConfirmAction(action);
  };

  const loadTopic = useCallback(async () => {
    try {
      const next = await fetchMasteryTopic(pathId, { cache: "no-store" });
      setTopic(next);
      setError(null);
    } catch (reason) {
      setError(
        reason instanceof Error
          ? reason.message
          : t("The map could not be loaded"),
      );
    } finally {
      setLoading(false);
    }
  }, [pathId, t]);

  const loadSessions = useCallback(async () => {
    try {
      setSessions(
        await fetchMasteryTopicSessions(pathId, { cache: "no-store" }),
      );
      setSessionsError(false);
    } catch {
      // Keep whatever we last showed. Blanking the list turns a network blip
      // into "you have no sessions", which is a different and alarming claim.
      setSessionsError(true);
    } finally {
      setSessionsLoading(false);
    }
  }, [pathId]);

  useEffect(() => {
    void loadTopic();
  }, [activity.revision, loadTopic]);

  useEffect(() => {
    void loadSessions();
  }, [activity.revision, activity.signal, loadSessions]);

  useEffect(() => {
    if (topicView !== "board") return;
    const controller = new AbortController();
    setBoardError(false);
    fetchLearningBoard(pathId, {
      cache: "no-store",
      signal: controller.signal,
    })
      .then((result) => setBoard(result))
      .catch(() => {
        if (controller.signal.aborted) return;
        setBoard(null);
        setBoardError(true);
      });
    return () => controller.abort();
  }, [activity.revision, boardRequestNonce, pathId, topicView]);

  useEffect(() => {
    if (!selectedId || !topic) return;
    const stillThere = topic.map.modules.some((module) =>
      module.knowledge_points.some((point) => point.id === selectedId),
    );
    if (!stillThere) setSelectedId(null);
  }, [selectedId, topic]);

  const sourceLabels = useMemo(
    () =>
      topic?.sources.filter((source) => source.kind !== "goal").slice(0, 5) ??
      [],
    [topic],
  );
  const displayName = topic ? topicDisplayName(topic, t) : "";

  const refresh = async () => {
    await Promise.all([loadTopic(), loadSessions()]);
    activity.refresh();
  };

  const handleOverride = async (
    objectiveId: string,
    mastered: boolean,
    note: string,
  ) => {
    const result = await setMasteryObjectiveOverride(
      pathId,
      objectiveId,
      mastered,
      note,
    );
    setTopic((previous) =>
      previous
        ? { ...previous, map: result.map, path_revision: result.path_revision }
        : previous,
    );
    await loadTopic();
  };

  /**
   * The rest of this page rediscovers changes through the activity feed's
   * revision counter, which lands a poll interval later. Waiting that long to
   * see the edit you just made reads as a failed save, so the new name is
   * applied locally the moment the write returns.
   */
  const handleRename = async (name: string) => {
    const saved = await renameProgress(pathId, name);
    setTopic((previous) =>
      previous ? { ...previous, name: saved.name } : previous,
    );
    activity.refresh();
  };

  const handleRetentionChange = async (desiredRetention: number) => {
    setRetentionBusy(true);
    setRetentionError(null);
    try {
      const saved = await updateMasteryReviewSettings(pathId, desiredRetention);
      setTopic(saved);
      activity.refresh();
    } catch {
      setRetentionError(t("Could not save review target. Try again."));
    } finally {
      setRetentionBusy(false);
    }
  };

  const handleReset = async () => {
    setMutationBusy(true);
    try {
      await redoProgress(pathId);
      setSelectedId(null);
      await refresh();
      setConfirmAction(null);
    } finally {
      setMutationBusy(false);
    }
  };

  const handleDelete = async () => {
    setMutationBusy(true);
    try {
      await deleteProgress(pathId);
      router.replace(scopedUrl(MASTERY_HOME));
    } finally {
      setMutationBusy(false);
    }
  };

  const startBoardTutoring = (knowledgePointName: string) => {
    setPendingPrompt(
      `Please tutor me on: ${knowledgePointName}. Start with a quick check of what I already know, then guide me step by step.`,
      "mastery_path",
    );
    router.push(masterySessionsRoute(pathId));
  };

  const startReview = (objectiveId: string, knowledgePointName: string) => {
    setPendingPrompt(
      masteryOpeningMessage("review", t as Translate, {
        dueTitles: [knowledgePointName],
      }),
      MASTERY_OPENING_SCOPE,
    );
    setSelectedId(objectiveId);
    router.push(masterySessionRoute(pathId, "review"));
  };

  if (loading && !topic) {
    return (
      <div className="mastery-shell flex h-full items-center justify-center text-[var(--muted-foreground)]">
        <Loader2 className="h-5 w-5 animate-spin" />
      </div>
    );
  }

  if (!topic) {
    return (
      <div className="mastery-shell flex h-full flex-col items-center justify-center px-6 text-center">
        <Compass className="h-10 w-10 text-[var(--muted-foreground)] opacity-40" />
        <h1 className="mt-4 text-lg font-semibold">
          {t("This map could not be found")}
        </h1>
        <p className="mt-2 text-sm text-[var(--muted-foreground)]">{error}</p>
        <Link
          href={scopedUrl(MASTERY_HOME)}
          className="mt-5 text-sm font-medium text-[var(--primary)] hover:underline"
        >
          {t("Back to topics")}
        </Link>
      </div>
    );
  }

  const nextCopy = NEXT_LABELS[topic.next.action] ?? {
    zh: topic.next.reason,
    en: topic.next.reason,
  };
  const progress = topic.map.counts.total
    ? Math.round((topic.map.counts.mastered / topic.map.counts.total) * 100)
    : 0;
  const needsRouteRepair = topic.map.counts.total === 0;
  const nextCta = NEXT_CTA_LABELS[topic.next.action];
  const pendingSessionId =
    topic.next.session_id ||
    sessions.find((session) => session.has_pending_question)?.session_id;
  const continuationSessionId =
    topic.next.action === "answer_pending"
      ? pendingSessionId
      : sessions[0]?.session_id;

  return (
    // One screen, not a scroll. A goal's dashboard answers "where am I and
    // what is next", and that answer stops being an answer the moment it is
    // below the fold — the review plan used to sit under a full outline, and a
    // goal with many sessions pushed everything else off balance as its list
    // grew. So the page itself never scrolls: identity and next step are
    // pinned, and each panel below scrolls inside its own frame.
    //
    // Under `lg` the columns stack and the page scrolls normally — a phone has
    // no second column to balance, and a fixed-height stack there would just
    // be three tiny scrollers.
    <main className="mastery-shell flex h-full flex-col overflow-y-auto [scrollbar-gutter:stable]">
      <PageContainer className="flex min-h-0 flex-1 flex-col pb-40 sm:pb-10">
        <MasteryPathCrumb id={pathId} label={displayName} />
        <div className="flex items-center justify-between gap-3">
          <Link
            href={scopedUrl(MASTERY_HOME)}
            className="dt-section-back inline-flex items-center gap-1.5 text-xs font-medium text-[var(--muted-foreground)] hover:text-[var(--foreground)]"
          >
            <ArrowLeft className="h-3.5 w-3.5" />
            {t("Learning topics")}
          </Link>
          {/* The goal's own actions go up to the page bar, top right. */}
          <PageBarSlot name="actions" className="ml-auto flex items-center gap-1">
            <button
              type="button"
              onClick={(event) => openEditor(event.currentTarget)}
              className="dt-quiet-button"
            >
              <PencilRuler className="h-3.5 w-3.5" />
              <span className="hidden sm:inline">{t("Edit modules")}</span>
            </button>
            <details className="relative">
              <summary className="dt-quiet-button is-icon cursor-pointer list-none">
                <MoreHorizontal className="h-4 w-4" />
                <span className="sr-only">{t("More actions")}</span>
              </summary>
              <div className="absolute right-0 z-20 mt-2 w-44 rounded-xl border border-[var(--border)] bg-[var(--popover)] p-1.5 text-xs shadow-xl">
                <button
                  type="button"
                  onClick={(event) =>
                    openConfirmation("reset", event.currentTarget)
                  }
                  className="flex w-full items-center gap-2 rounded-lg px-2.5 py-2 text-left hover:bg-[var(--accent)]"
                >
                  <RotateCcw className="h-3.5 w-3.5" /> {t("Reset progress")}
                </button>
                <button
                  type="button"
                  onClick={(event) =>
                    openConfirmation("delete", event.currentTarget)
                  }
                  className="flex w-full items-center gap-2 rounded-lg px-2.5 py-2 text-left text-red-600 hover:bg-red-500/10"
                >
                  <Trash2 className="h-3.5 w-3.5" /> {t("Delete topic")}
                </button>
              </div>
            </details>
          </PageBarSlot>
        </div>

        <header className="dt-page-header mt-2 mb-6 flex flex-col gap-4">
          <div className="min-w-0">
            <div className="flex items-center gap-3">
              <div className="min-w-0">
                <PathTitle
                  displayName={displayName}
                  storedName={topic.name}
                  onRename={handleRename}
                />
                <p className={PAGE_DESCRIPTION_CLASS}>
                  {topic.metadata.description || topic.metadata.goal}
                </p>
              </div>
            </div>
            {sourceLabels.length > 0 && (
              <div className="mt-4 flex flex-wrap items-center gap-2">
                {sourceLabels.map((source) => (
                  <span
                    key={source.id}
                    className="inline-flex items-center gap-1.5 rounded-full bg-[var(--muted)] px-2.5 py-1 text-[10px] text-[var(--muted-foreground)]"
                  >
                    <BookOpen className="h-3 w-3" /> {source.label}
                  </span>
                ))}
              </div>
            )}
          </div>
          <div className="flex shrink-0 items-center gap-3">
            <span className="text-[13px] tabular-nums text-[var(--muted-foreground)]">
              {topic.map.counts.mastered}/{topic.map.counts.total}{" "}
              {t("knowledge points")}
            </span>
            <span className="h-3 w-px bg-[var(--border)]" aria-hidden="true" />
            <div className="flex items-center gap-2">
              <div className="h-1 w-24 overflow-hidden rounded-full bg-[var(--muted)]">
                <div
                  className="h-full rounded-full bg-[var(--primary)] transition-[width] duration-500"
                  style={{ width: `${progress}%` }}
                />
              </div>
              <span className="text-[13px] font-medium tabular-nums text-[var(--foreground)]">
                {progress}%
              </span>
            </div>
          </div>
        </header>

        <section className="dt-next-up fixed bottom-3 left-4 right-4 z-20 shadow-lg sm:static sm:mt-2 sm:shadow-none">
          <div className="flex min-w-0 items-baseline gap-3">
            <span className="shrink-0 text-[12px] text-[var(--muted-foreground)]">
              {t("Next up")}
            </span>
            <div className="min-w-0">
              <div className="truncate text-[14px] font-medium text-[var(--foreground)]">
                {needsRouteRepair
                  ? t("Design the outline")
                  : topic.next.knowledge_point_name ||
                    t("Celebrate completion")}
              </div>
              <p className="mt-0.5 truncate text-[12px] text-[var(--muted-foreground)]">
                {needsRouteRepair
                  ? t(
                      "This goal has no outline yet. Open a session and the tutor will design one with you.",
                    )
                  : zh
                    ? nextCopy.zh
                    : nextCopy.en}
              </p>
            </div>
          </div>
          {needsRouteRepair ? (
            <button
              type="button"
              onClick={(event) => openEditor(event.currentTarget)}
              className="inline-flex h-9 shrink-0 items-center justify-center gap-1.5 rounded-lg bg-[var(--primary)] px-3.5 text-[13px] font-medium text-[var(--primary-foreground)] transition hover:opacity-90"
            >
              <PencilRuler className="h-4 w-4" />
              {t("Add modules")}
              <ArrowRight className="h-3.5 w-3.5" />
            </button>
          ) : (
            <Link
              onClick={() => {
                if (topic.next.action === "review") {
                  setPendingPrompt(
                    masteryOpeningMessage("review", t as Translate, {
                      dueTitles: topic.next.knowledge_point_name
                        ? [topic.next.knowledge_point_name]
                        : [],
                    }),
                    MASTERY_OPENING_SCOPE,
                  );
                }
              }}
              href={
                continuationSessionId
                  ? existingMasterySessionRoute(pathId, continuationSessionId)
                  : topic.next.action === "review"
                    ? masterySessionRoute(pathId, "review")
                    : masterySessionsRoute(pathId)
              }
              className="inline-flex h-9 shrink-0 items-center justify-center gap-1.5 rounded-lg bg-[var(--primary)] px-3.5 text-[13px] font-medium text-[var(--primary-foreground)] transition hover:opacity-90"
            >
              {nextCta
                ? zh
                  ? nextCta.zh
                  : nextCta.en
                : topic.session_count > 0
                  ? t("Continue learning")
                  : t("Begin first waypoint")}
              <ArrowRight className="h-3.5 w-3.5" />
            </Link>
          )}
        </section>

        <div className="mt-6 grid min-h-0 flex-1 items-start gap-7 lg:grid-cols-[minmax(0,1fr)_340px] lg:items-stretch">
          {needsRouteRepair ? (
            // A goal starts without an outline: the first session is where the
            // tutor asks about the learner and designs one with them. Writing
            // modules by hand is still possible, but it is the fallback now,
            // not the instruction.
            <section className="dt-panel min-h-72 items-center justify-center p-8 text-center">
              <PencilRuler className="h-9 w-9 text-[var(--mastery-route)]" />
              <h2 className="mt-4 text-lg font-semibold">
                {t("No outline yet")}
              </h2>
              <p className="mt-2 max-w-md text-sm leading-6 text-[var(--muted-foreground)]">
                {t(
                  "Open a session and the tutor will read your materials, ask what you already know and how much time you have, then design the outline with you.",
                )}
              </p>
              <Link
                onClick={() =>
                  setPendingPrompt(
                    masteryOpeningMessage("outline", t),
                    MASTERY_OPENING_SCOPE,
                  )
                }
                href={masterySessionRoute(pathId, "outline")}
                className="mt-5 inline-flex h-10 items-center gap-2 rounded-xl bg-[var(--primary)] px-4 text-sm font-medium text-[var(--primary-foreground)] transition hover:opacity-90"
              >
                {t("Design the outline with the tutor")}
                <ArrowRight className="h-4 w-4" />
              </Link>
              <button
                type="button"
                onClick={(event) => openEditor(event.currentTarget)}
                className="mt-3 inline-flex h-9 items-center gap-2 rounded-xl px-3 text-[13px] text-[var(--muted-foreground)] transition hover:bg-[var(--accent)] hover:text-[var(--foreground)]"
              >
                <PencilRuler className="h-3.5 w-3.5" />
                {t("Write the modules myself")}
              </button>
            </section>
          ) : (
            <div className="flex min-h-0 flex-col gap-5 lg:h-full">
              {/* The three things a mastery goal owns — outline, review plan,
                  sessions — are named the same way and sit at the same level,
                  so the page reads as one goal's assets rather than a map with
                  two widgets hanging off it. */}
              <div className="flex flex-wrap items-center justify-between gap-3">
                <h2 className="px-2.5 text-[13px] font-semibold text-[var(--foreground)]">
                  {t("Mastery outline")}
                </h2>
                <div className="flex items-center gap-0.5 rounded-lg bg-[var(--muted)] p-0.5">
                  {(
                    [
                      ["outline", List, t("Outline")],
                      ["board", LayoutGrid, t("Board")],
                    ] as const
                  ).map(([value, Icon, label]) => (
                    <button
                      key={value}
                      type="button"
                      onClick={() => setTopicView(value)}
                      aria-pressed={topicView === value}
                      className={`flex h-8 items-center gap-1.5 rounded-md px-2.5 text-xs font-medium transition ${
                        topicView === value
                          ? "bg-[var(--background)] text-[var(--foreground)] shadow-sm"
                          : "text-[var(--muted-foreground)] hover:text-[var(--foreground)]"
                      }`}
                    >
                      <Icon className="h-3.5 w-3.5" />
                      {label}
                    </button>
                  ))}
                </div>
                {topicView === "board" && boardError && (
                  <button
                    type="button"
                    onClick={() => setBoardRequestNonce((nonce) => nonce + 1)}
                    className="text-xs font-medium text-[var(--primary)] hover:underline"
                  >
                    {t("Try again")}
                  </button>
                )}
              </div>
              {/* The outline is the tall thing on this page, so it is the one
                  that scrolls. Everything else keeps its place. */}
              <div className="min-h-0 lg:min-h-[260px] lg:flex-1 lg:overflow-y-auto lg:pr-1">
                {topicView === "outline" ? (
                <ModuleOutline
                  topic={topic}
                  revision={Math.max(topic.path_revision, activity.revision)}
                  selectedId={selectedId}
                  zh={zh}
                  onSelect={setSelectedId}
                  onOverride={handleOverride}
                />
              ) : board ? (
                <LearningBoard
                  pathId={pathId}
                  modules={board.modules}
                  revision={Math.max(topic.path_revision, activity.revision)}
                  zh={zh}
                  onStartTutoring={startBoardTutoring}
                />
              ) : boardError ? (
                <p className="dt-panel p-6 text-center text-sm text-[var(--muted-foreground)]">
                  {t("The learning board could not be loaded")}
                </p>
              ) : (
                <div className="dt-panel min-h-40 items-center justify-center">
                  <Loader2 className="h-5 w-5 animate-spin text-[var(--muted-foreground)]" />
                </div>
              )}
              </div>
              <ReviewTrail
                reviews={topic.reviews}
                desiredRetention={
                  topic.review_settings?.desired_retention ??
                  topic.reviews[0]?.desired_retention ??
                  0.9
                }
                retentionBusy={retentionBusy}
                retentionError={retentionError}
                onRetentionChange={(value) => void handleRetentionChange(value)}
                zh={zh}
                onSelect={(objectiveId) => {
                  setSelectedId(objectiveId);
                  document
                    .getElementById("mastery-outline-start")
                    ?.scrollIntoView({
                      behavior: window.matchMedia(
                        "(prefers-reduced-motion: reduce)",
                      ).matches
                        ? "auto"
                        : "smooth",
                    });
                }}
                onStartReview={startReview}
              />
            </div>
          )}
          <div className="flex min-h-0 flex-col gap-5 lg:h-full">
            <LearnerProfileCard profile={topic.learner_profile} />
            <SessionCamp
              pathId={pathId}
              sessions={sessions}
              loading={sessionsLoading}
              stale={sessionsError}
              onRetry={() => void loadSessions()}
              zh={zh}
            />
          </div>
        </div>
      </PageContainer>
      {editorOpen && (
        <EditTopicRouteDialog
          topic={topic}
          returnFocusRef={editorTriggerRef}
          onClose={() => setEditorOpen(false)}
          onSaved={(next) => {
            setTopic(next);
            setSelectedId(null);
            setEditorOpen(false);
            activity.refresh();
          }}
        />
      )}
      {confirmAction === "reset" && (
        <ConfirmDialog
          title={t("Reset learning progress?")}
          description={t(
            "Modules and knowledge points stay. Mastery evidence, pending questions, and review schedules will be cleared.",
          )}
          confirmLabel={t("Confirm reset")}
          cancelLabel={t("Cancel")}
          busy={mutationBusy}
          returnFocusRef={confirmTriggerRef}
          onConfirm={() => void handleReset()}
          onClose={() => setConfirmAction(null)}
        />
      )}
      {confirmAction === "delete" && (
        <ConfirmDialog
          title={t("Permanently delete this topic?")}
          description={t(
            "The map, evidence, review schedule, and linked records will be deleted. This cannot be undone.",
          )}
          confirmLabel={t("Delete permanently")}
          cancelLabel={t("Cancel")}
          destructive
          busy={mutationBusy}
          returnFocusRef={confirmTriggerRef}
          onConfirm={() => void handleDelete()}
          onClose={() => setConfirmAction(null)}
        />
      )}
    </main>
  );
}