"use client"; import { useCallback, useEffect, useState } from "react"; import { FileText, Loader2, Plus, Trash2, X } from "lucide-react"; import { useTranslation } from "react-i18next"; import { importFromBook, initModules, generateModulesFromNotebook, type ModuleInit, } from "@/lib/learning-api"; import { bookApi } from "@/lib/book-api"; import type { Book } from "@/lib/book-types"; import { listNotebooks, getNotebook, type NotebookSummary, type NotebookRecordItem, } from "@/lib/notebook-api"; interface CreateModuleDialogProps { open: boolean; onClose: () => void; onCreated: () => void; } type Source = "manual" | "book" | "notebook"; interface KpRow { name: string; type: string; } /** * Derive a stable, collision-resistant id from a human label without ever * surfacing it in the UI. crypto.randomUUID keeps this opaque (the old code * leaked `Date.now()`-based ids through a free-text field). */ function genId(prefix: string): string { const rand = typeof crypto !== "undefined" && "randomUUID" in crypto ? crypto.randomUUID().slice(0, 8) : Math.random().toString(36).slice(2, 10); return `${prefix}_${rand}`; } export default function CreateModuleDialog({ open, onClose, onCreated, }: CreateModuleDialogProps) { const { t } = useTranslation(); const [source, setSource] = useState("manual"); // ── Manual ── const [moduleName, setModuleName] = useState(""); const [kpRows, setKpRows] = useState([{ name: "", type: "concept" }]); // ── Book ── const [books, setBooks] = useState([]); const [selectedBookId, setSelectedBookId] = useState(""); const [bookChapters, setBookChapters] = useState< { title: string; learning_objectives: string[] }[] >([]); const [loadingBooks, setLoadingBooks] = useState(false); const [loadingChapters, setLoadingChapters] = useState(false); // ── Notebook ── const [notebooks, setNotebooks] = useState([]); const [selectedNotebook, setSelectedNotebook] = useState(""); const [notebookRecords, setNotebookRecords] = useState([]); const [selectedRecordIds, setSelectedRecordIds] = useState>( new Set(), ); const [loadingNotebooks, setLoadingNotebooks] = useState(false); const [loadingRecords, setLoadingRecords] = useState(false); // ── Shared ── const [submitting, setSubmitting] = useState(false); const [error, setError] = useState(null); // Lazy-load the list for whichever non-manual source is active. useEffect(() => { if (!open) return; if (source === "book" && books.length === 0) { setLoadingBooks(true); bookApi .list() .then((data) => setBooks(data.books ?? [])) .catch(() => setError(t("masteryPath.loadBooksFailed"))) .finally(() => setLoadingBooks(false)); } if (source === "notebook" && notebooks.length === 0) { setLoadingNotebooks(true); listNotebooks() .then(setNotebooks) .catch(() => setError(t("masteryPath.loadNotebooksFailed"))) .finally(() => setLoadingNotebooks(false)); } }, [open, source, books.length, notebooks.length, t]); useEffect(() => { if (!selectedBookId) { setBookChapters([]); return; } setBookChapters([]); setLoadingChapters(true); bookApi .get(selectedBookId) .then((data) => setBookChapters(data.spine?.chapters ?? [])) .catch(() => setError(t("masteryPath.loadChaptersFailed"))) .finally(() => setLoadingChapters(false)); }, [selectedBookId, t]); useEffect(() => { if (!selectedNotebook) { setNotebookRecords([]); setSelectedRecordIds(new Set()); return; } setLoadingRecords(true); getNotebook(selectedNotebook) .then((data) => setNotebookRecords(data.records ?? [])) .catch(() => setError(t("masteryPath.loadRecordsFailed"))) .finally(() => setLoadingRecords(false)); }, [selectedNotebook, t]); const resetState = useCallback(() => { setSource("manual"); setModuleName(""); setKpRows([{ name: "", type: "concept" }]); setSelectedBookId(""); setBookChapters([]); setSelectedNotebook(""); setNotebookRecords([]); setSelectedRecordIds(new Set()); setSubmitting(false); setError(null); }, []); const handleClose = useCallback(() => { resetState(); onClose(); }, [resetState, onClose]); // ── Submit (one entry point, branches per source) ── const handleSubmit = useCallback(async () => { setSubmitting(true); setError(null); try { if (source === "manual") { const validKps = kpRows.filter((r) => r.name.trim()); if (validKps.length === 0) { setError(t("masteryPath.moduleNameRequired")); return; } const bookId = genId("manual"); const moduleId = genId("m"); const modules: ModuleInit[] = [ { id: moduleId, name: moduleName.trim() || t("masteryPath.untitledModule"), order: 0, pass_threshold: 0.7, knowledge_points: validKps.map((kp) => ({ id: genId("kp"), name: kp.name.trim(), type: kp.type, module_id: moduleId, })), }, ]; await initModules(bookId, modules); } else if (source === "book") { if (!selectedBookId || bookChapters.length === 0) return; const chapters = bookChapters.map((ch) => ({ title: ch.title, knowledge_points: ch.learning_objectives ?? [], })); await importFromBook(selectedBookId, chapters); } else { if (!selectedNotebook || selectedRecordIds.size === 0) return; const bookId = `nb_${selectedNotebook}`; const records = notebookRecords .filter((r) => selectedRecordIds.has(r.id)) .map((r) => ({ id: r.id, type: r.type, title: r.title, output: r.output, })); await generateModulesFromNotebook( bookId, selectedNotebook, records.slice(0, 20), ); } onCreated(); handleClose(); } catch { setError( source === "manual" ? t("masteryPath.createModuleFailed") : source === "book" ? t("masteryPath.importBookFailed") : t("masteryPath.importNotebookFailed"), ); } finally { setSubmitting(false); } }, [ source, kpRows, moduleName, selectedBookId, bookChapters, selectedNotebook, selectedRecordIds, notebookRecords, onCreated, handleClose, t, ]); if (!open) return null; const sources: { key: Source; label: string }[] = [ { key: "manual", label: t("masteryPath.tabManual") }, { key: "book", label: t("masteryPath.tabBook") }, { key: "notebook", label: t("masteryPath.tabNotebook") }, ]; const submitDisabled = submitting || (source === "book" && (!selectedBookId || bookChapters.length === 0)) || (source === "notebook" && selectedRecordIds.size === 0); return (
{/* Header */}

{t("masteryPath.createModule")}

{/* Source picker */}
{sources.map((s) => ( ))}
{/* Body */}
{error && (
{error}
)} {source === "manual" && (
setModuleName(e.target.value)} placeholder={t("masteryPath.moduleNamePlaceholder")} className="w-full rounded-md border border-[var(--border)] bg-[var(--background)] px-3 py-1.5 text-sm text-[var(--foreground)] placeholder:text-[var(--muted-foreground)]/50 focus:border-[var(--primary)]/40 focus:outline-none" />
{kpRows.map((row, i) => (
{ const next = [...kpRows]; next[i] = { ...next[i], name: e.target.value }; setKpRows(next); }} placeholder={t("masteryPath.kpNamePlaceholder")} className="flex-1 rounded-md border border-[var(--border)] bg-[var(--background)] px-3 py-1.5 text-sm text-[var(--foreground)] placeholder:text-[var(--muted-foreground)]/50 focus:border-[var(--primary)]/40 focus:outline-none" /> {kpRows.length > 1 && ( )}
))}
)} {source === "book" && (
{loadingBooks ? (
) : books.length === 0 ? (
{t("masteryPath.noBooks")}
) : ( <>
{books.map((book) => ( ))}
{selectedBookId && (
{loadingChapters ? (
{t("masteryPath.loadingChapters")}
) : bookChapters.length === 0 ? (
{t("masteryPath.noChapters")}
) : (

{t("masteryPath.chaptersToImport", { count: bookChapters.length, })}

{bookChapters.map((ch, i) => (
{ch.title} ({(ch.learning_objectives ?? []).length}{" "} {t("masteryPath.kps")})
))}
)}
)} )}
)} {source === "notebook" && (
{loadingNotebooks ? (
) : notebooks.length === 0 ? (
{t("masteryPath.noNotebooks")}
) : ( <>
{notebooks.map((nb) => ( ))}
{selectedNotebook && (
{loadingRecords ? (
{t("masteryPath.loadingRecords")}
) : notebookRecords.length === 0 ? (
{t("masteryPath.noRecords")}
) : (

{t("masteryPath.selectRecords")} ( {selectedRecordIds.size} {t("masteryPath.selected")})

{notebookRecords.slice(0, 20).map((rec) => ( ))}
{notebookRecords.length > 20 && (

{t("masteryPath.recordsLimited")}

)}
)}
)} )}
)}
{/* Footer */}
); }