openlearn-next 0.2.7 → 0.2.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/{AdminDirectoryView-Cai0cQqi.js → AdminDirectoryView-CD7tW4mc.js} +1 -1
- package/dist/assets/BatchPickerModal-Bt8Qx0Av.js +1 -0
- package/dist/assets/{ClassesView-Cxgfcrx1.js → ClassesView-B1B3wlkx.js} +2 -2
- package/dist/assets/CloudDriveModal-BSZaWIex.js +1 -0
- package/dist/assets/{ComputerLabView-CUCO2VIV.js → ComputerLabView-B6-twB0u.js} +1 -1
- package/dist/assets/CourseManagement-Bnezm9Vv.js +1 -0
- package/dist/assets/CourseWizardModal-BvfTvcQT.js +3 -0
- package/dist/assets/{CoursewareHubPanel-CAaf22Qm.js → CoursewareHubPanel-Cb1mAqHS.js} +1 -1
- package/dist/assets/{Dashboard-vSYAYoji.js → Dashboard-DQ91dQio.js} +2 -2
- package/dist/assets/ExportWeightModal-al1iIVxb.js +1 -0
- package/dist/assets/{HelpTour-ZgEkRnin.js → HelpTour-DwM9UBiA.js} +1 -1
- package/dist/assets/{HelpView-D3WIxMoB.js → HelpView-DLAKVpwf.js} +5 -5
- package/dist/assets/ImportLessonsModal-DwhvqzY_.js +1 -0
- package/dist/assets/{ImportModal-mkWuDoAN.js → ImportModal-CmUt1YeX.js} +1 -1
- package/dist/assets/InteractiveCoursewareViewer-DWnzq20c.js +1 -0
- package/dist/assets/{InteractiveWhiteboard-bmT1LKD6.js → InteractiveWhiteboard-CQ-4meYj.js} +12 -12
- package/dist/assets/{LazyCourseware-Bcxn_20f.js → LazyCourseware-g7b8EXR_.js} +1 -1
- package/dist/assets/{LazyWhiteboard-CJA7aRIM.js → LazyWhiteboard-B6rDWBFb.js} +1 -1
- package/dist/assets/{LessonEditorView-hdJblhmb.js → LessonEditorView-DixwX1Kw.js} +1 -1
- package/dist/assets/{LiveClassroomView-ByyIOLJC.js → LiveClassroomView-j93YOxSh.js} +1 -1
- package/dist/assets/NotificationDetailModal-CQ9PIqkD.js +1 -0
- package/dist/assets/{PluginView-B3ZolNGQ.js → PluginView-DCY4yi2h.js} +1 -1
- package/dist/assets/{ProcessLogsModal-8mVp07ic.js → ProcessLogsModal-B-PY780w.js} +1 -1
- package/dist/assets/QuizGeneratorModal-BvTcmD68.js +1 -0
- package/dist/assets/StudentAssignmentView-4R0WxStx.js +1 -0
- package/dist/assets/StudentLessonView-DZ0i9-tX.js +1 -0
- package/dist/assets/StudentPreviewModal-CfsB1dPY.js +1 -0
- package/dist/assets/StudentView-D7GtUiYR.js +2 -0
- package/dist/assets/SystemResourceLibraryModal-Ilnthwpw.js +1 -0
- package/dist/assets/TeacherView-DjnjsQ_3.js +2 -0
- package/dist/assets/{TimetableView-zce3okQn.js → TimetableView-BMsjwi-s.js} +3 -3
- package/dist/assets/index-D8x6bUeG.js +150 -0
- package/dist/assets/{index-CDTw8wSY.js → index-wdWIWwbg.js} +1 -1
- package/dist/assets/{vendor-icons-BvCtGbt1.js → vendor-icons-_c3xpwjZ.js} +1 -1
- package/dist/assets/vendor-motion-DjY2czvL.js +1 -0
- package/dist/index.html +1 -1
- package/dist/server.cjs +72 -20
- package/package.json +1 -1
- package/dist/assets/BatchPickerModal-CKQyeY6R.js +0 -1
- package/dist/assets/CloudDriveModal-TFWlPh8x.js +0 -1
- package/dist/assets/CourseManagement-DSCOjuIC.js +0 -1
- package/dist/assets/CourseWizardModal-B3QnFxvj.js +0 -3
- package/dist/assets/ExportWeightModal-BlS2auLs.js +0 -1
- package/dist/assets/ImportLessonsModal-BZZRDBRU.js +0 -1
- package/dist/assets/InteractiveCoursewareViewer-01PS40_x.js +0 -1
- package/dist/assets/NotificationDetailModal-dndFrE7p.js +0 -1
- package/dist/assets/QuizGeneratorModal-DpTFYbVJ.js +0 -1
- package/dist/assets/StudentAssignmentView-DDY7C092.js +0 -1
- package/dist/assets/StudentLessonView-BcQ7q4QF.js +0 -1
- package/dist/assets/StudentPreviewModal-ETJBF1Vc.js +0 -1
- package/dist/assets/StudentView-BOqPntx-.js +0 -1
- package/dist/assets/SystemResourceLibraryModal-tg8xnblT.js +0 -1
- package/dist/assets/TeacherView-CrbllHIm.js +0 -2
- package/dist/assets/index-BrEBeWAQ.js +0 -14
- package/dist/assets/index-eXp-qZdm.js +0 -129
- package/dist/assets/vendor-motion-Dz5URUo4.js +0 -9
|
@@ -1,129 +0,0 @@
|
|
|
1
|
-
import{R as Ve,r as o,j as r,d as or,h as ar,i as Wa}from"./vendor-react-0Lg0vA-4.js";import{G as Fn,S as qa,U as cr,C as Bn,a as Ct,L as Vn,A as Wn,b as lr,c as Ua,H as Ga,d as Ha,B as Qa,e as dr,f as ur,g as an,h as Ys,D as Ja,X as Qt,K as Za,P as Ka,T as Wt,i as Ya,j as cn,k as Xa,l as ln,m as ec,n as tc,o as sc,p as nc,q as rc,F as hr,M as ic,r as oc,V as ac,s as cc,t as lc,W as Hs,u as dc,v as uc,w as hc,I as fc}from"./vendor-icons-BvCtGbt1.js";import{d as it,e as pc,f as gc}from"./vendor-utils-4FcTwKPj.js";import{_ as ue,E as mc}from"./vendor-pdf-CVyNPGVr.js";import{A as yc,m as bc}from"./vendor-motion-Dz5URUo4.js";import{R as xc}from"./vendor-charts-B7ViBL9w.js";const Sc=s=>{const e=s.split(/\r?\n/);if(e.length<2)return[];const t=e[0],n=[",",";"," "];let i=",",a=0;n.forEach(x=>{const p=t.split(x).length;p>a&&(a=p,i=x)});const d=x=>{const p=[];let u=!1,P="";for(let I=0;I<x.length;I++){const _=x[I];_==='"'?u=!u:_===i&&!u?(p.push(P.trim()),P=""):P+=_}return p.push(P.trim()),p},l=d(t).map(x=>x.toLowerCase().replace(/["'\r]/g,"").trim()),h=l.findIndex(x=>x.includes("name")||x.includes("student")||x.includes("姓名")||x.includes("学生")),f=l.findIndex(x=>x.includes("email")||x.includes("mail")||x.includes("邮箱")),b=h>=0?h:0,v=f>=0?f:1,C=[];for(let x=1;x<e.length;x++){if(!e[x].trim())continue;const p=d(e[x]),u=p[b]?p[b].replace(/["'\r]/g,"").trim():"",P=p[v]?p[v].replace(/["'\r]/g,"").trim():"";u&&C.push({name:u,email:P})}return C},qn={zh:{migratableBadge:"可迁移",migrateToFormat:"迁移到新格式",migrationPromptHeading:"发现可迁移的旧格式插件",migrationPromptBody:"该插件使用旧格式运行。上传新格式 ZIP 包以完成迁移,迁移后旧版本可安全卸载。",zipParseError:"ZIP 文件解析失败,请确认文件包含有效的 manifest.json",workerActivationError:"插件在 Worker 环境中激活失败,请检查插件代码与浏览器兼容性",extensionLoadError:"扩展组件加载失败",retry:"重新加载",noExtensionPoints:"暂无已注册的扩展组件",dropZipHere:"拖拽 ZIP 文件到此处",zipFileHint:"仅支持 .zip 格式的插件包",analyzing:"分析中...",dragActive:"释放以上传",legacyTooltip:"该插件使用旧执行格式运行。新格式版本可能可用。",ready:"就绪",uploadZipPlugin:"上传并安装 ZIP 插件",agentTitle:"内核助手",agentSubtitle:"自主 Shell 控制器",agentIntro:"你好!我是你的教育系统 OS 内核助手。你可以让我“创建一节物理课并在白板上画一个圆”,我将通过底层总线为你构建。",placeholder:"例如:创建一节历史课并画一张地图...",dashboard:"系统总览",kernelRunning:"系统正常运行",lessons:"课程",noLessons:"暂无课程。请让助手创建一节课!",noContent:"无内容...",whiteboardCanvas:"白板画布",emptyWhiteboard:"白板为空",simulationError:"系统错误:执行 OS 命令失败。",executedCommands:"执行的命令:",switchLang:"Switch to English",plugins:"插件中心",uploadPlugin:"上传并安装插件",pluginSource:"扩展插件源码 (JS)",installPlugin:"验证并安装",installing:"安装中...",installedPlugins:"已运行插件",noPlugins:"未发现第三方插件",lessonContent:"课程教案与笔记",eventStream:"内核审计事件流",selectLesson:"请先在左侧选择一节课程",systemLogs:"系统日志",hideLogs:"隐藏日志",showLogs:"显示日志",approvals:"待审批高危操作",approve:"批准",reject:"拒绝",noApprovals:"暂无待审批命令",fileSystem:"虚拟文件系统",noFiles:"当前目录为空",processes:"进程管理",noProcesses:"没有正在运行的进程",processLogs:"查看日志",classes:"班级管理",students:"学生管理",noClasses:"暂无班级",noStudents:"暂无学生"},en:{migratableBadge:"Migratable",migrateToFormat:"Migrate to New Format",migrationPromptHeading:"Legacy Plugin Detected",migrationPromptBody:"This plugin runs in legacy mode. Upload a new-format ZIP package to migrate. The old version can be safely uninstalled afterwards.",zipParseError:"Failed to parse ZIP file. Ensure the package contains a valid manifest.json.",workerActivationError:"Plugin activation in Worker environment failed. Check plugin code and browser compatibility.",extensionLoadError:"Extension failed to load",retry:"Retry Load",noExtensionPoints:"No extension points registered",dropZipHere:"Drop ZIP file here",zipFileHint:".zip plugin packages only",analyzing:"Analyzing...",dragActive:"Release to upload",legacyTooltip:"This plugin uses the old execution format. A new-format version may be available.",ready:"Ready",uploadZipPlugin:"Upload & Install ZIP Plugin",agentTitle:"Kernel Agent",agentSubtitle:"Autonomous Shell Controller",agentIntro:'Hello! I am your Educational OS Kernel Agent. You can ask me to "create a physics lesson and draw a circle on its whiteboard" and I will use the Command Bus to build it.',placeholder:"e.g. Create a history lesson and draw a map...",dashboard:"OS Dashboard",kernelRunning:"Kernel Running",lessons:"Lessons",noLessons:"No lessons yet. Ask the Agent to create one!",noContent:"No content...",whiteboardCanvas:"Whiteboard Canvas",emptyWhiteboard:"Empty Whiteboard",simulationError:"Simulation Error: Failed to execute OS command.",executedCommands:"Executed Commands: ",switchLang:"切换到中文",plugins:"Plugin Center",uploadPlugin:"Upload & Install Plugin",pluginSource:"Extension Source Code (JS)",installPlugin:"Validate & Install",installing:"Installing...",installedPlugins:"Running Plugins",noPlugins:"No 3rd-party plugins found",lessonContent:"Lesson Content & Notes",eventStream:"Kernel Audit Event Stream",selectLesson:"Please select a lesson from the left",systemLogs:"System Logs",hideLogs:"Hide Logs",showLogs:"Show Logs",approvals:"Pending Approvals",approve:"Approve",reject:"Reject",noApprovals:"No pending commands",fileSystem:"Virtual File System",noFiles:"Directory is empty",processes:"Process Manager",noProcesses:"No active processes",processLogs:"View Logs",classes:"Classes",students:"Students",noClasses:"No classes found",noStudents:"No students found"}},vc=Ve.memo(function({onLoginSuccess:e,lang:t}){const[n,i]=o.useState("teacher"),[a,d]=o.useState(null),[l,h]=o.useState(""),[f,b]=o.useState(""),[v,C]=o.useState(""),[x,p]=o.useState(!1),[u,P]=o.useState([]),[I,_]=o.useState(""),[S,g]=o.useState(""),[E,O]=o.useState(""),[k,z]=o.useState(""),[M,y]=o.useState(!1);o.useEffect(()=>{(async()=>{try{const B=await fetch("/api/students");if(B.ok){const j=await B.json();P(j),j.length>0&&_(j[0].id)}}catch(B){console.warn("Failed to fetch student roster for login selection:",B)}})()},[]),o.useEffect(()=>{(async()=>{try{const B=await fetch("/api/site-settings");if(B.ok){const j=await B.json();d(j)}}catch(B){console.warn("Failed to fetch site settings for login branding:",B)}})()},[]);const N=async A=>{if(A.preventDefault(),!l.trim()||!f){C(t==="zh"?"请输入完整的用户名和密码。":"Please fill in both key fields.");return}try{C(""),p(!0);const B=await fetch("/api/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({entrance:"teacher",username:l.trim(),password:f})});if(B.ok){const j=await B.json();e(j.session)}else{const j=await B.json();C(j.error||(t==="zh"?"用户名或密码不正确":"Invalid username or password"))}}catch{C(t==="zh"?"网络连接异常,请重试":"Network communication failure. Please try again.")}finally{p(!1)}},D=async A=>{A.preventDefault();const B=I||S.trim();if(!B){z(t==="zh"?"请选择或输入学号/学生标识。":"Please select or enter your Student ID.");return}if(!E.trim()){z(t==="zh"?"请输入个人密码或临时班级密码。":"Please enter your personal password or temporary class passcode.");return}try{z(""),y(!0);const j=await fetch("/api/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({entrance:"student",studentId:B,password:E.trim()})});if(j.ok){const m=await j.json();e(m.session)}else{const m=await j.json();z(m.error||(t==="zh"?"找不到该学生记录":"Student record not found"))}}catch{z(t==="zh"?"网络连接异常,请重试":"Network connection failure. Please try again.")}finally{y(!1)}};return r.jsxs("div",{className:"min-h-screen bg-slate-900 flex flex-col items-center justify-center p-4 relative overflow-hidden font-sans",id:"login_page_container",children:[r.jsx("div",{className:"absolute top-[-10%] left-[-10%] w-[40rem] h-[40rem] rounded-full bg-indigo-500/10 blur-3xl -z-10"}),r.jsx("div",{className:"absolute bottom-[-10%] right-[-10%] w-[35rem] h-[35rem] rounded-full bg-violet-500/10 blur-3xl -z-10"}),r.jsxs("div",{className:"w-full max-w-md bg-slate-950/85 backdrop-blur-md rounded-2xl border border-slate-800 shadow-2xl p-6 sm:p-8",id:"login_card",children:[r.jsxs("div",{className:"text-center mb-8",children:[a?.logoUrl?r.jsx("img",{src:a.logoUrl,alt:a.siteName||"logo",className:"inline-block h-16 w-16 object-contain mb-4 rounded-xl"}):r.jsx("div",{className:"inline-flex items-center justify-center p-3 bg-gradient-to-tr from-indigo-500 to-indigo-600 rounded-2xl shadow-lg border border-indigo-400/20 mb-4 text-white",children:r.jsx(Fn,{size:32})}),r.jsxs("h1",{className:"text-2xl sm:text-3xl font-black text-white tracking-tight flex items-center justify-center gap-2",children:[a?.siteName||"OpenLearn Next"," ",r.jsx("span",{className:"text-indigo-400 font-medium text-xs bg-indigo-500/20 px-2 py-0.5 rounded-full border border-indigo-400/20",children:"V2.0"})]}),r.jsx("p",{className:"text-slate-400 text-xs sm:text-sm mt-2",children:a?.slogan||(t==="zh"?"下一代智能数字化学习系统":"Next-Generation Intelligent Digital Learning Platform")})]}),r.jsxs("div",{className:"flex bg-slate-900 p-1 rounded-xl border border-slate-800 gap-1 mb-6",children:[r.jsxs("button",{onClick:()=>i("teacher"),className:`flex-1 py-2.5 rounded-lg text-xs font-bold transition-all duration-200 flex items-center justify-center gap-2 focus:outline-none ${n==="teacher"?"bg-indigo-600 text-white shadow-md":"text-slate-400 hover:text-slate-200 hover:bg-slate-800/40"}`,children:[r.jsx(qa,{size:14}),t==="zh"?"教师与管理端":"Teacher / Staff Portal"]}),r.jsxs("button",{onClick:()=>i("student"),className:`flex-1 py-2.5 rounded-lg text-xs font-bold transition-all duration-200 flex items-center justify-center gap-2 focus:outline-none ${n==="student"?"bg-indigo-600 text-white shadow-md":"text-slate-400 hover:text-slate-200 hover:bg-slate-800/40"}`,children:[r.jsx(cr,{size:14}),t==="zh"?"学生自助端":"Student Self-Service"]})]}),n==="teacher"?r.jsxs("form",{onSubmit:N,className:"space-y-4",children:[v&&r.jsxs("div",{className:"p-3 bg-red-950/50 border border-red-800 text-red-300 text-xs rounded-xl flex items-center gap-2",children:[r.jsx(Bn,{size:15,className:"shrink-0"}),r.jsx("span",{children:v})]}),r.jsxs("div",{className:"space-y-1.5",children:[r.jsxs("label",{className:"text-xs font-medium text-slate-400 flex items-center gap-1.5",children:[r.jsx(Ct,{size:13}),t==="zh"?"教工账户名 / username":"Staff Username"]}),r.jsx("input",{type:"text",value:l,onChange:A=>h(A.target.value),placeholder:t==="zh"?"输入教工账户名":"Enter staff username",className:"w-full bg-slate-900 border border-slate-800 focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500 rounded-xl text-xs sm:text-sm p-3 text-white outline-none placeholder-slate-500 transition-colors",required:!0})]}),r.jsxs("div",{className:"space-y-1.5",children:[r.jsxs("label",{className:"text-xs font-medium text-slate-400 flex items-center gap-1.5",children:[r.jsx(Vn,{size:13}),t==="zh"?"输入登录密码 / password":"Access Password"]}),r.jsx("input",{type:"password",value:f,onChange:A=>b(A.target.value),placeholder:t==="zh"?"输入登录密码":"Enter access password",className:"w-full bg-slate-900 border border-slate-800 focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500 rounded-xl text-xs sm:text-sm p-3 text-white outline-none placeholder-slate-500 transition-colors",required:!0})]}),r.jsxs("button",{type:"submit",disabled:x,className:"w-full mt-6 bg-gradient-to-r from-indigo-600 to-violet-600 hover:from-indigo-500 hover:to-violet-500 disabled:opacity-50 text-white font-bold py-3 px-4 rounded-xl text-xs sm:text-sm flex items-center justify-center gap-2 transition-all duration-200 cursor-pointer shadow-lg shadow-indigo-600/20 active:scale-[0.98]",children:[r.jsx("span",{children:x?t==="zh"?"鉴权登录中...":"Authorizing...":t==="zh"?"安全验证登录":"Authorized Sign In"}),r.jsx(Wn,{size:15})]})]}):r.jsxs("form",{onSubmit:D,className:"space-y-4",children:[k&&r.jsxs("div",{className:"p-3 bg-red-950/50 border border-red-800 text-red-300 text-xs rounded-xl flex items-center gap-2",children:[r.jsx(Bn,{size:15,className:"shrink-0"}),r.jsx("span",{children:k})]}),u.length>0?r.jsxs("div",{className:"space-y-1.5",children:[r.jsxs("label",{className:"text-xs font-medium text-slate-400 flex items-center gap-1.5",children:[r.jsx(Fn,{size:14}),t==="zh"?"从学生花名册中快速选择":"Quick Access Student Select"]}),r.jsx("select",{value:I,onChange:A=>{_(A.target.value),g("")},className:"w-full bg-slate-900 border border-slate-800 focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500 rounded-xl text-xs sm:text-sm p-3 text-white outline-none transition-colors cursor-pointer",children:u.map(A=>r.jsxs("option",{value:A.id,children:[A.name," (",A.student_number||A.id,")"]},A.id))}),r.jsx("p",{className:"text-[10px] text-slate-500 font-medium",children:t==="zh"?"✨ 在沙盒调试中,你可以直接下拉选择已有的学生账户一键登录为该生。":"✨ Sandbox help: Quick select existing students on file to simulate as student."})]}):null,r.jsxs("div",{className:"relative flex py-2 items-center",children:[r.jsx("div",{className:"flex-grow border-t border-slate-850"}),r.jsx("span",{className:"flex-shrink mx-3 text-[10px] font-bold text-slate-500 uppercase tracking-wider",children:t==="zh"?"或手动输入学号":"Or input key manually"}),r.jsx("div",{className:"flex-grow border-t border-slate-850"})]}),r.jsxs("div",{className:"space-y-1.5",children:[r.jsxs("label",{className:"text-xs font-medium text-slate-400 flex items-center gap-1.5",children:[r.jsx(Ct,{size:13}),t==="zh"?"学号 / Student ID":"Student Access Key"]}),r.jsx("input",{type:"text",value:S,onChange:A=>{g(A.target.value),_("")},placeholder:t==="zh"?"手工输入您的特有学号":"Enter specific numeric ID code",className:"w-full bg-slate-900 border border-slate-800 focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500 rounded-xl text-xs sm:text-sm p-3 text-white outline-none placeholder-slate-500 transition-colors"})]}),r.jsxs("div",{className:"space-y-1.5",children:[r.jsxs("label",{className:"text-xs font-medium text-slate-400 flex items-center gap-1.5",children:[r.jsx(Vn,{size:13}),t==="zh"?"个人密码 / 临时班级密码":"Personal Password / Class Passcode"]}),r.jsx("input",{type:"password",required:!0,value:E,onChange:A=>O(A.target.value),placeholder:t==="zh"?"输入个人密码或临时班级密码":"Enter personal password or class passcode",className:"w-full bg-slate-900 border border-slate-800 focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500 rounded-xl text-xs sm:text-sm p-3 text-white outline-none placeholder-slate-500 transition-colors"})]}),r.jsxs("button",{type:"submit",disabled:M,className:"w-full mt-6 bg-gradient-to-r from-indigo-600 to-violet-600 hover:from-indigo-500 hover:to-violet-500 disabled:opacity-50 text-white font-bold py-3 px-4 rounded-xl text-xs sm:text-sm flex items-center justify-center gap-2 transition-all duration-200 cursor-pointer shadow-lg shadow-indigo-600/20 active:scale-[0.98]",children:[r.jsx("span",{children:M?t==="zh"?"正在连接学生终端...":"Entering Desk...":t==="zh"?"登录学生智慧桌面":"Login Interactive Desk"}),r.jsx(Wn,{size:15})]})]})]})]})});function wc({session:s,lang:e,onLogout:t,onProfile:n}){const[i,a]=o.useState(!1),d=o.useRef(null);o.useEffect(()=>{if(!i)return;const h=f=>{d.current&&!d.current.contains(f.target)&&a(!1)};return document.addEventListener("mousedown",h),()=>document.removeEventListener("mousedown",h)},[i]);const l=(h,f)=>e==="zh"?h:f;return r.jsxs("div",{className:"relative",ref:d,children:[r.jsxs("button",{type:"button",onClick:()=>a(h=>!h),"aria-haspopup":"menu","aria-expanded":i,title:s.name,className:"flex items-center gap-1 rounded-full p-1 hover:bg-gray-100 transition-colors cursor-pointer",children:[r.jsx("span",{className:"w-9 h-9 rounded-full bg-indigo-100 text-indigo-600 flex items-center justify-center shrink-0 overflow-hidden",children:s.avatar?r.jsx("img",{src:s.avatar,alt:s.name,className:"w-full h-full object-cover"}):r.jsx(Ct,{size:20})}),r.jsx(lr,{size:14,className:`text-gray-400 transition-transform duration-200 ${i?"rotate-180":""}`})]}),i&&r.jsxs("div",{role:"menu",className:"absolute right-0 mt-2 w-52 bg-white border border-gray-200 shadow-lg rounded-xl z-50 overflow-hidden py-1",children:[r.jsxs("div",{className:"px-4 py-2 border-b border-gray-100",children:[r.jsx("p",{className:"text-sm font-semibold text-gray-800 truncate",title:s.name,children:s.name}),r.jsx("p",{className:"text-xs text-gray-400 truncate",children:s.username})]}),r.jsxs("button",{type:"button",role:"menuitem",onClick:()=>{a(!1),n()},className:"w-full flex items-center gap-2 px-4 py-2 text-sm text-gray-700 hover:bg-gray-50 transition-colors cursor-pointer",children:[r.jsx(Ct,{size:16,className:"text-gray-400"}),l("个人资料","Profile")]}),r.jsxs("button",{type:"button",role:"menuitem",onClick:()=>{a(!1),t()},className:"w-full flex items-center gap-2 px-4 py-2 text-sm text-rose-600 hover:bg-rose-50 transition-colors cursor-pointer",children:[r.jsx(Ua,{size:16}),l("注销登录","Sign Out")]})]})]})}function Cc(s){const{activeRole:e,lang:t,teacherTab:n,studentViewStatus:i,session:a,activeStudentId:d,students:l,studentDashboardData:h,isNotificationsOpen:f,studentNotifications:b,unreadNotifications:v,readNotifications:C,dbConnected:x,dbStatus:p,siteInfo:u,setActiveStudentId:P,setReadNotifications:I,setIsSystemResourceLibraryOpen:_,setProfileOpen:S,setTeacherTab:g,setStudentViewStatus:E,setIsNotificationsOpen:O,setSelectedNotificationForModal:k,handleLogout:z,toggleLanguage:M}=s;return r.jsxs("header",{className:"h-16 border-b border-gray-200 bg-white flex items-center px-6 justify-between shrink-0 shadow-sm relative z-20",children:[r.jsxs("div",{className:"flex items-center gap-4 sm:gap-6",children:[r.jsxs("button",{onClick:()=>{e==="teacher"?g("dashboard"):e==="student"&&E("dashboard")},className:"flex items-center gap-2.5 shrink-0 hover:opacity-80 transition-opacity cursor-pointer",title:t==="zh"?"返回系统总览":"Back to Dashboard",children:[u.logoUrl?r.jsx("img",{src:u.logoUrl,alt:"site logo",className:"h-8 w-8 object-contain rounded-lg shrink-0"}):r.jsx("div",{className:"h-8 w-8 rounded-lg bg-gradient-to-tr from-indigo-600 to-indigo-700 flex items-center justify-center text-white font-black text-sm shadow-xs shrink-0",children:"OL"}),r.jsxs("div",{className:"flex items-baseline gap-2",children:[r.jsx("span",{className:"text-base font-black text-slate-900 tracking-tight",children:u.siteName||"OpenLearn Next"}),r.jsxs("span",{className:"text-[10px] font-medium text-slate-400 tracking-tight",children:["v","0.2.7"]}),u.slogan&&r.jsx("span",{className:"hidden md:inline text-xs text-slate-400 font-normal truncate max-w-[200px]",children:u.slogan})]})]}),r.jsxs("button",{onClick:()=>{e==="teacher"?g("dashboard"):e==="student"&&E("dashboard")},className:`flex items-center gap-1.5 px-3 py-1.5 rounded-md text-sm font-medium transition-colors cursor-pointer ${e==="teacher"&&n==="dashboard"||e==="student"&&i==="dashboard"?"bg-indigo-50 text-indigo-700":"text-slate-600 hover:text-indigo-600 hover:bg-slate-100"}`,children:[r.jsx(Ga,{size:16}),t==="zh"?"系统总览":"Dashboard"]}),e==="student"&&r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"text-slate-300 font-light text-lg select-none",children:"/"}),r.jsxs("h2",{className:"font-semibold text-gray-800 tracking-tight flex items-center gap-2",children:[r.jsx(Ha,{size:20,className:"text-gray-400"}),"Student Dashboard"]})]}),e==="student"&&a.role==="teacher"&&r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:"text-sm text-gray-500",children:"View as:"}),r.jsxs("select",{className:"border border-gray-200 rounded p-1 text-sm bg-white",value:d||"",onChange:y=>P(y.target.value),children:[r.jsx("option",{value:"",children:"-- Select Student --"}),l.map(y=>r.jsx("option",{value:y.id,children:y.name},y.id))]})]})]}),r.jsxs("div",{className:"flex items-center gap-4 text-sm text-gray-500",children:[e==="student"&&d&&h&&r.jsxs("div",{className:"relative",children:[r.jsxs("button",{onClick:()=>O(!f),className:"relative p-2 text-gray-500 hover:text-gray-700 hover:bg-gray-100 rounded-full transition-colors",children:[r.jsx(Qa,{size:20}),v.length>0&&r.jsx("span",{className:"absolute top-1 right-1 bg-red-500 text-white text-[10px] font-bold px-1.5 py-0.5 rounded-full flex items-center justify-center min-w-[18px]",children:v.length})]}),f&&r.jsxs("div",{className:"absolute right-0 mt-2 w-80 bg-white border border-gray-200 shadow-lg rounded-xl z-50 overflow-hidden",children:[r.jsxs("div",{className:"p-3 border-b border-gray-100 flex justify-between items-center bg-gray-50",children:[r.jsx("h3",{className:"font-semibold text-gray-800",children:"Notifications"}),v.length>0&&r.jsx("button",{onClick:async()=>{if(!d)return;try{const N=b.filter(D=>!C.has(D.id)).map(D=>fetch(`/api/students/${d}/read_notifications`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({notificationId:D.id})}));await Promise.all(N)}catch(N){console.error(N)}const y=new Set(C);b.forEach(N=>y.add(N.id)),I(y)},className:"text-xs text-indigo-600 hover:text-indigo-800 font-medium",children:"Mark all as read"})]}),r.jsx("div",{className:"max-h-96 overflow-y-auto",children:b.length===0?r.jsx("div",{className:"p-4 text-center text-sm text-gray-500 italic",children:"No notifications."}):r.jsx("div",{className:"divide-y divide-gray-100",children:b.map(y=>{const N=!C.has(y.id);return r.jsx("div",{className:`p-3 hover:bg-gray-50 cursor-pointer ${N?"bg-indigo-50/30":""}`,onClick:()=>{if(N){d&&fetch(`/api/students/${d}/read_notifications`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({notificationId:y.id})}).catch(console.error);const A=new Set(C);A.add(y.id),I(A)}const D=h?.assignments?.find(A=>A.id===y.relatedId);k({...y,assignment:D}),O(!1)},children:r.jsxs("div",{className:"flex gap-3",children:[r.jsx("div",{className:"mt-0.5",children:y.type==="new_assignment"?r.jsx(dr,{size:16,className:"text-indigo-500"}):y.type==="rollcall_picked"?r.jsx(ur,{size:16,className:"text-amber-500 animate-pulse"}):r.jsx(an,{size:16,className:"text-green-500"})}),r.jsxs("div",{className:"flex-1",children:[r.jsx("div",{className:`text-sm ${N?"font-semibold text-gray-900":"font-medium text-gray-700"}`,children:y.title}),r.jsx("div",{className:`text-xs mt-0.5 ${N?"text-gray-600":"text-gray-500"}`,children:y.message})]}),N&&r.jsx("div",{className:"w-2 h-2 rounded-full bg-indigo-500 mt-1"})]})},y.id)})})})]})]}),r.jsxs("button",{onClick:()=>_(!0),className:"flex items-center gap-1.5 hover:text-indigo-600 transition-colors bg-white px-3 py-1.5 rounded-md border border-gray-200 shadow-sm font-medium cursor-pointer",children:[r.jsx(Ys,{size:14,className:"text-emerald-500 animate-pulse"}),t==="zh"?"系统资源库":"System Resource Library"]}),r.jsx("button",{onClick:M,title:t==="zh"?"Switch to English":"切换为中文",className:"p-2 hover:bg-slate-100 text-slate-600 hover:text-indigo-600 transition-colors bg-white rounded-lg border border-gray-200 shadow-3xs flex items-center justify-center shrink-0 cursor-pointer",children:r.jsx(Ys,{size:16})}),(()=>{const y=p==="error"||!x?{bg:"bg-rose-50 border-rose-200 text-rose-600 hover:bg-rose-100 animate-pulse",dot:"bg-rose-500",ping:"bg-rose-400",label:t==="zh"?"SQLite 数据库连接出错或已断开":"SQLite DB Error / Disconnected"}:p==="warning"?{bg:"bg-amber-50 border-amber-200 text-amber-600 hover:bg-amber-100",dot:"bg-amber-500",ping:"bg-amber-400",label:t==="zh"?"SQLite 数据库存在状态警告":"SQLite DB Warning"}:{bg:"bg-emerald-50 border-emerald-200 text-emerald-600 hover:bg-emerald-100",dot:"bg-emerald-500",ping:"bg-emerald-400",label:t==="zh"?"SQLite 数据库连接正常":"SQLite DB Connected & Normal"};return r.jsxs("div",{id:"db-connection-status-badge",className:`w-8 h-8 rounded-lg border flex items-center justify-center relative select-none shrink-0 cursor-pointer transition-colors shadow-3xs ${y.bg}`,title:y.label,children:[r.jsx(Ja,{size:15}),r.jsxs("span",{className:"absolute -top-0.5 -right-0.5 flex h-2.5 w-2.5",children:[r.jsx("span",{className:`animate-ping absolute inline-flex h-full w-full rounded-full opacity-75 ${y.ping}`}),r.jsx("span",{className:`relative inline-flex rounded-full h-2.5 w-2.5 ${y.dot}`})]})]})})(),r.jsx(wc,{session:a,lang:t,onLogout:z,onProfile:()=>S(!0)})]})]})}function Ec({open:s,session:e,lang:t,onClose:n,onSaved:i,onAvatar:a}){const[d,l]=o.useState(e.name),[h,f]=o.useState(!1),[b,v]=o.useState(null),C=o.useRef(null),[x,p]=o.useState(!1),[u,P]=o.useState(null),[I,_]=o.useState(!1),[S,g]=o.useState(""),[E,O]=o.useState(""),[k,z]=o.useState(""),[M,y]=o.useState(!1),[N,D]=o.useState(null),[A,B]=o.useState(!1);if(!s)return null;const j=(q,Q)=>t==="zh"?q:Q,m=e.role==="teacher"?e.subRole==="administrator"?j("管理员","Administrator"):j("教师","Teacher"):j("学生","Student"),L=d.trim(),w=L.length>0&&L!==e.name,R=async()=>{if(!(!w||h)){f(!0),v(null);try{const q=await fetch("/api/auth/profile",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:L})}),Q=await q.json();if(!q.ok){v(Q.error||(t==="zh"?"保存失败":"Save failed"));return}i(Q.name??L)}catch{v(t==="zh"?"网络错误,请重试":"Network error, please retry")}finally{f(!1)}}},F=S.length>0&&E.length>=8&&/[a-zA-Z]/.test(E)&&/[0-9]/.test(E)&&E===k,Z=async()=>{if(!(!F||M)){y(!0),D(null);try{const q=await fetch("/api/auth/change-password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({oldPassword:S,newPassword:E})}),Q=await q.json();if(!q.ok){D(Q.error||(t==="zh"?"修改失败":"Change failed"));return}B(!0),g(""),O(""),z(""),_(!1)}catch{D(t==="zh"?"网络错误,请重试":"Network error, please retry")}finally{y(!1)}}},ae=async q=>{const Q=q.target.files?.[0];if(q.target.value="",!!Q){p(!0),P(null);try{const he=await new Promise((We,ze)=>{const se=new FileReader;se.onload=()=>We(se.result),se.onerror=()=>ze(se.error),se.readAsDataURL(Q)}),ce=await fetch("/api/auth/avatar",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filename:Q.name,base64Data:he})}),Ce=await ce.json();if(!ce.ok){P(Ce.error||(t==="zh"?"上传失败":"Upload failed"));return}a?.(Ce.avatar)}catch{P(t==="zh"?"网络错误,请重试":"Network error, please retry")}finally{p(!1)}}},G=async()=>{p(!0),P(null);try{const q=await fetch("/api/auth/avatar",{method:"DELETE"}),Q=await q.json().catch(()=>({}));if(!q.ok){P(Q.error||(t==="zh"?"移除失败":"Remove failed"));return}a?.(null)}catch{P(t==="zh"?"网络错误,请重试":"Network error, please retry")}finally{p(!1)}};return r.jsx("div",{className:"fixed inset-0 bg-black/40 backdrop-blur-xs flex items-center justify-center z-50 p-4",onClick:n,children:r.jsxs("div",{className:"bg-white rounded-2xl shadow-xl w-full max-w-md overflow-hidden",onClick:q=>q.stopPropagation(),children:[r.jsxs("div",{className:"flex items-center justify-between px-5 py-4 border-b border-gray-100",children:[r.jsx("h3",{className:"font-semibold text-gray-800",children:j("个人资料","Profile")}),r.jsx("button",{onClick:n,className:"text-gray-400 hover:text-gray-600 cursor-pointer",children:r.jsx(Qt,{size:18})})]}),r.jsxs("div",{className:"p-5 space-y-5",children:[r.jsxs("div",{className:"flex items-center gap-3",children:[r.jsx("span",{className:"w-14 h-14 rounded-full bg-indigo-100 text-indigo-600 flex items-center justify-center shrink-0 overflow-hidden",children:e.avatar?r.jsx("img",{src:e.avatar,alt:e.name,className:"w-full h-full object-cover"}):r.jsx(Ct,{size:28})}),r.jsxs("div",{className:"min-w-0",children:[r.jsx("p",{className:"text-base font-semibold text-gray-800 truncate",children:e.name}),r.jsx("p",{className:"text-xs text-gray-400",children:m}),r.jsxs("div",{className:"mt-1.5 flex items-center gap-3",children:[r.jsx("button",{type:"button",onClick:()=>C.current?.click(),disabled:x,className:"text-xs text-indigo-600 hover:text-indigo-800 disabled:opacity-50 cursor-pointer",children:x?j("上传中…","Uploading…"):e.avatar?j("更换头像","Change avatar"):j("上传头像","Upload avatar")}),e.avatar&&r.jsx("button",{type:"button",onClick:G,disabled:x,className:"text-xs text-rose-500 hover:text-rose-700 disabled:opacity-50 cursor-pointer",children:j("移除","Remove")})]}),r.jsx("input",{ref:C,type:"file",accept:"image/png,image/jpeg,image/gif,image/webp",className:"hidden",onChange:ae})]})]}),u&&r.jsx("p",{className:"text-xs text-rose-500",children:u}),r.jsxs("div",{children:[r.jsx("label",{className:"block text-sm text-gray-500 mb-1",children:j("显示名称","Display Name")}),r.jsxs("div",{className:"flex gap-2",children:[r.jsx("input",{value:d,onChange:q=>l(q.target.value),maxLength:50,className:"flex-1 border border-gray-300 rounded-lg px-3 py-2 text-sm text-gray-800 focus:outline-none focus:ring-2 focus:ring-indigo-200"}),r.jsx("button",{onClick:R,disabled:!w||h,className:"px-4 py-2 rounded-lg bg-indigo-600 text-white text-sm font-medium disabled:opacity-40 enabled:hover:bg-indigo-700 transition-colors cursor-pointer shrink-0",children:h?j("保存中…","Saving…"):j("保存","Save")})]}),b&&r.jsx("p",{className:"text-xs text-rose-500 mt-1",children:b})]}),r.jsxs("div",{className:"border-t border-gray-100 pt-4",children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsxs("span",{className:"text-sm font-medium text-gray-700 flex items-center gap-2",children:[r.jsx(Za,{size:16,className:"text-gray-400"}),j("修改密码","Change Password")]}),!I&&!A&&r.jsx("button",{onClick:()=>{_(!0),D(null)},className:"text-sm text-indigo-600 hover:text-indigo-800 cursor-pointer",children:j("修改","Edit")})]}),A&&r.jsxs("p",{className:"mt-2 flex items-center gap-1.5 text-sm text-emerald-600",children:[r.jsx(an,{size:16}),j("密码已修改,其他设备的登录已失效","Password changed. Other devices were logged out.")]}),I&&r.jsxs("div",{className:"mt-3 space-y-3",children:[r.jsx("input",{type:"password",value:S,onChange:q=>g(q.target.value),placeholder:j("当前密码","Current password"),className:"w-full border border-gray-300 rounded-lg px-3 py-2 text-sm text-gray-800 focus:outline-none focus:ring-2 focus:ring-indigo-200"}),r.jsx("input",{type:"password",value:E,onChange:q=>O(q.target.value),placeholder:j("新密码(≥8 位,含字母和数字)","New password (≥8 chars, letters + numbers)"),className:"w-full border border-gray-300 rounded-lg px-3 py-2 text-sm text-gray-800 focus:outline-none focus:ring-2 focus:ring-indigo-200"}),r.jsx("input",{type:"password",value:k,onChange:q=>z(q.target.value),placeholder:j("确认新密码","Confirm new password"),className:"w-full border border-gray-300 rounded-lg px-3 py-2 text-sm text-gray-800 focus:outline-none focus:ring-2 focus:ring-indigo-200"}),N&&r.jsx("p",{className:"text-xs text-rose-500",children:N}),r.jsxs("div",{className:"flex gap-2 justify-end",children:[r.jsx("button",{onClick:()=>{_(!1),g(""),O(""),z(""),D(null)},className:"px-4 py-2 rounded-lg border border-gray-300 text-sm text-gray-600 hover:bg-gray-50 cursor-pointer",children:j("取消","Cancel")}),r.jsx("button",{onClick:Z,disabled:!F||M,className:"px-4 py-2 rounded-lg bg-indigo-600 text-white text-sm font-medium disabled:opacity-40 enabled:hover:bg-indigo-700 transition-colors cursor-pointer",children:M?j("提交中…","Submitting…"):j("提交","Submit")})]})]})]}),r.jsxs("div",{className:"border-t border-gray-100 pt-4 space-y-2",children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsx("span",{className:"text-sm text-gray-400",children:j("用户名(登录账号)","Username (login)")}),r.jsx("span",{className:"text-sm font-medium text-gray-700 truncate max-w-[60%]",title:e.username,children:e.username||"-"})]}),r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsx("span",{className:"text-sm text-gray-400",children:j("角色","Role")}),r.jsx("span",{className:"text-sm font-medium text-gray-700",children:m})]})]})]})]})})}const $u={slate:{iconBg:"bg-slate-100",iconText:"text-slate-600",cardHoverBorder:"hover:border-slate-400",cardHoverRing:"group-hover:ring-slate-300",cardHoverShadow:"group-hover:shadow-slate-200/70",groupAccent:"bg-slate-400",groupText:"text-slate-500"},blue:{iconBg:"bg-blue-100",iconText:"text-blue-600",cardHoverBorder:"hover:border-blue-400",cardHoverRing:"group-hover:ring-blue-300",cardHoverShadow:"group-hover:shadow-blue-200/70",groupAccent:"bg-blue-400",groupText:"text-blue-500"},violet:{iconBg:"bg-violet-100",iconText:"text-violet-600",cardHoverBorder:"hover:border-violet-400",cardHoverRing:"group-hover:ring-violet-300",cardHoverShadow:"group-hover:shadow-violet-200/70",groupAccent:"bg-violet-400",groupText:"text-violet-500"},amber:{iconBg:"bg-amber-100",iconText:"text-amber-600",cardHoverBorder:"hover:border-amber-400",cardHoverRing:"group-hover:ring-amber-300",cardHoverShadow:"group-hover:shadow-amber-200/70",groupAccent:"bg-amber-400",groupText:"text-amber-500"},rose:{iconBg:"bg-rose-100",iconText:"text-rose-600",cardHoverBorder:"hover:border-rose-400",cardHoverRing:"group-hover:ring-rose-300",cardHoverShadow:"group-hover:shadow-rose-200/70",groupAccent:"bg-rose-400",groupText:"text-rose-500"},emerald:{iconBg:"bg-emerald-100",iconText:"text-emerald-600",cardHoverBorder:"hover:border-emerald-400",cardHoverRing:"group-hover:ring-emerald-300",cardHoverShadow:"group-hover:shadow-emerald-200/70",groupAccent:"bg-emerald-400",groupText:"text-emerald-500"},cyan:{iconBg:"bg-cyan-100",iconText:"text-cyan-600",cardHoverBorder:"hover:border-cyan-400",cardHoverRing:"group-hover:ring-cyan-300",cardHoverShadow:"group-hover:shadow-cyan-200/70",groupAccent:"bg-cyan-400",groupText:"text-cyan-500"},pink:{iconBg:"bg-pink-100",iconText:"text-pink-600",cardHoverBorder:"hover:border-pink-400",cardHoverRing:"group-hover:ring-pink-300",cardHoverShadow:"group-hover:shadow-pink-200/70",groupAccent:"bg-pink-400",groupText:"text-pink-500"},indigo:{iconBg:"bg-indigo-100",iconText:"text-indigo-600",cardHoverBorder:"hover:border-indigo-400",cardHoverRing:"group-hover:ring-indigo-300",cardHoverShadow:"group-hover:shadow-indigo-200/70",groupAccent:"bg-indigo-400",groupText:"text-indigo-500"}},Fu=[{id:"present",labelZh:"内容呈现",labelEn:"Content"},{id:"assess",labelZh:"评估互动",labelEn:"Assessment"},{id:"manage",labelZh:"课堂管理",labelEn:"Classroom"}],Pc=[{type:"presentation",labelZh:"课件演示",labelEn:"Slides Deck",descriptionZh:"Markdown 幻灯片",descriptionEn:"Markdown slides",icon:Ka,color:"violet",group:"present",defaultData:{markdown:`# Title Slide
|
|
2
|
-
---
|
|
3
|
-
## Slide 2`},editFields:[{key:"markdown",labelZh:"幻灯片内容 (Markdown)",labelEn:"Slides Content (Markdown)",kind:"textarea",placeholderZh:`# 标题
|
|
4
|
-
---
|
|
5
|
-
## 第二页`}]},{type:"code-sandbox",labelZh:"代码沙箱",labelEn:"Code Editor",descriptionZh:"可运行代码",descriptionEn:"Runnable code",icon:Wt,color:"slate",group:"present",defaultData:{code:"console.log('Hello Sandbox!');"},editFields:[{key:"code",labelZh:"代码",labelEn:"Code",kind:"textarea",placeholderZh:"console.log('Hello');"}]},{type:"math-graph",labelZh:"数学函数",labelEn:"Math Grapher",descriptionZh:"函数图像",descriptionEn:"Function graph",icon:Ya,color:"blue",group:"present",defaultData:{equation:"Math.sin(x)"},editFields:[{key:"equation",labelZh:"函数表达式",labelEn:"Equation",kind:"input",placeholderZh:"如 Math.sin(x)"}]},{type:"html-applet",labelZh:"交互网页课件",labelEn:"Interactive Courseware",descriptionZh:"可交互 HTML/ZIP 网页",descriptionEn:"Interactive web/ZIP applet",icon:Ys,color:"emerald",group:"present",defaultData:{code:`<!-- Interactive Web Courseware -->
|
|
6
|
-
<div style='padding:20px; text-align:center;'>
|
|
7
|
-
<h2>Interactive Web Courseware</h2>
|
|
8
|
-
<p>在属性栏中配置本地 ZIP/HTML 部署包。</p>
|
|
9
|
-
</div>`},editFields:[{key:"code",labelZh:"HTML 代码",labelEn:"HTML Code",kind:"textarea",placeholderZh:"<div>…</div>"}]},{type:"quiz",labelZh:"随堂测试",labelEn:"Interactive Quiz",descriptionZh:"选择题互动",descriptionEn:"Multiple choice",icon:cn,color:"amber",group:"assess",defaultData:{question:"New Quiz",options:["A","B","C","D"]},editFields:[{key:"question",labelZh:"题目",labelEn:"Question",kind:"input",placeholderZh:"请输入题目"},{key:"options",labelZh:"选项 (A/B/C/D)",labelEn:"Options (A/B/C/D)",kind:"options"}]},{type:"assignment",labelZh:"作业提交",labelEn:"Assignment",descriptionZh:"布置与提交",descriptionEn:"Submit work",icon:dr,color:"rose",group:"assess",defaultData:{title:"New Assignment",description:"Upload your work here"},editFields:[{key:"title",labelZh:"作业标题",labelEn:"Title",kind:"input",placeholderZh:"如:第一章练习"},{key:"description",labelZh:"说明",labelEn:"Description",kind:"textarea",placeholderZh:"作业要求说明…"}]},{type:"rollcall",labelZh:"随机点名",labelEn:"Random Picker",descriptionZh:"课堂点名",descriptionEn:"Pick a student",icon:Xa,color:"cyan",group:"manage",defaultData:{allStudents:[]},editFields:[]},{type:"hello-world",labelZh:"问候插件",labelEn:"Hello World",descriptionZh:"欢迎问候",descriptionEn:"Welcome greeting",icon:ur,color:"pink",group:"manage",defaultData:{},editFields:[]}],Tc=Pc.reduce((s,e)=>(s[e.type]=e,s),{}),Ne=it(s=>({lang:"zh",activeRole:"teacher",teacherTab:"courses",profileOpen:!1,isCourseWizardOpen:!1,isImportLessonsOpen:!1,isQuizGeneratorOpen:!1,isLessonPreviewVisible:!1,isSystemResourceLibraryOpen:!1,batchPicker:null,isExportWeightModalOpen:!1,toasts:[],siteInfo:{siteName:"",slogan:"",logoUrl:null},setLang:e=>s({lang:e}),setActiveRole:e=>s({activeRole:e}),setTeacherTab:e=>s({teacherTab:e}),setProfileOpen:e=>s({profileOpen:e}),setIsCourseWizardOpen:e=>s({isCourseWizardOpen:e}),setIsImportLessonsOpen:e=>s({isImportLessonsOpen:e}),setIsQuizGeneratorOpen:e=>s({isQuizGeneratorOpen:e}),setIsLessonPreviewVisible:e=>s({isLessonPreviewVisible:e}),setIsSystemResourceLibraryOpen:e=>s({isSystemResourceLibraryOpen:e}),setBatchPicker:e=>s({batchPicker:e}),setIsExportWeightModalOpen:e=>s({isExportWeightModalOpen:e}),addToast:e=>s(t=>({toasts:[...t.toasts,e]})),removeToast:e=>s(t=>({toasts:t.toasts.filter(n=>n.id!==e)})),setSiteInfo:e=>s({siteInfo:e})})),kc=it(s=>({classes:[],students:[],classStudentsMap:{},classDashboardMap:{},studentProgressMap:{},classSchedulesMap:{},scheduleAttendanceMap:{},assignmentSubmissionsMap:{},classAssignmentsMap:{},classProgressMap:{},classSeats:{lab_id:null,seats:[]},setClasses:e=>s({classes:e}),setStudents:e=>s({students:e}),setClassStudents:(e,t)=>s(n=>({classStudentsMap:{...n.classStudentsMap,[e]:t}})),setClassDashboard:(e,t)=>s(n=>({classDashboardMap:{...n.classDashboardMap,[e]:t}})),setStudentProgress:(e,t)=>s(n=>({studentProgressMap:{...n.studentProgressMap,[e]:t}})),setClassSchedules:(e,t)=>s(n=>({classSchedulesMap:{...n.classSchedulesMap,[e]:t}})),setScheduleAttendance:(e,t)=>s(n=>({scheduleAttendanceMap:{...n.scheduleAttendanceMap,[e]:t}})),setAssignmentSubmissions:(e,t)=>s(n=>({assignmentSubmissionsMap:{...n.assignmentSubmissionsMap,[e]:t}})),setClassAssignments:(e,t)=>s(n=>({classAssignmentsMap:{...n.classAssignmentsMap,[e]:t}})),setClassProgress:(e,t)=>s(n=>({classProgressMap:{...n.classProgressMap,[e]:t}})),setClassSeats:e=>s({classSeats:e})})),Nc=it(s=>({lessons:[],selectedLesson:null,elements:[],vfsNodes:[],setLessons:e=>s(t=>({lessons:typeof e=="function"?e(t.lessons):e})),setSelectedLesson:e=>s({selectedLesson:e}),setElements:e=>s({elements:e}),setVfsNodes:e=>s({vfsNodes:e})})),Ac=it(s=>({liveClassSelectedClassId:null,liveClassIsActive:!1,liveClassFeed:[],liveClassTimeRemaining:0,liveClassAcknowledgedMap:new Map,liveClassStudentProgress:[],onlineStudentIds:[],activeStudentLessons:{},setLiveClassSelectedClassId:e=>s({liveClassSelectedClassId:e}),setLiveClassIsActive:e=>s({liveClassIsActive:e}),setLiveClassFeed:e=>s({liveClassFeed:e}),appendLiveClassFeed:e=>s(t=>({liveClassFeed:[...t.liveClassFeed.slice(-49),e]})),setLiveClassTimeRemaining:e=>s({liveClassTimeRemaining:e}),setLiveClassAcknowledgedMap:e=>s({liveClassAcknowledgedMap:e}),setLiveClassStudentProgress:e=>s({liveClassStudentProgress:e}),setOnlineStudentIds:e=>s({onlineStudentIds:e}),setActiveStudentLessons:e=>s({activeStudentLessons:e})})),_c=it(s=>({studentDashboardData:null,notifications:[],setStudentDashboardData:e=>s({studentDashboardData:e}),setNotifications:e=>s({notifications:e})})),ge=it(s=>({lang:Ne.getState().lang,session:null,lessons:[],selectedLesson:null,elements:[],classes:[],students:[],liveClassSelectedClassId:null,liveClassIsActive:!1,teacherTab:Ne.getState().teacherTab,aiProviders:[],plugins:[],registeredCommands:[],events:[],approvals:[],processes:[],vfsNodes:[],todaySchedules:[],computerLabs:[],dbConnected:!1,sessionLoading:!0,classStudentsMap:{},classDashboardMap:{},studentProgressMap:{},classSchedulesMap:{},scheduleAttendanceMap:{},assignmentSubmissionsMap:{},classAssignmentsMap:{},classProgressMap:{},classSeats:{lab_id:null,seats:[]},onlineStudentIds:[],activeStudentLessons:{},liveClassFeed:[],liveClassTimeRemaining:0,liveClassAcknowledgedMap:new Map,liveClassStudentProgress:[],studentDashboardData:null,notifications:[],toasts:Ne.getState().toasts,siteInfo:Ne.getState().siteInfo,setLang:e=>{Ne.getState().setLang(e)},setSession:e=>s({session:e}),setLessons:e=>s(t=>({lessons:typeof e=="function"?e(t.lessons):e})),setSelectedLesson:e=>s({selectedLesson:e}),setElements:e=>s({elements:e}),setClasses:e=>s({classes:e}),setStudents:e=>s({students:e}),setLiveClassSelectedClassId:e=>s({liveClassSelectedClassId:e}),setLiveClassIsActive:e=>s({liveClassIsActive:e}),setTeacherTab:e=>{Ne.getState().setTeacherTab(e)},setAiProviders:e=>s({aiProviders:e}),setPlugins:e=>s({plugins:e}),setRegisteredCommands:e=>s({registeredCommands:e}),setEvents:e=>s({events:e}),setApprovals:e=>s({approvals:e}),setProcesses:e=>s({processes:e}),setVfsNodes:e=>s({vfsNodes:e}),setTodaySchedules:e=>s({todaySchedules:e}),setComputerLabs:e=>s({computerLabs:e}),setDbConnected:e=>s({dbConnected:e}),setSessionLoading:e=>s({sessionLoading:e}),setClassStudents:(e,t)=>s(n=>({classStudentsMap:{...n.classStudentsMap,[e]:t}})),setClassDashboard:(e,t)=>s(n=>({classDashboardMap:{...n.classDashboardMap,[e]:t}})),setStudentProgress:(e,t)=>s(n=>({studentProgressMap:{...n.studentProgressMap,[e]:t}})),setClassSchedules:(e,t)=>s(n=>({classSchedulesMap:{...n.classSchedulesMap,[e]:t}})),setScheduleAttendance:(e,t)=>s(n=>({scheduleAttendanceMap:{...n.scheduleAttendanceMap,[e]:t}})),setAssignmentSubmissions:(e,t)=>s(n=>({assignmentSubmissionsMap:{...n.assignmentSubmissionsMap,[e]:t}})),setClassAssignments:(e,t)=>s(n=>({classAssignmentsMap:{...n.classAssignmentsMap,[e]:t}})),setClassProgress:(e,t)=>s(n=>({classProgressMap:{...n.classProgressMap,[e]:t}})),setClassSeats:e=>s({classSeats:e}),setOnlineStudentIds:e=>s({onlineStudentIds:e}),setActiveStudentLessons:e=>s({activeStudentLessons:e}),setLiveClassFeed:e=>s({liveClassFeed:e}),appendLiveClassFeed:e=>s(t=>({liveClassFeed:[...t.liveClassFeed.slice(-49),e]})),setLiveClassTimeRemaining:e=>s({liveClassTimeRemaining:e}),setLiveClassAcknowledgedMap:e=>s({liveClassAcknowledgedMap:e}),setLiveClassStudentProgress:e=>s({liveClassStudentProgress:e}),setStudentDashboardData:e=>s({studentDashboardData:e}),setNotifications:e=>s({notifications:e}),addToast:e=>{Ne.getState().addToast(e)},removeToast:e=>{Ne.getState().removeToast(e)},setSiteInfo:e=>{Ne.getState().setSiteInfo(e)}}));Ne.subscribe(s=>{ge.setState({lang:s.lang,teacherTab:s.teacherTab,toasts:s.toasts,siteInfo:s.siteInfo})});kc.subscribe(s=>{ge.setState({classes:s.classes,students:s.students,classStudentsMap:s.classStudentsMap,classDashboardMap:s.classDashboardMap,studentProgressMap:s.studentProgressMap,classSchedulesMap:s.classSchedulesMap,scheduleAttendanceMap:s.scheduleAttendanceMap,assignmentSubmissionsMap:s.assignmentSubmissionsMap,classAssignmentsMap:s.classAssignmentsMap,classProgressMap:s.classProgressMap,classSeats:s.classSeats})});Nc.subscribe(s=>{ge.setState({lessons:s.lessons,selectedLesson:s.selectedLesson,elements:s.elements,vfsNodes:s.vfsNodes})});Ac.subscribe(s=>{ge.setState({liveClassSelectedClassId:s.liveClassSelectedClassId,liveClassIsActive:s.liveClassIsActive,liveClassFeed:s.liveClassFeed,liveClassTimeRemaining:s.liveClassTimeRemaining,liveClassAcknowledgedMap:s.liveClassAcknowledgedMap,liveClassStudentProgress:s.liveClassStudentProgress,onlineStudentIds:s.onlineStudentIds,activeStudentLessons:s.activeStudentLessons})});_c.subscribe(s=>{ge.setState({studentDashboardData:s.studentDashboardData,notifications:s.notifications})});const K=s=>pc(ge,s),fr=o.createContext(null);function zc({children:s,host:e}){return r.jsx(fr.Provider,{value:e,children:s})}function pr(){const s=o.useContext(fr);if(!s)throw new Error("usePluginHost must be used within PluginHostProvider");return s}const gr="openlearn:dashboardVisibility";function jc(){try{const s=localStorage.getItem(gr);if(s)return new Map(JSON.parse(s))}catch{}return new Map}function Un(s){try{localStorage.setItem(gr,JSON.stringify([...s.entries()]))}catch{}}const oe=gc()((s,e)=>({activePlugins:[],extensionPoints:new Map,services:null,dashboardVisibility:jc(),initialized:!1,initialize:t=>s({services:t,initialized:!0}),addPlugin:t=>s(n=>({activePlugins:[...n.activePlugins,t]})),removePlugin:t=>s(n=>({activePlugins:n.activePlugins.filter(i=>i.id!==t)})),updatePluginState:(t,n)=>s(i=>({activePlugins:i.activePlugins.map(a=>a.id===t?{...a,state:n}:a)})),registerExtensionPoint:(t,n)=>s(i=>{const a=i.extensionPoints.get(t)??[];if(a.find(h=>h.id===n.id)){const h=new Map(i.extensionPoints);return h.set(t,a.map(f=>f.id===n.id?n:f)),{extensionPoints:h}}const l=new Map(i.extensionPoints);return l.set(t,[...a,n]),{extensionPoints:l}}),unregisterExtensionPoint:(t,n)=>s(i=>{const a=i.extensionPoints.get(t);if(!a)return i;const d=a.filter(h=>h.id!==n),l=new Map(i.extensionPoints);return d.length===0?l.delete(t):l.set(t,d),{extensionPoints:l}}),unregisterPluginExtensionPoints:t=>s(n=>{const i=new Map(n.extensionPoints);for(const[a,d]of i){const l=d.filter(h=>h.pluginId!==t);l.length===0?i.delete(a):i.set(a,l)}return{extensionPoints:i}}),getExtensions:t=>[...e().extensionPoints.get(t)??[]].sort((i,a)=>(i.position??100)-(a.position??100)),setDashboardVisibility:(t,n)=>s(i=>{const a=new Map(i.dashboardVisibility);return a.set(t,n),Un(a),{dashboardVisibility:a}}),setDashboardVisibilityBatch:t=>s(n=>{const i=new Map(n.dashboardVisibility);for(const[a,d]of t)i.set(a,d);return Un(i),{dashboardVisibility:i}})}));function Ic(){return r.jsx("div",{className:"w-full h-32 bg-gray-100 rounded-xl animate-pulse flex items-center justify-center",children:r.jsxs("div",{className:"flex flex-col items-center gap-2",children:[r.jsx(ln,{size:24,className:"text-gray-400 animate-spin"}),r.jsx("span",{className:"text-xs text-gray-400",children:"Loading..."})]})})}class Lc extends Ve.Component{constructor(e){super(e),this.state={hasError:!1},this.props=e}static getDerivedStateFromError(){return{hasError:!0}}render(){return this.state.hasError?this.props.fallback??null:this.props.children}}function Rc({ext:s,route:e,slotProps:t,slot:n}){const i=Ve.useRef(null),a=JSON.stringify(t||{});Ve.useEffect(()=>{i.current&&typeof s.render=="function"&&(i.current.innerHTML="",Promise.resolve(s.render(i.current,{route:e,...t})).catch(console.error))},[s,e,a]);const l=n==="teacher.dashboard.widget"?"h-auto":"h-full min-h-0";return r.jsx("div",{ref:i,className:`w-full ${l}`})}const Qs=new WeakMap;function Oc(s){const e=s.component,t=Qs.get(e);if(t)return t;if(e.__isLazyFactory===!0){const n=Ve.lazy(e);return Qs.set(e,n),n}return Qs.set(e,e),e}function Bu({slot:s,fallback:e,lang:t,route:n,slotProps:i,placement:a}){let l=pr().getExtensions(s);const h=oe(f=>f.dashboardVisibility);return a&&(l=l.filter(f=>(f.placement??"after")===a)),l.length===0?null:s==="teacher.tab"&&i?.renderType==="button"?r.jsx(r.Fragment,{children:l.map(f=>{const b=`${f.pluginId}/${f.id}`,v=i?.teacherTab===b,C=f.title||f.label||f.id;return r.jsxs("button",{onClick:()=>i?.setTeacherTab?.(b),className:`flex items-center gap-3 p-3 transition-colors text-sm font-medium rounded-xl ${v?"bg-indigo-50 text-indigo-700 font-bold":"text-gray-600 hover:bg-gray-50"} ${i?.mainNavCollapsed?"justify-center px-2":""}`,title:C,children:[r.jsx(cn,{size:20,className:"shrink-0"}),r.jsx("span",{className:i?.mainNavCollapsed?"hidden":"hidden md:block",children:C})]},`${f.pluginId}/${f.id}`)})}):r.jsx(r.Fragment,{children:l.map(f=>{const b=typeof f.component=="function",v=typeof f.render=="function";return s==="teacher.dashboard.widget"&&h.get(f.pluginId)===!1||!b&&!v?null:r.jsx(Lc,{fallback:r.jsx("div",{className:"bg-red-50 border border-red-200 rounded-lg p-4 text-sm text-red-700",children:r.jsx("p",{children:t==="zh"?"扩展组件加载失败":"Extension failed to load"})}),children:r.jsx(o.Suspense,{fallback:e??r.jsx(Ic,{}),children:b?Ve.createElement(Oc(f),{route:f.route||n,...f.slotProps,...i}):r.jsx(Rc,{ext:f,route:f.route||n,slotProps:{...f.slotProps,...i},slot:s})})},`${f.pluginId}/${f.id}`)})})}const Mc=(s,e)=>{const t=s?s.trim():"New Course";switch(e){case"Mathematics":return`# ${t}
|
|
10
|
-
|
|
11
|
-
## 101 Course Core Foundations
|
|
12
|
-
Welcome to our mathematics laboratory. This course is designed to break down abstract calculations into visual whiteboard proofs and real-world application models.
|
|
13
|
-
|
|
14
|
-
### 📐 Key Theorems & Proof Matrix
|
|
15
|
-
- **Formula A**: $E = mc^2$ or equivalent derivative parameters
|
|
16
|
-
- **Core Axiom**: For every linear projection, a finite dimension defines its trace.
|
|
17
|
-
|
|
18
|
-
### 实践演练随堂真题 Practice Problems
|
|
19
|
-
1. Calculate the local optima for the function on the interactive workspace.
|
|
20
|
-
2. Prove the uniqueness of the residual limit under Gaussian conditions.
|
|
21
|
-
|
|
22
|
-
### 📥 Homework Assignment Task
|
|
23
|
-
Identify three real-world physical structures implementing these spatial principles and coordinate maps.`;case"ComputerScience":return`# ${t}
|
|
24
|
-
|
|
25
|
-
## 💻 Technical Exploration & Engineering Lab
|
|
26
|
-
This session acts as an immersive sandbox exploring core algorithmic structures, optimization mechanics, and data abstractions.
|
|
27
|
-
|
|
28
|
-
### ⚙️ Core Lecture Blueprint & Pseudocode
|
|
29
|
-
\`\`\`python
|
|
30
|
-
def optimize_weights(data, factor=0.01):
|
|
31
|
-
# Initialize local metrics
|
|
32
|
-
scores = [x * factor for x in data]
|
|
33
|
-
return sum(scores) / len(scores)
|
|
34
|
-
\`\`\`
|
|
35
|
-
|
|
36
|
-
### ⚡ Laboratory Workspace Drill
|
|
37
|
-
- **Objective**: Develop a linear hash-map with zero-collision distribution.
|
|
38
|
-
- **Action**: Use the interactive canvas to sketch data pipelines.
|
|
39
|
-
|
|
40
|
-
### 📝 Post-Class Evaluation
|
|
41
|
-
Write a 200-word critique analyzing memory-locality vs execution-speed trade-offs in low-level registers.`;case"Literature":return`# ${t}
|
|
42
|
-
|
|
43
|
-
## ✍️ Literary Critical Analysis Seminar
|
|
44
|
-
This curriculum evaluates textual aesthetics, semantic patterns, subtextual symbols, and historical contexts across classic paradigms.
|
|
45
|
-
|
|
46
|
-
### 🏛️ Classic Textual Excerpts
|
|
47
|
-
> "Reality represents a state of constant translation between what is experienced and what is chronicled."
|
|
48
|
-
|
|
49
|
-
### 💭 Critique Evaluation Metrics
|
|
50
|
-
- **Theme Assessment**: Analyze structural ironies within contemporary essays.
|
|
51
|
-
- **Author Intention**: Focus on pacing triggers and character foils.
|
|
52
|
-
|
|
53
|
-
### 💬 Classroom Collaborative Debate Topics
|
|
54
|
-
Does digital notation diminish the biological connection to textual journaling? Discuss under 15 minutes framework.`;case"Physics":return`# ${t}
|
|
55
|
-
|
|
56
|
-
## ⚡ Experimental Physics & Natural Science Sandbox
|
|
57
|
-
In this session, theoretical models undergo practical validation through interactive virtual whiteboard modeling and numerical measurements.
|
|
58
|
-
|
|
59
|
-
### 🔬 Key Mechanical Principles & Constraints
|
|
60
|
-
- **Axiom 1**: Momentum is conserved in closed coordinate vectors.
|
|
61
|
-
- **Axiom 2**: Resistance is directly proportional to temperature factors.
|
|
62
|
-
|
|
63
|
-
### 🛠️ Lab Step-by-Step Procedure
|
|
64
|
-
1. Plot the force vectors acting on the balance coordinate vertices.
|
|
65
|
-
2. Measure the velocity coefficients across three alternate trial loops.
|
|
66
|
-
|
|
67
|
-
### 📝 Homework Assignment Evaluation
|
|
68
|
-
Calculate energy loss ratios using standard mathematical integrals in your journal.`;case"History":return`# ${t}
|
|
69
|
-
|
|
70
|
-
## 🏛️ Geopolitical Context Mapping & Historical Context
|
|
71
|
-
This course explores historical trends, decision frameworks, resource patterns, and socio-economic influences that shaped modern civilization.
|
|
72
|
-
|
|
73
|
-
### 🗺️ Context Timeline Focus
|
|
74
|
-
- **Phase A**: Resource migration patterns along major trade waterways.
|
|
75
|
-
- **Phase B**: Strategic institutional reforms and cultural integration cycles.
|
|
76
|
-
|
|
77
|
-
### 🔍 Primary Source Critique Work
|
|
78
|
-
Analyze the 18th-century legislative documents for bias, context gaps, and underlying socio-economic drivers.
|
|
79
|
-
|
|
80
|
-
### 💬 Group Discussion Prompts
|
|
81
|
-
How did geography influence the longevity of ancient administrative models?`;case"Art":return`# ${t}
|
|
82
|
-
|
|
83
|
-
## 🎨 Visual Composition & Creative Sketching Studio
|
|
84
|
-
A workshop focusing on aesthetic principles, negative space ratios, visual balance, and dynamic typography models.
|
|
85
|
-
|
|
86
|
-
### 🖌️ Design Principles
|
|
87
|
-
- **Golden Spiral**: Align critical focal points with recursive visual arcs.
|
|
88
|
-
- **Chiaroscuro**: Leverage deep high-contrast shading to establish three-dimensional form.
|
|
89
|
-
|
|
90
|
-
### 🛠️ Whiteboard Practical Sandbox Project
|
|
91
|
-
Collaborate on the dynamic canvas to draft a raw responsive layout using minimal monochromatic blocks.
|
|
92
|
-
|
|
93
|
-
### 🎨 Portfolio Task
|
|
94
|
-
Submit three divergent conceptual drafts representing active space constraints.`;default:return`# ${t}
|
|
95
|
-
|
|
96
|
-
## 🔮 Multidisciplinary Advanced Exploration & Research
|
|
97
|
-
This course integrates cross-subject paradigms, cognitive practices, and critical reasoning methods.
|
|
98
|
-
|
|
99
|
-
### 📚 Course Syllabus Modules
|
|
100
|
-
- **Module 1**: Core theoretical grounding and conceptual models.
|
|
101
|
-
- **Module 2**: Practical exercises combining research and action.
|
|
102
|
-
|
|
103
|
-
### 📝 Interactive Classroom Tasks
|
|
104
|
-
1. Formulate 2 key research queries aligning with this lecture.
|
|
105
|
-
2. Sketch the systemic flow diagram depicting interaction factors.
|
|
106
|
-
|
|
107
|
-
### 📥 Assignment Brief
|
|
108
|
-
Draft a 300-word integration proposal based on today's whiteboard exercises.`}};async function Dc(s="all"){const e=await fetch(`/api/activities?role=${encodeURIComponent(s)}`,{headers:{Accept:"application/json"}});if(!e.ok)throw new Error(`Failed to load activities (${e.status})`);return(await e.json()).activities??[]}async function Gn(){const s=await fetch("/api/activities/running",{headers:{Accept:"application/json"}});if(!s.ok)throw new Error(`Failed to load running activities (${s.status})`);return(await s.json()).activities??[]}async function $c(s){const e=await fetch(`/api/activities/${encodeURIComponent(s)}/finish`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!e.ok){const t=await e.json().catch(()=>({}));throw new Error(t.error||`Failed to finish activity (${e.status})`)}}async function Fc(s){const e=await fetch(`/api/activities/${encodeURIComponent(s)}/pause`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!e.ok){const t=await e.json().catch(()=>({}));throw new Error(t.error||`Failed to pause activity (${e.status})`)}}async function Bc(s){const e=await fetch(`/api/activities/${encodeURIComponent(s)}/resume`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!e.ok){const t=await e.json().catch(()=>({}));throw new Error(t.error||`Failed to resume activity (${e.status})`)}}async function Vc(s,e,t){const n=await fetch(`/api/activities/${encodeURIComponent(s)}/start`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({payload:e??{},actorId:t})}),i=await n.json();if(!n.ok||i.ok===!1)throw new Error(i.error||`Failed to start activity (${n.status})`);return i}const Ft={padding:"12px",color:"#e2e8f0",fontSize:"13px"},Wc={HelpCircle:cc,Vote:ac,BarChart3:oc,MessagesSquare:ic,Users:cr,FileText:hr,Trophy:rc,CheckCircle2:an,BookOpen:nc};function qc({name:s,className:e}){const t=s&&Wc[s]||cn;return r.jsx(t,{size:18,className:e})}function Uc(s,e){if(!s)return e==="zh"?"进行中":"In progress";const t=Math.max(0,Math.floor((Date.now()-s)/1e3)),n=Math.floor(t/60),i=t%60;return e==="zh"?`${n} 分 ${i} 秒`:`${n}m ${i}s`}const mr=({role:s,actorId:e,lang:t="en",classroomId:n,mode:i="launcher"})=>{const[a,d]=o.useState([]),[l,h]=o.useState(!0),[f,b]=o.useState(null),[v,C]=o.useState({}),[x,p]=o.useState([]),[u,P]=o.useState(!0),[I,_]=o.useState(null),[S,g]=o.useState(null),[E,O]=o.useState(!1),[k,z]=o.useState(null),M=K(w=>w.setTeacherTab);o.useEffect(()=>{if(i!=="launcher")return;let w=!1;return h(!0),Dc(s).then(R=>{w||d(R)}).catch(R=>{w||b(R instanceof Error?R.message:String(R))}).finally(()=>{w||h(!1)}),()=>{w=!0}},[s,i]),o.useEffect(()=>{if(i!=="status")return;let w=!1;const R=async()=>{try{const Z=await Gn();w||p(Z)}catch(Z){w||_(Z instanceof Error?Z.message:String(Z))}finally{w||P(!1)}};R();const F=setInterval(R,5e3);return()=>{w=!0,clearInterval(F)}},[i]);const y=async w=>{if(S){O(!0),z(null);try{await w(S),p(await Gn())}catch(R){z(R instanceof Error?R.message:String(R))}finally{O(!1)}}},N=()=>y($c),D=()=>y(Fc),A=()=>y(Bc),B=()=>{g(null),M("live_class")};if(i==="status"){if(u)return r.jsx("div",{className:"bg-white border border-slate-200/80 rounded-2xl p-5 shadow-sm h-24 animate-pulse"});if(I||x.length===0)return null;const w=x.find(R=>R.id===S)||null;return r.jsxs("div",{className:"bg-white border border-slate-200/80 rounded-2xl p-5 shadow-sm",children:[r.jsxs("div",{className:"flex items-center justify-between mb-3",children:[r.jsxs("div",{className:"flex items-center gap-2 text-slate-800 font-extrabold",children:[r.jsx("span",{children:"🧩"}),r.jsx("span",{children:t==="zh"?"进行中的活动":"Activities in Progress"})]}),r.jsx("span",{className:"text-[10px] font-bold bg-indigo-50 text-indigo-700 px-2 py-0.5 rounded-full",children:x.length})]}),r.jsx("div",{className:"flex flex-col gap-2",children:x.map(R=>{const F=R.state==="running";return r.jsxs("button",{onClick:()=>g(R.id),className:"w-full flex items-center gap-3 text-left bg-slate-50 hover:bg-slate-100 border border-slate-200/70 rounded-xl p-3 transition-colors",children:[r.jsx(qc,{name:R.icon,className:"text-indigo-600 shrink-0"}),r.jsxs("div",{className:"min-w-0 flex-1",children:[r.jsx("div",{className:"font-bold text-slate-800 truncate",children:R.name}),R.category&&r.jsx("div",{className:"text-[11px] text-slate-500 truncate",children:R.category})]}),r.jsxs("div",{className:"flex flex-col items-end gap-1 shrink-0",children:[r.jsx("span",{className:`text-[10px] font-bold px-2 py-0.5 rounded-full ${F?"bg-emerald-100 text-emerald-700":"bg-amber-100 text-amber-700"}`,children:F?t==="zh"?"进行中":"Running":t==="zh"?"已暂停":"Paused"}),r.jsxs("span",{className:"text-[10px] text-slate-400 flex items-center gap-1",children:[r.jsx(ec,{size:10})," ",Uc(R.startedAt,t)]})]})]},R.id)})}),w&&r.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/30 p-4",onClick:()=>g(null),children:r.jsxs("div",{className:"bg-white rounded-2xl shadow-xl w-full max-w-sm p-5",onClick:R=>R.stopPropagation(),children:[r.jsxs("div",{className:"flex items-center justify-between mb-3",children:[r.jsx("h3",{className:"font-bold text-slate-800",children:w.name}),r.jsx("button",{onClick:()=>g(null),className:"text-slate-400 hover:text-slate-600","aria-label":"close",children:r.jsx(Qt,{size:18})})]}),r.jsxs("div",{className:"text-sm text-slate-500 mb-1",children:[t==="zh"?"状态":"Status",":"," ",w.state==="running"?t==="zh"?"进行中":"Running":t==="zh"?"已暂停":"Paused"]}),r.jsxs("div",{className:"text-sm text-slate-500 mb-4",children:[t==="zh"?"开始时间":"Started",":"," ",w.startedAt?new Date(w.startedAt).toLocaleString():"-"]}),k&&r.jsx("div",{className:"text-xs text-rose-600 mb-2",children:k}),r.jsxs("div",{className:"flex gap-2",children:[w.state==="running"?r.jsxs("button",{disabled:E,onClick:D,className:"flex-1 flex items-center justify-center gap-1 bg-amber-500 hover:bg-amber-600 disabled:opacity-60 text-white rounded-lg py-2 text-sm font-bold",children:[r.jsx(tc,{size:14})," ",t==="zh"?"暂停":"Pause"]}):r.jsxs("button",{disabled:E,onClick:A,className:"flex-1 flex items-center justify-center gap-1 bg-indigo-500 hover:bg-indigo-600 disabled:opacity-60 text-white rounded-lg py-2 text-sm font-bold",children:[r.jsx(sc,{size:14})," ",t==="zh"?"恢复":"Resume"]}),r.jsx("button",{disabled:E,onClick:N,className:"flex-1 flex items-center justify-center gap-1 bg-rose-600 hover:bg-rose-700 disabled:opacity-60 text-white rounded-lg py-2 text-sm font-bold",children:E?t==="zh"?"处理中…":"Working…":t==="zh"?"结束":"End"})]}),r.jsx("button",{onClick:B,className:"w-full mt-2 bg-slate-100 hover:bg-slate-200 text-slate-700 rounded-lg py-2 text-sm font-bold",children:t==="zh"?"进入课堂":"Enter Classroom"})]})})]})}const j=o.useMemo(()=>{const w=new Map;for(const R of a){const F=R.category;w.has(F)||w.set(F,[]),w.get(F).push(R)}return Array.from(w.entries())},[a]),m=async w=>{C(R=>({...R,[w.id]:t==="zh"?"启动中…":"Starting…"}));try{const R=await Vc(w.id,{classroomId:n,role:s},e);C(F=>({...F,[w.id]:R.dispatched?t==="zh"?"已启动 ✓":"Started ✓":t==="zh"?"已通知 ✓":"Notified ✓"}))}catch(R){C(F=>({...F,[w.id]:R instanceof Error?R.message:String(R)}))}};if(l)return r.jsx("div",{style:Ft,children:t==="zh"?"加载活动中…":"Loading activities…"});if(f)return r.jsxs("div",{style:Ft,children:[r.jsxs("div",{style:{fontWeight:600,marginBottom:6},children:["🧩 ",t==="zh"?"活动中心":"Activity Center"]}),r.jsx("div",{style:{opacity:.7},children:f})]});const L=s==="teacher"?t==="zh"?"活动中心(教师)":"Activity Center":t==="zh"?"活动(学生)":"Activities";return a.length===0?r.jsxs("div",{style:Ft,children:[r.jsxs("div",{style:{fontWeight:600,marginBottom:6},children:["🧩 ",L]}),r.jsx("div",{style:{opacity:.7},children:t==="zh"?"暂无可用活动。":"No activities available."})]}):r.jsxs("div",{style:Ft,children:[r.jsxs("div",{style:{fontWeight:600,marginBottom:8},children:["🧩 ",L]}),j.map(([w,R])=>r.jsxs("div",{style:{marginBottom:10},children:[r.jsx("div",{style:{opacity:.6,fontSize:11,textTransform:"uppercase",marginBottom:4},children:w}),r.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:8},children:R.map(F=>r.jsxs("div",{style:{border:"1px solid #334155",borderRadius:8,padding:"8px 10px",minWidth:150,background:"#0f172a"},children:[r.jsxs("div",{style:{fontWeight:600},children:[F.icon?`${F.icon} `:"▫️ ",F.name]}),F.description&&r.jsx("div",{style:{opacity:.7,fontSize:11,margin:"2px 0 6px"},children:F.description}),r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[r.jsx("button",{onClick:()=>m(F),style:{cursor:"pointer",background:s==="teacher"?"#2563eb":"#0ea5e9",color:"#fff",border:"none",borderRadius:6,padding:"4px 10px",fontSize:12},children:s==="teacher"?t==="zh"?"启动":"Start":t==="zh"?"参与":"Open"}),v[F.id]&&r.jsx("span",{style:{fontSize:11,opacity:.85},children:v[F.id]})]}),r.jsx("div",{style:{opacity:.5,fontSize:10,marginTop:4},children:F.provider==="official"?"official":F.provider})]},F.id))})]},w))]})},Gc=Object.freeze(Object.defineProperty({__proto__:null,ActivityWorkspaceWidget:mr},Symbol.toStringTag,{value:"Module"}));let Hn=!1;function Hc(){if(Hn)return;Hn=!0;const s=()=>ue(()=>Promise.resolve().then(()=>Gc),void 0).then(e=>({default:()=>r.jsx(mr,{role:"teacher",mode:"status"})}));s.__isLazyFactory=!0,oe.getState().registerExtensionPoint("teacher.dashboard.widget",{id:"official_activity_center",label:"Activity Center",icon:"Puzzle",pluginId:"openlearn-official",component:s})}const Qn="@openlearn/frontend:IFrontendAPI",Jn="@openlearn/frontend:ISocketService",Zn="@openlearn/frontend:IUIService",Kn="@openlearn/frontend:IStorageService",Qc="@openlearn/frontend:ISemesterGradeService";var X=(s=>(s.INSTALLED="installed",s.ACTIVATING="activating",s.ACTIVE="active",s.DEACTIVATING="deactivating",s.INACTIVE="inactive",s.ERROR="error",s.UNINSTALLED="uninstalled",s))(X||{});const Jc=o.lazy(()=>ue(()=>import("./StudentView-BOqPntx-.js"),[]).then(s=>({default:s.StudentView}))),Zc=o.lazy(()=>ue(()=>import("./TeacherView-CrbllHIm.js"),[]).then(s=>({default:s.TeacherView})));function Kc(s){const{activeRole:e}=s;return r.jsx(o.Suspense,{fallback:r.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center min-h-[50vh] text-slate-400 gap-3",children:[r.jsx(ln,{className:"w-8 h-8 animate-spin text-indigo-500"}),r.jsx("span",{className:"text-sm font-medium tracking-wide",children:"正在加载工作台..."})]}),children:e==="student"?r.jsx(Jc,{...s}):r.jsx(Zc,{...s})})}function Yc(){const s=K(e=>e.toasts);return r.jsx("div",{className:"fixed bottom-6 right-6 z-50 flex flex-col gap-3 min-w-[320px] max-w-sm pointer-events-none",children:r.jsx(yc,{children:s.map(e=>r.jsxs(bc.div,{initial:{opacity:0,y:50,x:50,scale:.9},animate:{opacity:1,y:0,x:0,scale:1},exit:{opacity:0,scale:.85,transition:{duration:.2}},transition:{type:"spring",stiffness:300,damping:24},className:"pointer-events-auto w-full bg-white ring-1 ring-black/5 shadow-2xl rounded-xl p-4 flex gap-3 border-l-4 border-emerald-500 overflow-hidden",id:`toast-${e.id}`,children:[r.jsxs("div",{className:"flex-1",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:"p-1 rounded-full bg-emerald-50 text-emerald-600",children:r.jsx(lc,{size:16})}),r.jsx("p",{className:"font-semibold text-gray-900 text-sm font-sans",children:e.title})]}),r.jsx("p",{className:"text-xs text-gray-500 mt-2 leading-relaxed font-sans",children:e.message})]}),r.jsx("button",{type:"button",onClick:()=>ge.getState().removeToast(e.id),className:"text-gray-400 hover:text-gray-600 hover:bg-gray-50 rounded p-1 h-fit transition-colors shrink-0 cursor-pointer",children:r.jsx(Qt,{size:14})})]},e.id))})})}function Xc({showRightSidebar:s,setShowRightSidebar:e,rightSidebarTab:t,setRightSidebarTab:n,effectiveAgentProviderId:i,agentProviderId:a,setAgentProviderId:d,aiProviders:l,selectedAgentProvider:h,chatLog:f,loading:b,input:v,setInput:C,handleSend:x,chatAttachments:p,setChatAttachments:u,handleChatFileChange:P,handleChatDrop:I,onClearAgentMemory:_,events:S,lang:g,t:E}){const O=o.useRef(null);return o.useEffect(()=>{O.current?.scrollIntoView({behavior:"smooth"})},[f]),r.jsx("div",{className:`transition-all duration-300 bg-white border-l border-gray-200 flex flex-col shadow-xl relative z-30 shrink-0 ${s?"w-96":"w-12 items-center cursor-pointer hover:bg-gray-50"}`,children:s?r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"flex bg-gray-100 p-1 m-4 rounded-lg shrink-0",children:[r.jsxs("button",{onClick:()=>n("agent"),className:`flex-1 py-1.5 text-xs font-medium rounded-md transition-colors flex items-center justify-center gap-1 ${t==="agent"?"bg-white shadow text-indigo-600":"text-gray-500 hover:text-gray-700"}`,children:[r.jsx(Hs,{size:14})," Agent"]}),r.jsxs("button",{onClick:()=>n("shell"),className:`flex-1 py-1.5 text-xs font-medium rounded-md transition-colors flex items-center justify-center gap-1 ${t==="shell"?"bg-white shadow text-indigo-600":"text-gray-500 hover:text-gray-700"}`,children:[r.jsx(Wt,{size:14})," Shell"]}),r.jsx("button",{onClick:()=>e(!1),className:"ml-1 p-1.5 text-gray-400 hover:text-gray-600 rounded-md",children:r.jsx(dc,{size:14})})]}),t==="agent"?r.jsxs("div",{className:"flex-1 flex flex-col min-h-0",children:[r.jsx("div",{className:"p-4 border-b border-gray-100 shrink-0",children:r.jsxs("div",{className:"flex items-start justify-between gap-3",children:[r.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[r.jsx("div",{className:"p-1.5 bg-indigo-50 text-indigo-600 rounded-lg",children:r.jsx(Hs,{size:16})}),r.jsxs("div",{className:"min-w-0",children:[r.jsx("h2",{className:"font-semibold text-gray-900 text-sm",children:E.agentTitle}),r.jsx("p",{className:"text-[10px] text-gray-500",children:E.agentSubtitle}),r.jsxs("button",{onClick:_,title:g==="zh"?"清除内核助手的对话记忆":"Clear the kernel assistant's conversation memory",className:"mt-1 inline-flex items-center gap-1 text-[10px] text-gray-400 hover:text-red-500 transition-colors",children:["🧹 ",g==="zh"?"清除记忆":"Clear memory"]})]})]}),r.jsxs("div",{className:"flex flex-col items-end gap-1.5 min-w-[150px] max-w-[50%]",children:[r.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-[0.18em] text-gray-400",children:g==="zh"?"AI 提供商":"AI Provider"}),r.jsxs("div",{className:"relative w-full",children:[r.jsxs("select",{value:i,onChange:k=>d(k.target.value),className:"w-full appearance-none rounded-xl border border-gray-200 bg-gradient-to-b from-white to-gray-50 px-3 py-2 pr-9 text-[11px] font-medium text-gray-700 shadow-sm outline-none transition-colors focus:border-indigo-400 focus:ring-2 focus:ring-indigo-100",children:[r.jsx("option",{value:"system",children:g==="zh"?"系统默认(Gemini)":"System Default (Gemini)"}),l.map(k=>r.jsx("option",{value:k.id,children:k.name},k.id))]}),r.jsx(lr,{size:12,className:"pointer-events-none absolute right-3 top-1/2 -translate-y-1/2 text-gray-400"})]}),r.jsx("div",{className:"text-[10px] text-gray-400 truncate w-full text-right",title:i==="system"?g==="zh"?"使用内置 Gemini 系统模型":"Using the built-in Gemini system model":h?.model_name||"",children:i==="system"?g==="zh"?"内置系统模型":"Built-in system model":`${h?.name||(g==="zh"?"已选提供商":"Selected provider")}`})]})]})}),r.jsxs("div",{className:"flex-1 overflow-y-auto p-4 space-y-4",children:[f.map((k,z)=>r.jsx("div",{className:`flex flex-col ${k.role==="user"?"items-end":"items-start"}`,children:r.jsx("div",{className:`px-4 py-2.5 rounded-2xl max-w-[85%] text-xs whitespace-pre-wrap ${k.role==="user"?"bg-indigo-600 text-white rounded-br-none":"bg-gray-100 text-gray-800 rounded-bl-none"}`,children:k.content})},z)),b&&r.jsx("div",{className:"flex items-start",children:r.jsxs("div",{className:"px-4 py-2.5 rounded-2xl max-w-[85%] text-xs bg-gray-100 text-gray-500 rounded-bl-none flex items-center gap-1",children:[r.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-gray-400 animate-bounce"}),r.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-gray-400 animate-bounce",style:{animationDelay:"0.1s"}}),r.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-gray-400 animate-bounce",style:{animationDelay:"0.2s"}})]})}),r.jsx("div",{ref:O})]}),r.jsxs("form",{onSubmit:x,className:"p-3 border-t border-gray-100 bg-white shrink-0 font-sans",onDragOver:k=>k.preventDefault(),onDrop:I,children:[p.length>0&&r.jsx("div",{className:"flex flex-wrap gap-1 mb-2 px-1",children:p.map((k,z)=>r.jsxs("div",{className:"flex items-center gap-1 bg-indigo-50 border border-indigo-100 text-indigo-700 px-2 py-0.5 rounded-full text-[10px]",children:[r.jsx(hr,{size:10,className:"shrink-0"}),r.jsx("span",{className:"truncate max-w-[100px]",title:k.name,children:k.name}),r.jsx("button",{type:"button",onClick:()=>u(M=>M.filter((y,N)=>N!==z)),className:"hover:bg-indigo-200 rounded-full p-0.5 cursor-pointer ml-0.5 transition-colors text-indigo-400 hover:text-indigo-600",children:r.jsx(Qt,{size:10})})]},z))}),r.jsxs("div",{className:"flex items-center gap-1.5",children:[r.jsxs("label",{className:"p-1 px-1.5 text-gray-500 hover:text-indigo-600 rounded-full hover:bg-gray-100 cursor-pointer transition-colors shrink-0",children:[r.jsx(uc,{size:14}),r.jsx("input",{type:"file",multiple:!0,className:"hidden",onChange:P,accept:".csv,.txt,.json,.md"})]}),r.jsxs("div",{className:"relative flex-1",children:[r.jsx("input",{type:"text",value:v,onChange:k=>C(k.target.value),placeholder:E.placeholder,className:"w-full bg-gray-50 border border-gray-200 rounded-full pl-4 pr-10 py-1.5 text-xs focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-transparent transition-all"}),r.jsx("button",{type:"submit",disabled:b||!v.trim(),className:"absolute right-1 top-1/2 -translate-y-1/2 p-1 bg-indigo-600 text-white rounded-full hover:bg-indigo-700 disabled:opacity-50 transition-colors",children:r.jsx(hc,{size:10})})]})]})]})]}):r.jsxs("div",{className:"flex-1 flex flex-col bg-black text-green-400 font-mono text-[10px] min-h-0 mx-4 mb-4 rounded-xl shadow-inner border border-gray-800 overflow-hidden",children:[r.jsx("div",{className:"p-3 border-b border-gray-800 flex items-center justify-between shrink-0 bg-gray-900",children:r.jsxs("div",{className:"flex items-center gap-2 text-gray-300 font-sans tracking-wide",children:[r.jsx(Wt,{size:14}),r.jsx("span",{className:"text-xs",children:E.eventStream})]})}),r.jsx("div",{className:"p-3 overflow-y-auto flex-1 flex flex-col gap-1 select-text",children:S.length===0?r.jsx("div",{className:"text-gray-600 italic",children:"Waiting for events..."}):S.map((k,z)=>r.jsxs("div",{className:"flex flex-col gap-1 hover:bg-gray-800/50 p-2 rounded mb-1",children:[r.jsxs("div",{className:"flex items-center gap-2 justify-between",children:[r.jsxs("span",{className:"text-gray-500 shrink-0 text-[9px]",children:["[",new Date(k.timestamp).toLocaleTimeString(),"]"]}),r.jsx("span",{className:"text-blue-400 shrink-0 truncate text-[9px]",title:k.source,children:k.source})]}),r.jsx("div",{className:"text-green-300 font-bold",children:k.type}),r.jsx("div",{className:"text-gray-400 break-words mt-1 leading-tight",children:k.payload})]},z))})]})]}):r.jsxs("div",{className:"flex flex-col items-center py-6 h-full text-gray-400 w-full",onClick:()=>e(!0),children:[r.jsx(Hs,{size:18,className:"mb-6 hover:text-indigo-500"}),r.jsx(Wt,{size:18,className:"hover:text-indigo-500"}),r.jsx("div",{className:"mt-8 flex-1 flex flex-col justify-end pb-8",children:r.jsx("div",{className:"uppercase tracking-widest text-[9px] rotate-180",style:{writingMode:"vertical-rl"},children:"OS Core Options"})})]})})}const el=o.lazy(()=>ue(()=>import("./ImportModal-mkWuDoAN.js"),[]).then(s=>({default:s.ImportModal}))),tl=o.lazy(()=>ue(()=>import("./CourseWizardModal-B3QnFxvj.js"),[]).then(s=>({default:s.CourseWizardModal}))),sl=o.lazy(()=>ue(()=>import("./ImportLessonsModal-BZZRDBRU.js"),[]).then(s=>({default:s.ImportLessonsModal}))),nl=o.lazy(()=>ue(()=>import("./QuizGeneratorModal-DpTFYbVJ.js"),[]).then(s=>({default:s.QuizGeneratorModal}))),rl=o.lazy(()=>ue(()=>import("./StudentPreviewModal-ETJBF1Vc.js"),[]).then(s=>({default:s.StudentPreviewModal}))),il=o.lazy(()=>ue(()=>import("./ProcessLogsModal-8mVp07ic.js"),[]).then(s=>({default:s.ProcessLogsModal}))),ol=o.lazy(()=>ue(()=>import("./CloudDriveModal-TFWlPh8x.js"),[]).then(s=>({default:s.CloudDriveModal}))),al=o.lazy(()=>ue(()=>import("./SystemResourceLibraryModal-tg8xnblT.js"),[]).then(s=>({default:s.SystemResourceLibraryModal}))),cl=o.lazy(()=>ue(()=>import("./BatchPickerModal-CKQyeY6R.js"),[]).then(s=>({default:s.BatchPickerModal}))),ll=o.lazy(()=>ue(()=>import("./ExportWeightModal-BlS2auLs.js"),[]).then(s=>({default:s.ExportWeightModal}))),dl=o.lazy(()=>ue(()=>import("./NotificationDetailModal-dndFrE7p.js"),[]).then(s=>({default:s.NotificationDetailModal}))),ul=o.lazy(()=>ue(()=>import("./HelpTour-ZgEkRnin.js"),[]).then(s=>({default:s.HelpTour}))),hl=o.lazy(()=>ue(()=>import("./CoursewareHubPanel-CAaf22Qm.js"),[]).then(s=>({default:s.CoursewareHubPanel})));function fl(s){const{lang:e,t,showImportModal:n=!1,setShowImportModal:i=()=>{},handleImportFile:a=()=>{},importError:d=null,importSuccess:l=null,isImporting:h=!1,downloadCSVTemplate:f=()=>{},addToast:b=()=>{},generateTemplateContent:v=()=>"",isImportLessonsOpen:C=!1,setIsImportLessonsOpen:x=()=>{},importStatus:p="idle",setIsDraggingImport:u=()=>{},handleCSVFileChange:P=()=>{},downloadCsvTemplate:I=()=>{},isDraggingImport:_=!1,previewImportData:S=[],setPreviewImportData:g=()=>{},setImportStatus:E=()=>{},importProgress:O=0,importProgressTotal:k=0,importErrorMsg:z="",setImportErrorMsg:M=()=>{},handleCSVImportSubmit:y=()=>{},lessons:N=[],fetchClassDashboard:D=()=>{},isLessonPreviewVisible:A=!1,setIsLessonPreviewVisible:B=()=>{},selectedLesson:j=null,previewFullscreenPanel:m="none",setPreviewFullscreenPanel:L=()=>{},previewLessonTab:w="whiteboard",setPreviewLessonTab:R=()=>{},activeRole:F="teacher",elements:Z=[],activeSegmentId:ae=null,setActiveSegmentId:G=()=>{},fetchElements:q=()=>{},currentVfsParent:Q=null,setCurrentVfsParent:he=()=>{},vfsNodes:ce=[],previewSelectedCourseware:Ce=null,setPreviewSelectedCourseware:We=()=>{},showProcessLogs:ze=null,setShowProcessLogs:se=()=>{},processLogsContent:Ke="",isCloudDriveOpen:Et=!1,setIsCloudDriveOpen:Pt=()=>{},cloudDrivePreviewNode:at=null,setCloudDrivePreviewNode:ct=()=>{},isSystemResourceLibraryOpen:V=!1,setIsSystemResourceLibraryOpen:U=()=>{},systemResourceTab:J="system",setSystemResourceTab:le=()=>{},selectedLibraryResourceId:Te=null,setSelectedLibraryResourceId:Y=()=>{},loadingLibraryResources:fe=!1,libraryResources:de=[],fetchLibraryResources:je=()=>{},classes:qe=[],expandedClassId:Ee=null,isExportWeightModalOpen:Se=!1,setIsExportWeightModalOpen:pe=()=>{},quizzesWeight:lt=40,setQuizzesWeight:dt=()=>{},assignmentsWeight:Kt=60,setAssignmentsWeight:Tt=()=>{},handleQuizzesWeightChange:Yt=()=>{},handleAssignmentsWeightChange:Me=()=>{},customCategoryOverrides:Ye={},setCustomCategoryOverrides:ut=()=>{},classDashboardMap:Xt={},exportClassId:es="",exportClassName:ts="",csvPreviewData:ss=null,handleExportGrades:ns=()=>{},setSelectedAssignment:rs=()=>{},setStudentViewStatus:is=()=>{},setQuizStudentAnswers:os=()=>{},setSubAssignmentTab:kt=()=>{},isTourOpen:as=!1,setIsTourOpen:cs=()=>{},handleSeedSuccess:ls=()=>{},setTeacherTab:ht=()=>{},showCoursewareHub:ft=!1,setShowCoursewareHub:Nt=()=>{}}=s,re=s.courseWizard,Xe=re?.isCourseWizardOpen??s.isCourseWizardOpen??!1,ds=re?.setIsCourseWizardOpen??s.setIsCourseWizardOpen??(()=>{}),ke=re?.wizardStep??s.wizardStep??1,At=re?.setWizardStep??s.setWizardStep??(()=>{}),us=re?.wizardIsSubmitting??s.wizardIsSubmitting??!1,_t=re?.wizardCourseTitle??s.wizardCourseTitle??"",hs=re?.setWizardCourseTitle??s.setWizardCourseTitle??(()=>{}),et=re?.wizardCourseDescription??s.wizardCourseDescription??"",fs=re?.setWizardCourseDescription??s.setWizardCourseDescription??(()=>{}),zt=re?.wizardCourseCategory??s.wizardCourseCategory??"",ps=re?.setWizardCourseCategory??s.setWizardCourseCategory??(()=>{}),gs=re?.wizardCourseTimeline??s.wizardCourseTimeline??[],ms=re?.setWizardCourseTimeline??s.setWizardCourseTimeline??(()=>{}),ys=re?.wizardCourseContent??s.wizardCourseContent??"",bs=re?.setWizardCourseContent??s.setWizardCourseContent??(()=>{}),xs=re?.handleDeployWizardCourse??s.handleDeployWizardCourse??(()=>{}),ee=s.quizGenerator,Ss=ee?.isQuizGeneratorOpen??s.isQuizGeneratorOpen??!1,Ue=ee?.setIsQuizGeneratorOpen??s.setIsQuizGeneratorOpen??(()=>{}),vs=ee?.quizGenMode??s.quizGenMode??"scan_lesson",ws=ee?.setQuizGenMode??s.setQuizGenMode??(()=>{}),Cs=ee?.quizGenSelectedLessonId??s.quizGenSelectedLessonId??"",jt=ee?.setQuizGenSelectedLessonId??s.setQuizGenSelectedLessonId??(()=>{}),It=ee?.quizGenTopic??s.quizGenTopic??"",Es=ee?.setQuizGenTopic??s.setQuizGenTopic??(()=>{}),Ps=ee?.isGeneratingSuggestions??s.isGeneratingSuggestions??!1,Lt=ee?.setIsGeneratingSuggestions??s.setIsGeneratingSuggestions??(()=>{}),pt=ee?.suggestedObjectives??s.suggestedObjectives??[],gt=ee?.setSuggestedObjectives??s.setSuggestedObjectives??(()=>{}),Ts=ee?.suggestedQuestions??s.suggestedQuestions??[],ks=ee?.setSuggestedQuestions??s.setSuggestedQuestions??(()=>{}),ne=ee?.quizGenTimeLimit??s.quizGenTimeLimit??0,Ge=ee?.setQuizGenTimeLimit??s.setQuizGenTimeLimit??(()=>{}),Rt=ee?.savingQuiz??s.savingQuiz??!1,Ot=ee?.setSavingQuiz??s.setSavingQuiz??(()=>{}),ye=ee?.quizGeneratorClassId??s.quizGeneratorClassId??null,me=s.classBatch,Ns=me?.batchPicker??s.batchPicker??null,As=me?.setBatchPicker??s.setBatchPicker??(()=>{}),_s=me?.batchPickerLesson??s.batchPickerLesson??"",tt=me?.setBatchPickerLesson??s.setBatchPickerLesson??(()=>{}),zs=me?.batchPickerDate??s.batchPickerDate??"",He=me?.setBatchPickerDate??s.setBatchPickerDate??(()=>{}),De=me?.batchPickerTargetClass??s.batchPickerTargetClass??"",be=me?.setBatchPickerTargetClass??s.setBatchPickerTargetClass??(()=>{}),js=me?.confirmBatchPicker??s.confirmBatchPicker??(()=>{}),st=s.studentNotificationsHook,Is=st?.selectedNotificationForModal??s.selectedNotificationForModal??null,Ls=st?.setSelectedNotificationForModal??s.setSelectedNotificationForModal??(()=>{});return r.jsxs(o.Suspense,{fallback:null,children:[r.jsx(el,{show:n,onClose:()=>i(!1),lang:e,handleImportFile:a,importError:d,importSuccess:l,isImporting:h,downloadCSVTemplate:f}),r.jsx(tl,{isCourseWizardOpen:Xe,setIsCourseWizardOpen:ds,lang:e,wizardStep:ke,setWizardStep:At,wizardIsSubmitting:us,wizardCourseTitle:_t,setWizardCourseTitle:hs,wizardCourseDescription:et,setWizardCourseDescription:fs,wizardCourseCategory:zt,setWizardCourseCategory:ps,wizardCourseTimeline:gs,setWizardCourseTimeline:ms,wizardCourseContent:ys,setWizardCourseContent:bs,addToast:b,generateTemplateContent:v,handleDeployWizardCourse:xs}),r.jsx(sl,{isImportLessonsOpen:C,setIsImportLessonsOpen:x,lang:e,importStatus:p,setIsDraggingImport:u,handleCSVFileChange:P,downloadCsvTemplate:I,isDraggingImport:_,previewImportData:S,setPreviewImportData:g,setImportStatus:E,importProgress:O,importProgressTotal:k,importErrorMsg:z,setImportErrorMsg:M,handleCSVImportSubmit:y}),r.jsx(nl,{isQuizGeneratorOpen:Ss,setIsQuizGeneratorOpen:Ue,lessons:N,quizGenMode:vs,setQuizGenMode:ws,quizGenSelectedLessonId:Cs,setQuizGenSelectedLessonId:jt,quizGenTopic:It,setQuizGenTopic:Es,isGeneratingSuggestions:Ps,setIsGeneratingSuggestions:Lt,suggestedObjectives:pt,setSuggestedObjectives:gt,suggestedQuestions:Ts,setSuggestedQuestions:ks,quizGenTimeLimit:ne,setQuizGenTimeLimit:Ge,savingQuiz:Rt,setSavingQuiz:Ot,quizGeneratorClassId:ye,fetchClassDashboard:D}),r.jsx(rl,{isLessonPreviewVisible:A,setIsLessonPreviewVisible:B,lessons:N,selectedLesson:j,previewFullscreenPanel:m,setPreviewFullscreenPanel:L,previewLessonTab:w,setPreviewLessonTab:R,activeRole:F,elements:Z,activeSegmentId:ae,setActiveSegmentId:G,fetchElements:q,currentVfsParent:Q,setCurrentVfsParent:he,vfsNodes:ce,previewSelectedCourseware:Ce,setPreviewSelectedCourseware:We}),r.jsx(il,{showProcessLogs:ze,setShowProcessLogs:se,processLogsContent:Ke,t}),r.jsx(ol,{isOpen:Et,onClose:()=>Pt(!1),vfsNodes:ce,currentVfsParent:Q,setCurrentVfsParent:he,cloudDrivePreviewNode:at,setCloudDrivePreviewNode:ct}),r.jsx(al,{isSystemResourceLibraryOpen:V,setIsSystemResourceLibraryOpen:U,lang:e,systemResourceTab:J,setSystemResourceTab:le,selectedLibraryResourceId:Te,setSelectedLibraryResourceId:Y,vfsNodes:ce,currentVfsParent:Q,setCurrentVfsParent:he,cloudDrivePreviewNode:at,setCloudDrivePreviewNode:ct,loadingLibraryResources:fe,libraryResources:de,fetchLibraryResources:je}),r.jsx(cl,{batchPicker:Ns,setBatchPicker:As,batchPickerLesson:_s,setBatchPickerLesson:tt,batchPickerDate:zs,setBatchPickerDate:He,batchPickerTargetClass:De,setBatchPickerTargetClass:be,lessons:N,classes:qe,expandedClassId:Ee,confirmBatchPicker:js,lang:e}),r.jsx(ll,{isExportWeightModalOpen:Se,setIsExportWeightModalOpen:pe,lang:e,quizzesWeight:lt,setQuizzesWeight:dt,assignmentsWeight:Kt,setAssignmentsWeight:Tt,handleQuizzesWeightChange:Yt,handleAssignmentsWeightChange:Me,customCategoryOverrides:Ye,setCustomCategoryOverrides:ut,classDashboardMap:Xt,exportClassId:es,exportClassName:ts,csvPreviewData:ss,handleExportGrades:ns}),r.jsx(dl,{notification:Is,onClose:()=>Ls(null),lang:e,onOpenWorkspace:mt=>{rs(mt),is("assignment"),os({}),kt("quiz")}}),r.jsx(ul,{isOpen:as,onClose:()=>cs(!1),lang:e,onSeedSuccess:ls,onJumpTab:mt=>ht(mt)}),ft&&r.jsx(hl,{onClose:()=>Nt(!1),lang:e})]})}async function pl(s){const e=s.data;if(!e||typeof e!="object")return;if(typeof window<"u"&&typeof document<"u"&&s.source)try{if(!Array.from(document.querySelectorAll("iframe")).some(f=>f.contentWindow===s.source)&&s.source!==window)return}catch{}let t=e.attempt_id;const n=e.type||"",i=e.payload||e;if(!t&&s.source)try{const l=Array.from(document.querySelectorAll("iframe")).find(h=>h.contentWindow===s.source);if(l&&l.contentWindow){const h=l.contentWindow;h.__LMS_STUDENT__?.attempt_id&&(t=h.__LMS_STUDENT__.attempt_id)}}catch{}if(!t||typeof t!="string")return;const a=n==="LMS_SUBMIT"||n==="LMS_FINISH"||n==="submit"||n==="finish"||n==="completed"||i&&typeof i=="object"&&(i.score!==void 0||i.grade!==void 0||i.result!==void 0||i.points!==void 0),d=n==="LMS_SAVE_PROGRESS"||n==="saveProgress";if(a)try{await fetch(`/api/courseware/attempts/${encodeURIComponent(t)}/submit`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({score:i?.score??i?.grade??i?.result??i?.points??void 0,comment:i?.comment??i?.feedback??i?.note??void 0,completion:i?.completion??1,status:"submitted",extra:i})})}catch(l){console.error("[LMS Bridge] Failed to submit attempt data to backend:",l)}else if(d)try{await fetch(`/api/courseware/attempts/${encodeURIComponent(t)}/submit`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({score:i?.score??i?.grade??i?.result??i?.points??void 0,comment:i?.comment??i?.feedback??void 0,completion:i?.completion??void 0,status:"inprogress",extra:i})})}catch(l){console.error("[LMS Bridge] Failed to save progress to backend:",l)}else try{await fetch(`/api/courseware/attempts/${encodeURIComponent(t)}/log`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({eventType:n||"log",payload:i})})}catch(l){console.error("[LMS Bridge] Failed to log event to backend:",l)}}function gl(s){o.useEffect(()=>{if(!s)return;const e=t=>{pl(t)};return window.addEventListener("message",e),()=>{window.removeEventListener("message",e)}},[s])}function ml(s){const{session:e,showProcessLogs:t,activeStudentId:n,currentVfsParent:i,selectedLesson:a,selectedAssignment:d,expandedClassId:l,fetchLessons:h,fetchPlugins:f,fetchRegisteredCommands:b,fetchEvents:v,fetchApprovals:C,fetchProcesses:x,fetchClasses:p,fetchTodaySchedules:u,fetchStudents:P,fetchLabs:I,fetchVfs:_,fetchProcessLogs:S,fetchClassStudents:g,fetchElements:E}=s,O=o.useRef(i),k=o.useRef(a),z=o.useRef(d),M=o.useRef(l);o.useEffect(()=>{O.current=i},[i]),o.useEffect(()=>{k.current=a},[a]),o.useEffect(()=>{z.current=d},[d]),o.useEffect(()=>{M.current=l},[l]),o.useEffect(()=>{if(!e)return;h(),f(),b(),v(),C(),x(),p(),u(),P(),I(),_(O.current);let y=!1;const N=setInterval(async()=>{if(!y){y=!0;try{if(await v(),await h(),await C(),await x(),await p(),await u().catch(()=>{}),await P(),await I(),await _(O.current),await b(),t&&await S(t),M.current&&await g(M.current),k.current&&await E(k.current),z.current){const D=n||z.current.student_id;await E(`assignment-${z.current.id}-student-${D}`)}}finally{y=!1}}},2e3);return()=>clearInterval(N)},[e,t,n]),o.useEffect(()=>{_(i)},[i]),o.useEffect(()=>{a&&E(a)},[a])}function yl(s){const{lang:e,t,selectedLesson:n,effectiveAgentProviderId:i,expandedClassId:a,fetchLessons:d,fetchClasses:l,fetchStudents:h,fetchClassStudents:f,fetchClassProgress:b,fetchClassDashboard:v,fetchElements:C}=s,[x,p]=o.useState([{role:"agent",content:t.agentIntro||""}]),[u,P]=o.useState(""),[I,_]=o.useState(!1),[S,g]=o.useState([]);o.useEffect(()=>{x.length===1&&x[0].role==="agent"&&p([{role:"agent",content:t.agentIntro}])},[e,t.agentIntro]);const E=o.useCallback(async y=>{try{const N=await fetch(`/api/agent/conversations?lessonId=${encodeURIComponent(y||"")}`);if(!N.ok)return;const D=await N.json(),A=Array.isArray(D.messages)?D.messages:[];A.length>0?p(A.map(B=>({role:B.role==="assistant"?"agent":"user",content:B.content}))):p([{role:"agent",content:t.agentIntro}])}catch{}},[t.agentIntro]),O=o.useCallback(async()=>{try{await fetch(`/api/agent/conversations?lessonId=${encodeURIComponent(n||"")}`,{method:"DELETE"})}catch{}p([{role:"agent",content:t.agentIntro}])},[n,t.agentIntro]);return o.useEffect(()=>{E(n)},[n,E]),{chatLog:x,setChatLog:p,input:u,setInput:P,loading:I,setLoading:_,chatAttachments:S,setChatAttachments:g,handleChatFileChange:y=>{y.target.files&&Array.from(y.target.files).forEach(N=>{const D=new FileReader;D.onload=A=>{A.target?.result&&g(B=>[...B,{name:N.name,content:A.target.result}])},N.name.endsWith(".zip")?D.readAsDataURL(N):D.readAsText(N)})},handleChatDrop:y=>{y.preventDefault(),y.dataTransfer.files&&Array.from(y.dataTransfer.files).forEach(N=>{const D=new FileReader;D.onload=A=>{A.target?.result&&g(B=>[...B,{name:N.name,content:A.target.result}])},N.name.endsWith(".zip")?D.readAsDataURL(N):D.readAsText(N)})},handleSend:async y=>{if(y.preventDefault(),!u.trim()||I)return;const N=[...S];let D=u;N.length>0&&(D+=`
|
|
109
|
-
(📁 ${e==="zh"?"附件":"Attachments"}: ${N.map(A=>A.name).join(", ")})`),p(A=>[...A,{role:"user",content:D}]),P(""),g([]),_(!0);try{const A=await fetch("/api/agent/chat",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({message:u,lang:e,currentLessonId:n,attachments:N,providerId:i==="system"?null:i})}),B=await A.json();let j="";!A.ok||B.success===!1?j=`⚠️ [System Error] ${B.error||(e==="zh"?"未知系统错误":"Unknown System Error")}`:(j=B.agentText||"",B.toolResults&&B.toolResults.length>0&&(j+=`
|
|
110
|
-
|
|
111
|
-
${t.executedCommands}`+B.toolResults.map(m=>m.callName).join(", "))),p(m=>[...m,{role:"agent",content:j}]),await d(),await l(),await h(),a&&(await f(a),await b(a),await v(a)),n&&await C(n)}catch{p(A=>[...A,{role:"agent",content:t.simulationError}])}finally{_(!1)}},handleClearAgentMemory:O,restoreAgentMemory:E}}const _e=Object.create(null);_e.open="0";_e.close="1";_e.ping="2";_e.pong="3";_e.message="4";_e.upgrade="5";_e.noop="6";const qt=Object.create(null);Object.keys(_e).forEach(s=>{qt[_e[s]]=s});const Xs={type:"error",data:"parser error"},yr=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",br=typeof ArrayBuffer=="function",xr=s=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(s):s&&s.buffer instanceof ArrayBuffer,dn=({type:s,data:e},t,n)=>yr&&e instanceof Blob?t?n(e):Yn(e,n):br&&(e instanceof ArrayBuffer||xr(e))?t?n(e):Yn(new Blob([e]),n):n(_e[s]+(e||"")),Yn=(s,e)=>{const t=new FileReader;return t.onload=function(){const n=t.result.split(",")[1];e("b"+(n||""))},t.readAsDataURL(s)};function Xn(s){return s instanceof Uint8Array?s:s instanceof ArrayBuffer?new Uint8Array(s):new Uint8Array(s.buffer,s.byteOffset,s.byteLength)}let Js;function bl(s,e){if(yr&&s.data instanceof Blob)return s.data.arrayBuffer().then(Xn).then(e);if(br&&(s.data instanceof ArrayBuffer||xr(s.data)))return e(Xn(s.data));dn(s,!1,t=>{Js||(Js=new TextEncoder),e(Js.encode(t))})}const er="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",wt=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let s=0;s<er.length;s++)wt[er.charCodeAt(s)]=s;const xl=s=>{let e=s.length*.75,t=s.length,n,i=0,a,d,l,h;s[s.length-1]==="="&&(e--,s[s.length-2]==="="&&e--);const f=new ArrayBuffer(e),b=new Uint8Array(f);for(n=0;n<t;n+=4)a=wt[s.charCodeAt(n)],d=wt[s.charCodeAt(n+1)],l=wt[s.charCodeAt(n+2)],h=wt[s.charCodeAt(n+3)],b[i++]=a<<2|d>>4,b[i++]=(d&15)<<4|l>>2,b[i++]=(l&3)<<6|h&63;return f},Sl=typeof ArrayBuffer=="function",un=(s,e)=>{if(typeof s!="string")return{type:"message",data:Sr(s,e)};const t=s.charAt(0);return t==="b"?{type:"message",data:vl(s.substring(1),e)}:qt[t]?s.length>1?{type:qt[t],data:s.substring(1)}:{type:qt[t]}:Xs},vl=(s,e)=>{if(Sl){const t=xl(s);return Sr(t,e)}else return{base64:!0,data:s}},Sr=(s,e)=>{switch(e){case"blob":return s instanceof Blob?s:new Blob([s]);case"arraybuffer":default:return s instanceof ArrayBuffer?s:s.buffer}},vr="",wl=(s,e)=>{const t=s.length,n=new Array(t);let i=0;s.forEach((a,d)=>{dn(a,!1,l=>{n[d]=l,++i===t&&e(n.join(vr))})})},Cl=(s,e)=>{const t=s.split(vr),n=[];for(let i=0;i<t.length;i++){const a=un(t[i],e);if(n.push(a),a.type==="error")break}return n};function El(){return new TransformStream({transform(s,e){bl(s,t=>{const n=t.length;let i;if(n<126)i=new Uint8Array(1),new DataView(i.buffer).setUint8(0,n);else if(n<65536){i=new Uint8Array(3);const a=new DataView(i.buffer);a.setUint8(0,126),a.setUint16(1,n)}else{i=new Uint8Array(9);const a=new DataView(i.buffer);a.setUint8(0,127),a.setBigUint64(1,BigInt(n))}s.data&&typeof s.data!="string"&&(i[0]|=128),e.enqueue(i),e.enqueue(t)})}})}let Zs;function Bt(s){return s.reduce((e,t)=>e+t.length,0)}function Vt(s,e){if(s[0].length===e)return s.shift();const t=new Uint8Array(e);let n=0;for(let i=0;i<e;i++)t[i]=s[0][n++],n===s[0].length&&(s.shift(),n=0);return s.length&&n<s[0].length&&(s[0]=s[0].slice(n)),t}function Pl(s,e){Zs||(Zs=new TextDecoder);const t=[];let n=0,i=-1,a=!1;return new TransformStream({transform(d,l){for(t.push(d);;){if(n===0){if(Bt(t)<1)break;const h=Vt(t,1);a=(h[0]&128)===128,i=h[0]&127,i<126?n=3:i===126?n=1:n=2}else if(n===1){if(Bt(t)<2)break;const h=Vt(t,2);i=new DataView(h.buffer,h.byteOffset,h.length).getUint16(0),n=3}else if(n===2){if(Bt(t)<8)break;const h=Vt(t,8),f=new DataView(h.buffer,h.byteOffset,h.length),b=f.getUint32(0);if(b>Math.pow(2,21)-1){l.enqueue(Xs);break}i=b*Math.pow(2,32)+f.getUint32(4),n=3}else{if(Bt(t)<i)break;const h=Vt(t,i);l.enqueue(un(a?h:Zs.decode(h),e)),n=0}if(i===0||i>s){l.enqueue(Xs);break}}}})}const wr=4;function te(s){if(s)return Tl(s)}function Tl(s){for(var e in te.prototype)s[e]=te.prototype[e];return s}te.prototype.on=te.prototype.addEventListener=function(s,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+s]=this._callbacks["$"+s]||[]).push(e),this};te.prototype.once=function(s,e){function t(){this.off(s,t),e.apply(this,arguments)}return t.fn=e,this.on(s,t),this};te.prototype.off=te.prototype.removeListener=te.prototype.removeAllListeners=te.prototype.removeEventListener=function(s,e){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var t=this._callbacks["$"+s];if(!t)return this;if(arguments.length==1)return delete this._callbacks["$"+s],this;for(var n,i=0;i<t.length;i++)if(n=t[i],n===e||n.fn===e){t.splice(i,1);break}return t.length===0&&delete this._callbacks["$"+s],this};te.prototype.emit=function(s){this._callbacks=this._callbacks||{};for(var e=new Array(arguments.length-1),t=this._callbacks["$"+s],n=1;n<arguments.length;n++)e[n-1]=arguments[n];if(t){t=t.slice(0);for(var n=0,i=t.length;n<i;++n)t[n].apply(this,e)}return this};te.prototype.emitReserved=te.prototype.emit;te.prototype.listeners=function(s){return this._callbacks=this._callbacks||{},this._callbacks["$"+s]||[]};te.prototype.hasListeners=function(s){return!!this.listeners(s).length};const Jt=typeof Promise=="function"&&typeof Promise.resolve=="function"?e=>Promise.resolve().then(e):(e,t)=>t(e,0),we=typeof self<"u"?self:typeof window<"u"?window:Function("return this")(),kl="arraybuffer";function Cr(s,...e){return e.reduce((t,n)=>(s.hasOwnProperty(n)&&(t[n]=s[n]),t),{})}const Nl=we.setTimeout,Al=we.clearTimeout;function Zt(s,e){e.useNativeTimers?(s.setTimeoutFn=Nl.bind(we),s.clearTimeoutFn=Al.bind(we)):(s.setTimeoutFn=we.setTimeout.bind(we),s.clearTimeoutFn=we.clearTimeout.bind(we))}const _l=1.33;function zl(s){return typeof s=="string"?jl(s):Math.ceil((s.byteLength||s.size)*_l)}function jl(s){let e=0,t=0;for(let n=0,i=s.length;n<i;n++)e=s.charCodeAt(n),e<128?t+=1:e<2048?t+=2:e<55296||e>=57344?t+=3:(n++,t+=4);return t}function Er(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function Il(s){let e="";for(let t in s)s.hasOwnProperty(t)&&(e.length&&(e+="&"),e+=encodeURIComponent(t)+"="+encodeURIComponent(s[t]));return e}function Ll(s){let e={},t=s.split("&");for(let n=0,i=t.length;n<i;n++){let a=t[n].split("=");e[decodeURIComponent(a[0])]=decodeURIComponent(a[1])}return e}class Rl extends Error{constructor(e,t,n){super(e),this.description=t,this.context=n,this.type="TransportError"}}class hn extends te{constructor(e){super(),this.writable=!1,Zt(this,e),this.opts=e,this.query=e.query,this.socket=e.socket,this.supportsBinary=!e.forceBase64}onError(e,t,n){return super.emitReserved("error",new Rl(e,t,n)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return(this.readyState==="opening"||this.readyState==="open")&&(this.doClose(),this.onClose()),this}send(e){this.readyState==="open"&&this.write(e)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){const t=un(e,this.socket.binaryType);this.onPacket(t)}onPacket(e){super.emitReserved("packet",e)}onClose(e){this.readyState="closed",super.emitReserved("close",e)}pause(e){}createUri(e,t={}){return e+"://"+this._hostname()+this._port()+this.opts.path+this._query(t)}_hostname(){const e=this.opts.hostname;return e.indexOf(":")===-1?e:"["+e+"]"}_port(){return this.opts.port&&(this.opts.secure&&Number(this.opts.port)!==443||!this.opts.secure&&Number(this.opts.port)!==80)?":"+this.opts.port:""}_query(e){const t=Il(e);return t.length?"?"+t:""}}class Ol extends hn{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(e){this.readyState="pausing";const t=()=>{this.readyState="paused",e()};if(this._polling||!this.writable){let n=0;this._polling&&(n++,this.once("pollComplete",function(){--n||t()})),this.writable||(n++,this.once("drain",function(){--n||t()}))}else t()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){const t=n=>{if(this.readyState==="opening"&&n.type==="open"&&this.onOpen(),n.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(n)};Cl(e,this.socket.binaryType).forEach(t),this.readyState!=="closed"&&(this._polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"&&this._poll())}doClose(){const e=()=>{this.write([{type:"close"}])};this.readyState==="open"?e():this.once("open",e)}write(e){this.writable=!1,wl(e,t=>{this.doWrite(t,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const e=this.opts.secure?"https":"http",t=this.query||{};return this.opts.timestampRequests!==!1&&(t[this.opts.timestampParam]=Er()),!this.supportsBinary&&!t.sid&&(t.b64=1),this.createUri(e,t)}}let Pr=!1;try{Pr=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}const Ml=Pr;function Dl(){}class $l extends Ol{constructor(e){if(super(e),typeof location<"u"){const t=location.protocol==="https:";let n=location.port;n||(n=t?"443":"80"),this.xd=typeof location<"u"&&e.hostname!==location.hostname||n!==e.port}}doWrite(e,t){const n=this.request({method:"POST",data:e});n.on("success",t),n.on("error",(i,a)=>{this.onError("xhr post error",i,a)})}doPoll(){const e=this.request();e.on("data",this.onData.bind(this)),e.on("error",(t,n)=>{this.onError("xhr poll error",t,n)}),this.pollXhr=e}}class Ae extends te{constructor(e,t,n){super(),this.createRequest=e,Zt(this,n),this._opts=n,this._method=n.method||"GET",this._uri=t,this._data=n.data!==void 0?n.data:null,this._create()}_create(){var e;const t=Cr(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");t.xdomain=!!this._opts.xd;const n=this._xhr=this.createRequest(t);try{n.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){n.setDisableHeaderCheck&&n.setDisableHeaderCheck(!0);for(let i in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(i)&&n.setRequestHeader(i,this._opts.extraHeaders[i])}}catch{}if(this._method==="POST")try{n.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{n.setRequestHeader("Accept","*/*")}catch{}(e=this._opts.cookieJar)===null||e===void 0||e.addCookies(n),"withCredentials"in n&&(n.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(n.timeout=this._opts.requestTimeout),n.onreadystatechange=()=>{var i;n.readyState===3&&((i=this._opts.cookieJar)===null||i===void 0||i.parseCookies(n.getResponseHeader("set-cookie"))),n.readyState===4&&(n.status===200||n.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof n.status=="number"?n.status:0)},0))},n.send(this._data)}catch(i){this.setTimeoutFn(()=>{this._onError(i)},0);return}typeof document<"u"&&(this._index=Ae.requestsCount++,Ae.requests[this._index]=this)}_onError(e){this.emitReserved("error",e,this._xhr),this._cleanup(!0)}_cleanup(e){if(!(typeof this._xhr>"u"||this._xhr===null)){if(this._xhr.onreadystatechange=Dl,e)try{this._xhr.abort()}catch{}typeof document<"u"&&delete Ae.requests[this._index],this._xhr=null}}_onLoad(){const e=this._xhr.responseText;e!==null&&(this.emitReserved("data",e),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}}Ae.requestsCount=0;Ae.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",tr);else if(typeof addEventListener=="function"){const s="onpagehide"in we?"pagehide":"unload";addEventListener(s,tr,!1)}}function tr(){for(let s in Ae.requests)Ae.requests.hasOwnProperty(s)&&Ae.requests[s].abort()}const Fl=(function(){const s=Tr({xdomain:!1});return s&&s.responseType!==null})();class Bl extends $l{constructor(e){super(e);const t=e&&e.forceBase64;this.supportsBinary=Fl&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new Ae(Tr,this.uri(),e)}}function Tr(s){const e=s.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!e||Ml))return new XMLHttpRequest}catch{}if(!e)try{return new we[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}const kr=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class Vl extends hn{get name(){return"websocket"}doOpen(){const e=this.uri(),t=this.opts.protocols,n=kr?{}:Cr(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(n.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(e,t,n)}catch(i){return this.emitReserved("error",i)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:"websocket connection closed",context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError("websocket error",e)}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const n=e[t],i=t===e.length-1;dn(n,this.supportsBinary,a=>{try{this.doWrite(n,a)}catch{}i&&Jt(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){const e=this.opts.secure?"wss":"ws",t=this.query||{};return this.opts.timestampRequests&&(t[this.opts.timestampParam]=Er()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}}const Ks=we.WebSocket||we.MozWebSocket;class Wl extends Vl{createSocket(e,t,n){return kr?new Ks(e,t,n):t?new Ks(e,t):new Ks(e)}doWrite(e,t){this.ws.send(t)}}class ql extends hn{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(e){return this.emitReserved("error",e)}this._transport.closed.then(()=>{this.onClose()}).catch(e=>{this.onError("webtransport error",e)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(e=>{const t=Pl(Number.MAX_SAFE_INTEGER,this.socket.binaryType),n=e.readable.pipeThrough(t).getReader(),i=El();i.readable.pipeTo(e.writable),this._writer=i.writable.getWriter();const a=()=>{n.read().then(({done:l,value:h})=>{l||(this.onPacket(h),a())}).catch(l=>{})};a();const d={type:"open"};this.query.sid&&(d.data=`{"sid":"${this.query.sid}"}`),this._writer.write(d).then(()=>this.onOpen())})})}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const n=e[t],i=t===e.length-1;this._writer.write(n).then(()=>{i&&Jt(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;(e=this._transport)===null||e===void 0||e.close()}}const Ul={websocket:Wl,webtransport:ql,polling:Bl},Gl=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,Hl=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function en(s){if(s.length>8e3)throw"URI too long";const e=s,t=s.indexOf("["),n=s.indexOf("]");t!=-1&&n!=-1&&(s=s.substring(0,t)+s.substring(t,n).replace(/:/g,";")+s.substring(n,s.length));let i=Gl.exec(s||""),a={},d=14;for(;d--;)a[Hl[d]]=i[d]||"";return t!=-1&&n!=-1&&(a.source=e,a.host=a.host.substring(1,a.host.length-1).replace(/;/g,":"),a.authority=a.authority.replace("[","").replace("]","").replace(/;/g,":"),a.ipv6uri=!0),a.pathNames=Ql(a,a.path),a.queryKey=Jl(a,a.query),a}function Ql(s,e){const t=/\/{2,9}/g,n=e.replace(t,"/").split("/");return(e.slice(0,1)=="/"||e.length===0)&&n.splice(0,1),e.slice(-1)=="/"&&n.splice(n.length-1,1),n}function Jl(s,e){const t={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(n,i,a){i&&(t[i]=a)}),t}const tn=typeof addEventListener=="function"&&typeof removeEventListener=="function",Ut=[];tn&&addEventListener("offline",()=>{Ut.forEach(s=>s())},!1);class Be extends te{constructor(e,t){if(super(),this.binaryType=kl,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,e&&typeof e=="object"&&(t=e,e=null),e){const n=en(e);t.hostname=n.host,t.secure=n.protocol==="https"||n.protocol==="wss",t.port=n.port,n.query&&(t.query=n.query)}else t.host&&(t.hostname=en(t.host).host);Zt(this,t),this.secure=t.secure!=null?t.secure:typeof location<"u"&&location.protocol==="https:",t.hostname&&!t.port&&(t.port=this.secure?"443":"80"),this.hostname=t.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=t.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},t.transports.forEach(n=>{const i=n.prototype.name;this.transports.push(i),this._transportsByName[i]=n}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},t),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=Ll(this.opts.query)),tn&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},Ut.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(e){const t=Object.assign({},this.opts.query);t.EIO=wr,t.transport=e,this.id&&(t.sid=this.id);const n=Object.assign({},this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return new this._transportsByName[e](n)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}const e=this.opts.rememberUpgrade&&Be.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1?"websocket":this.transports[0];this.readyState="opening";const t=this.createTransport(e);t.open(),this.setTransport(t)}setTransport(e){this.transport&&this.transport.removeAllListeners(),this.transport=e,e.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",t=>this._onClose("transport close",t))}onOpen(){this.readyState="open",Be.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush()}_onPacket(e){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")switch(this.emitReserved("packet",e),this.emitReserved("heartbeat"),e.type){case"open":this.onHandshake(JSON.parse(e.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":const t=new Error("server error");t.code=e.data,this._onError(t);break;case"message":this.emitReserved("data",e.data),this.emitReserved("message",e.data);break}}onHandshake(e){this.emitReserved("handshake",e),this.id=e.sid,this.transport.query.sid=e.sid,this._pingInterval=e.pingInterval,this._pingTimeout=e.pingTimeout,this._maxPayload=e.maxPayload,this.onOpen(),this.readyState!=="closed"&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);const e=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+e,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},e),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved("drain"):this.flush()}flush(){if(this.readyState!=="closed"&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const e=this._getWritablePackets();this.transport.send(e),this._prevBufferLen=e.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let t=1;for(let n=0;n<this.writeBuffer.length;n++){const i=this.writeBuffer[n].data;if(i&&(t+=zl(i)),n>0&&t>this._maxPayload)return this.writeBuffer.slice(0,n);t+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const e=Date.now()>this._pingTimeoutTime;return e&&(this._pingTimeoutTime=0,Jt(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),e}write(e,t,n){return this._sendPacket("message",e,t,n),this}send(e,t,n){return this._sendPacket("message",e,t,n),this}_sendPacket(e,t,n,i){if(typeof t=="function"&&(i=t,t=void 0),typeof n=="function"&&(i=n,n=null),this.readyState==="closing"||this.readyState==="closed")return;n=n||{},n.compress=n.compress!==!1;const a={type:e,data:t,options:n};this.emitReserved("packetCreate",a),this.writeBuffer.push(a),i&&this.once("flush",i),this.flush()}close(){const e=()=>{this._onClose("forced close"),this.transport.close()},t=()=>{this.off("upgrade",t),this.off("upgradeError",t),e()},n=()=>{this.once("upgrade",t),this.once("upgradeError",t)};return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?n():e()}):this.upgrading?n():e()),this}_onError(e){if(Be.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return this.transports.shift(),this._open();this.emitReserved("error",e),this._onClose("transport error",e)}_onClose(e,t){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing"){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),tn&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const n=Ut.indexOf(this._offlineEventListener);n!==-1&&Ut.splice(n,1)}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}}Be.protocol=wr;class Zl extends Be{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade)for(let e=0;e<this._upgrades.length;e++)this._probe(this._upgrades[e])}_probe(e){let t=this.createTransport(e),n=!1;Be.priorWebsocketSuccess=!1;const i=()=>{n||(t.send([{type:"ping",data:"probe"}]),t.once("packet",v=>{if(!n)if(v.type==="pong"&&v.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;Be.priorWebsocketSuccess=t.name==="websocket",this.transport.pause(()=>{n||this.readyState!=="closed"&&(b(),this.setTransport(t),t.send([{type:"upgrade"}]),this.emitReserved("upgrade",t),t=null,this.upgrading=!1,this.flush())})}else{const C=new Error("probe error");C.transport=t.name,this.emitReserved("upgradeError",C)}}))};function a(){n||(n=!0,b(),t.close(),t=null)}const d=v=>{const C=new Error("probe error: "+v);C.transport=t.name,a(),this.emitReserved("upgradeError",C)};function l(){d("transport closed")}function h(){d("socket closed")}function f(v){t&&v.name!==t.name&&a()}const b=()=>{t.removeListener("open",i),t.removeListener("error",d),t.removeListener("close",l),this.off("close",h),this.off("upgrading",f)};t.once("open",i),t.once("error",d),t.once("close",l),this.once("close",h),this.once("upgrading",f),this._upgrades.indexOf("webtransport")!==-1&&e!=="webtransport"?this.setTimeoutFn(()=>{n||t.open()},200):t.open()}onHandshake(e){this._upgrades=this._filterUpgrades(e.upgrades),super.onHandshake(e)}_filterUpgrades(e){const t=[];for(let n=0;n<e.length;n++)~this.transports.indexOf(e[n])&&t.push(e[n]);return t}}let Kl=class extends Zl{constructor(e,t={}){const n=typeof e=="object"?e:t;(!n.transports||n.transports&&typeof n.transports[0]=="string")&&(n.transports=(n.transports||["polling","websocket","webtransport"]).map(i=>Ul[i]).filter(i=>!!i)),super(e,n)}};function Yl(s,e="",t){let n=s;t=t||typeof location<"u"&&location,s==null&&(s=t.protocol+"//"+t.host),typeof s=="string"&&(s.charAt(0)==="/"&&(s.charAt(1)==="/"?s=t.protocol+s:s=t.host+s),/^(https?|wss?):\/\//.test(s)||(typeof t<"u"?s=t.protocol+"//"+s:s="https://"+s),n=en(s)),n.port||(/^(http|ws)$/.test(n.protocol)?n.port="80":/^(http|ws)s$/.test(n.protocol)&&(n.port="443")),n.path=n.path||"/";const a=n.host.indexOf(":")!==-1?"["+n.host+"]":n.host;return n.id=n.protocol+"://"+a+":"+n.port+e,n.href=n.protocol+"://"+a+(t&&t.port===n.port?"":":"+n.port),n}const Xl=typeof ArrayBuffer=="function",ed=s=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(s):s.buffer instanceof ArrayBuffer,Nr=Object.prototype.toString,td=typeof Blob=="function"||typeof Blob<"u"&&Nr.call(Blob)==="[object BlobConstructor]",sd=typeof File=="function"||typeof File<"u"&&Nr.call(File)==="[object FileConstructor]";function fn(s){return Xl&&(s instanceof ArrayBuffer||ed(s))||td&&s instanceof Blob||sd&&s instanceof File}function Gt(s,e){if(!s||typeof s!="object")return!1;if(Array.isArray(s)){for(let t=0,n=s.length;t<n;t++)if(Gt(s[t]))return!0;return!1}if(fn(s))return!0;if(s.toJSON&&typeof s.toJSON=="function"&&arguments.length===1)return Gt(s.toJSON(),!0);for(const t in s)if(Object.prototype.hasOwnProperty.call(s,t)&&Gt(s[t]))return!0;return!1}function nd(s){const e=[],t=s.data,n=s;return n.data=sn(t,e),n.attachments=e.length,{packet:n,buffers:e}}function sn(s,e){if(!s)return s;if(fn(s)){const t={_placeholder:!0,num:e.length};return e.push(s),t}else if(Array.isArray(s)){const t=new Array(s.length);for(let n=0;n<s.length;n++)t[n]=sn(s[n],e);return t}else if(typeof s=="object"&&!(s instanceof Date)){const t={};for(const n in s)Object.prototype.hasOwnProperty.call(s,n)&&(t[n]=sn(s[n],e));return t}return s}function rd(s,e){return s.data=nn(s.data,e),delete s.attachments,s}function nn(s,e){if(!s)return s;if(s&&s._placeholder===!0){if(typeof s.num=="number"&&s.num>=0&&s.num<e.length)return e[s.num];throw new Error("illegal attachments")}else if(Array.isArray(s))for(let t=0;t<s.length;t++)s[t]=nn(s[t],e);else if(typeof s=="object")for(const t in s)Object.prototype.hasOwnProperty.call(s,t)&&(s[t]=nn(s[t],e));return s}const id=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var H;(function(s){s[s.CONNECT=0]="CONNECT",s[s.DISCONNECT=1]="DISCONNECT",s[s.EVENT=2]="EVENT",s[s.ACK=3]="ACK",s[s.CONNECT_ERROR=4]="CONNECT_ERROR",s[s.BINARY_EVENT=5]="BINARY_EVENT",s[s.BINARY_ACK=6]="BINARY_ACK"})(H||(H={}));class od{constructor(e){this.replacer=e}encode(e){return(e.type===H.EVENT||e.type===H.ACK)&&Gt(e)?this.encodeAsBinary({type:e.type===H.EVENT?H.BINARY_EVENT:H.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id}):[this.encodeAsString(e)]}encodeAsString(e){let t=""+e.type;return(e.type===H.BINARY_EVENT||e.type===H.BINARY_ACK)&&(t+=e.attachments+"-"),e.nsp&&e.nsp!=="/"&&(t+=e.nsp+","),e.id!=null&&(t+=e.id),e.data!=null&&(t+=JSON.stringify(e.data,this.replacer)),t}encodeAsBinary(e){const t=nd(e),n=this.encodeAsString(t.packet),i=t.buffers;return i.unshift(n),i}}class pn extends te{constructor(e){super(),this.opts=Object.assign({reviver:void 0,maxAttachments:10},typeof e=="function"?{reviver:e}:e)}add(e){let t;if(typeof e=="string"){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");t=this.decodeString(e);const n=t.type===H.BINARY_EVENT;n||t.type===H.BINARY_ACK?(t.type=n?H.EVENT:H.ACK,this.reconstructor=new ad(t),t.attachments===0&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else if(fn(e)||e.base64)if(this.reconstructor)t=this.reconstructor.takeBinaryData(e),t&&(this.reconstructor=null,super.emitReserved("decoded",t));else throw new Error("got binary data when not reconstructing a packet");else throw new Error("Unknown type: "+e)}decodeString(e){let t=0;const n={type:Number(e.charAt(0))};if(H[n.type]===void 0)throw new Error("unknown packet type "+n.type);if(n.type===H.BINARY_EVENT||n.type===H.BINARY_ACK){const a=t+1;for(;e.charAt(++t)!=="-"&&t!=e.length;);const d=e.substring(a,t);if(d!=Number(d)||e.charAt(t)!=="-")throw new Error("Illegal attachments");const l=Number(d);if(!cd(l)||l<0)throw new Error("Illegal attachments");if(l>this.opts.maxAttachments)throw new Error("too many attachments");n.attachments=l}if(e.charAt(t+1)==="/"){const a=t+1;for(;++t&&!(e.charAt(t)===","||t===e.length););n.nsp=e.substring(a,t)}else n.nsp="/";const i=e.charAt(t+1);if(i!==""&&Number(i)==i){const a=t+1;for(;++t;){const d=e.charAt(t);if(d==null||Number(d)!=d){--t;break}if(t===e.length)break}n.id=Number(e.substring(a,t+1))}if(e.charAt(++t)){const a=this.tryParse(e.substr(t));if(pn.isPayloadValid(n.type,a))n.data=a;else throw new Error("invalid payload")}return n}tryParse(e){try{return JSON.parse(e,this.opts.reviver)}catch{return!1}}static isPayloadValid(e,t){switch(e){case H.CONNECT:return sr(t);case H.DISCONNECT:return t===void 0;case H.CONNECT_ERROR:return typeof t=="string"||sr(t);case H.EVENT:case H.BINARY_EVENT:return Array.isArray(t)&&(typeof t[0]=="number"||typeof t[0]=="string"&&id.indexOf(t[0])===-1);case H.ACK:case H.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class ad{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){const t=rd(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const cd=Number.isInteger||function(s){return typeof s=="number"&&isFinite(s)&&Math.floor(s)===s};function sr(s){return Object.prototype.toString.call(s)==="[object Object]"}const ld=Object.freeze(Object.defineProperty({__proto__:null,Decoder:pn,Encoder:od,get PacketType(){return H}},Symbol.toStringTag,{value:"Module"}));function Pe(s,e,t){return s.on(e,t),function(){s.off(e,t)}}const dd=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class Ar extends te{constructor(e,t,n){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=t,n&&n.auth&&(this.auth=n.auth),this._opts=Object.assign({},n),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const e=this.io;this.subs=[Pe(e,"open",this.onopen.bind(this)),Pe(e,"packet",this.onpacket.bind(this)),Pe(e,"error",this.onerror.bind(this)),Pe(e,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected?this:(this.subEvents(),this.io._reconnecting||this.io.open(),this.io._readyState==="open"&&this.onopen(),this)}open(){return this.connect()}send(...e){return e.unshift("message"),this.emit.apply(this,e),this}emit(e,...t){var n,i,a;if(dd.hasOwnProperty(e))throw new Error('"'+e.toString()+'" is a reserved event name');if(t.unshift(e),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(t),this;const d={type:H.EVENT,data:t};if(d.options={},d.options.compress=this.flags.compress!==!1,typeof t[t.length-1]=="function"){const b=this.ids++,v=t.pop();this._registerAckCallback(b,v),d.id=b}const l=(i=(n=this.io.engine)===null||n===void 0?void 0:n.transport)===null||i===void 0?void 0:i.writable,h=this.connected&&!(!((a=this.io.engine)===null||a===void 0)&&a._hasPingExpired());return this.flags.volatile&&!l||(h?(this.notifyOutgoingListeners(d),this.packet(d)):this.sendBuffer.push(d)),this.flags={},this}_registerAckCallback(e,t){var n;const i=(n=this.flags.timeout)!==null&&n!==void 0?n:this._opts.ackTimeout;if(i===void 0){this.acks[e]=t;return}const a=this.io.setTimeoutFn(()=>{delete this.acks[e];for(let l=0;l<this.sendBuffer.length;l++)this.sendBuffer[l].id===e&&this.sendBuffer.splice(l,1);t.call(this,new Error("operation has timed out"))},i),d=(...l)=>{this.io.clearTimeoutFn(a),t.apply(this,l)};d.withError=!0,this.acks[e]=d}emitWithAck(e,...t){return new Promise((n,i)=>{const a=(d,l)=>d?i(d):n(l);a.withError=!0,t.push(a),this.emit(e,...t)})}_addToQueue(e){let t;typeof e[e.length-1]=="function"&&(t=e.pop());const n={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((i,...a)=>(this._queue[0],i!==null?n.tryCount>this._opts.retries&&(this._queue.shift(),t&&t(i)):(this._queue.shift(),t&&t(null,...a)),n.pending=!1,this._drainQueue())),this._queue.push(n),this._drainQueue()}_drainQueue(e=!1){if(!this.connected||this._queue.length===0)return;const t=this._queue[0];t.pending&&!e||(t.pending=!0,t.tryCount++,this.flags=t.flags,this.emit.apply(this,t.args))}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){typeof this.auth=="function"?this.auth(e=>{this._sendConnectPacket(e)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:H.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},e):e})}onerror(e){this.connected||this.emitReserved("connect_error",e)}onclose(e,t){this.connected=!1,delete this.id,this.emitReserved("disconnect",e,t),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(e=>{if(!this.sendBuffer.some(n=>String(n.id)===e)){const n=this.acks[e];delete this.acks[e],n.withError&&n.call(this,new Error("socket has been disconnected"))}})}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case H.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case H.EVENT:case H.BINARY_EVENT:this.onevent(e);break;case H.ACK:case H.BINARY_ACK:this.onack(e);break;case H.DISCONNECT:this.ondisconnect();break;case H.CONNECT_ERROR:this.destroy();const n=new Error(e.data.message);n.data=e.data.data,this.emitReserved("connect_error",n);break}}onevent(e){const t=e.data||[];e.id!=null&&t.push(this.ack(e.id)),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length){const t=this._anyListeners.slice();for(const n of t)n.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&typeof e[e.length-1]=="string"&&(this._lastOffset=e[e.length-1])}ack(e){const t=this;let n=!1;return function(...i){n||(n=!0,t.packet({type:H.ACK,id:e,data:i}))}}onack(e){const t=this.acks[e.id];typeof t=="function"&&(delete this.acks[e.id],t.withError&&e.data.unshift(null),t.apply(this,e.data))}onconnect(e,t){this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this._drainQueue(!0),this.emitReserved("connect")}emitBuffered(){this.receiveBuffer.forEach(e=>this.emitEvent(e)),this.receiveBuffer=[],this.sendBuffer.forEach(e=>{this.notifyOutgoingListeners(e),this.packet(e)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(e=>e()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:H.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){const t=this._anyListeners;for(let n=0;n<t.length;n++)if(e===t[n])return t.splice(n,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}prependAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}offAnyOutgoing(e){if(!this._anyOutgoingListeners)return this;if(e){const t=this._anyOutgoingListeners;for(let n=0;n<t.length;n++)if(e===t[n])return t.splice(n,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const t=this._anyOutgoingListeners.slice();for(const n of t)n.apply(this,e.data)}}}function ot(s){s=s||{},this.ms=s.min||100,this.max=s.max||1e4,this.factor=s.factor||2,this.jitter=s.jitter>0&&s.jitter<=1?s.jitter:0,this.attempts=0}ot.prototype.duration=function(){var s=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var e=Math.random(),t=Math.floor(e*this.jitter*s);s=(Math.floor(e*10)&1)==0?s-t:s+t}return Math.min(s,this.max)|0};ot.prototype.reset=function(){this.attempts=0};ot.prototype.setMin=function(s){this.ms=s};ot.prototype.setMax=function(s){this.max=s};ot.prototype.setJitter=function(s){this.jitter=s};class rn extends te{constructor(e,t){var n;super(),this.nsps={},this.subs=[],e&&typeof e=="object"&&(t=e,e=void 0),t=t||{},t.path=t.path||"/socket.io",this.opts=t,Zt(this,t),this.reconnection(t.reconnection!==!1),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor((n=t.randomizationFactor)!==null&&n!==void 0?n:.5),this.backoff=new ot({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(t.timeout==null?2e4:t.timeout),this._readyState="closed",this.uri=e;const i=t.parser||ld;this.encoder=new i.Encoder,this.decoder=new i.Decoder,this._autoConnect=t.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,e||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(e){return e===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return e===void 0?this._reconnectionDelay:(this._reconnectionDelay=e,(t=this.backoff)===null||t===void 0||t.setMin(e),this)}randomizationFactor(e){var t;return e===void 0?this._randomizationFactor:(this._randomizationFactor=e,(t=this.backoff)===null||t===void 0||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return e===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,(t=this.backoff)===null||t===void 0||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(e){if(~this._readyState.indexOf("open"))return this;this.engine=new Kl(this.uri,this.opts);const t=this.engine,n=this;this._readyState="opening",this.skipReconnect=!1;const i=Pe(t,"open",function(){n.onopen(),e&&e()}),a=l=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",l),e?e(l):this.maybeReconnectOnOpen()},d=Pe(t,"error",a);if(this._timeout!==!1){const l=this._timeout,h=this.setTimeoutFn(()=>{i(),a(new Error("timeout")),t.close()},l);this.opts.autoUnref&&h.unref(),this.subs.push(()=>{this.clearTimeoutFn(h)})}return this.subs.push(i),this.subs.push(d),this}connect(e){return this.open(e)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const e=this.engine;this.subs.push(Pe(e,"ping",this.onping.bind(this)),Pe(e,"data",this.ondata.bind(this)),Pe(e,"error",this.onerror.bind(this)),Pe(e,"close",this.onclose.bind(this)),Pe(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){try{this.decoder.add(e)}catch(t){this.onclose("parse error",t)}}ondecoded(e){Jt(()=>{this.emitReserved("packet",e)},this.setTimeoutFn)}onerror(e){this.emitReserved("error",e)}socket(e,t){let n=this.nsps[e];return n?this._autoConnect&&!n.active&&n.connect():(n=new Ar(this,e,t),this.nsps[e]=n),n}_destroy(e){const t=Object.keys(this.nsps);for(const n of t)if(this.nsps[n].active)return;this._close()}_packet(e){const t=this.encoder.encode(e);for(let n=0;n<t.length;n++)this.engine.write(t[n],e.options)}cleanup(){this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(e,t){var n;this.cleanup(),(n=this.engine)===null||n===void 0||n.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",e,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const e=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const t=this.backoff.duration();this._reconnecting=!0;const n=this.setTimeoutFn(()=>{e.skipReconnect||(this.emitReserved("reconnect_attempt",e.backoff.attempts),!e.skipReconnect&&e.open(i=>{i?(e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",i)):e.onreconnect()}))},t);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}}onreconnect(){const e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}}const vt={};function Ht(s,e){typeof s=="object"&&(e=s,s=void 0),e=e||{};const t=Yl(s,e.path||"/socket.io"),n=t.source,i=t.id,a=t.path,d=vt[i]&&a in vt[i].nsps,l=e.forceNew||e["force new connection"]||e.multiplex===!1||d;let h;return l?h=new rn(n,e):(vt[i]||(vt[i]=new rn(n,e)),h=vt[i]),t.query&&!e.query&&(e.query=t.queryKey),h.socket(t.path,e)}Object.assign(Ht,{Manager:rn,Socket:Ar,io:Ht,connect:Ht});class ud{constructor(e=""){this.baseUrl=e}async get(e){return this.request("GET",e)}async post(e,t){return this.request("POST",e,t)}async del(e){return this.request("DELETE",e)}async request(e,t,n){try{const i=`${this.baseUrl}${t}`,a={method:e,credentials:"same-origin",headers:{"Content-Type":"application/json"}};return n!==void 0&&e!=="GET"&&e!=="DELETE"&&(a.body=JSON.stringify(n)),await(await fetch(i,a)).json()}catch(i){return{success:!1,error:i.message??"Network error"}}}}let on=null;function hd(s){on=s}function Wu(){if(!on)throw new Error("Socket instance not initialized. Call setSocketInstance() first.");return on}class fd{constructor(e){this.socket=e,hd(e)}emit(e,...t){this.socket.emit(e,...t)}on(e,t){this.socket.on(e,t)}off(e,t){this.socket.off(e,t)}disconnect(){this.socket.disconnect()}}class pd{constructor(e){this.modalState=null,this.addToastFn=e??null}showToast(e,t,n="info"){this.addToastFn?this.addToastFn(e,t,n):console.warn("[UIService] No addToast callback registered — toast not shown:",e,t)}showModal(e,t){this.modalState={visible:!0,title:e,content:t}}closeModal(){this.modalState=null}getModalState(){return this.modalState}downloadFile(e,t,n="application/octet-stream"){const i=typeof e=="string"?new Blob([e],{type:n}):e,a=URL.createObjectURL(i),d=document.createElement("a");d.href=a,d.download=t,document.body.appendChild(d),d.click(),document.body.removeChild(d),URL.revokeObjectURL(a)}}class gd{constructor(e){this.prefix=`edu_os_plugin:${e}:`}get(e){return localStorage.getItem(this.prefix+e)}set(e,t){localStorage.setItem(this.prefix+e,t)}delete(e){localStorage.removeItem(this.prefix+e)}clear(){this.prefix.length;const e=[];for(let t=0;t<localStorage.length;t++){const n=localStorage.key(t);n&&n.startsWith(this.prefix)&&e.push(n)}for(const t of e)localStorage.removeItem(t)}}function md(s){const{session:e,host:t,activeRole:n,activeStudentId:i,selectedLesson:a,activeSegmentId:d,studentViewStatus:l,lang:h,students:f,addToast:b,setOnlineStudentIds:v,setActiveStudentLessons:C,setLessons:x,setActiveSegmentId:p,setLiveClassStudentProgress:u,setLiveClassAcknowledgedMap:P,setLiveClassFeed:I,setSelectedLesson:_,setStudentViewStatus:S,setLocalProgressPercent:g,fetchStudentDashboard:E,fetchStudents:O,fetchElements:k}=s,z=o.useRef(null),M=o.useRef(n),y=o.useRef(i),N=o.useRef(h),D=o.useRef(f),A=o.useRef(b),B=o.useRef(a);return o.useEffect(()=>{M.current=n},[n]),o.useEffect(()=>{y.current=i},[i]),o.useEffect(()=>{N.current=h},[h]),o.useEffect(()=>{D.current=f},[f]),o.useEffect(()=>{A.current=b},[b]),o.useEffect(()=>{B.current=a},[a]),o.useEffect(()=>{if(!e)return;const j=Ht();return z.current=j,t.isInitialized()||t.initialize(new ud,new fd(j),new pd(A.current),new gd("__app__")),M.current==="student"&&y.current&&j.emit("register-student",{studentId:y.current,name:D.current.find(m=>m.id===y.current)?.name||y.current}),j.emit("join-room","whiteboard-broadcast"),j.on("presence-update",m=>{v(m.onlineStudentIds),C(m.activeStudentLessons)}),j.on("lesson-progress-mode-changed",m=>{const{lessonId:L,progressMode:w,progressConditions:R}=m;x(F=>F.map(Z=>Z.id===L?{...Z,progress_mode:w,progress_conditions:R}:Z))}),j.on("student-active-segment-changed",m=>{const{activeSegmentId:L}=m;p(L)}),j.on("student-pinged",m=>{const L=m.message||(N.current==="zh"?"⚠️ 学习进度预警:老师注意到您的进度有些落后,请抓紧时间跟上!":"⚠️ Progress Alert: The teacher noticed you are falling behind. Please keep up!");b(N.current==="zh"?"⚠️ 学习进度预警":"⚠️ Progress Warning",L,"warning")}),j.on("student-progress-updated",m=>{const{studentId:L,progressPercent:w,completed:R}=m;u(F=>{const Z=F.findIndex(ae=>ae.student_id===L);if(Z!==-1){const ae=[...F];return ae[Z]={...ae[Z],progress_percent:w,completed:R?1:0},ae}else return[...F,{student_id:L,progress_percent:w,completed:R?1:0}]})}),j.on("assignment-graded-toast",m=>{if(M.current==="student"&&y.current&&m.studentId===y.current){const L=m.assignmentTitle||m.assignmentId,w=N.current==="zh"?`您的作业"${L}"已完成评分!得分:${m.score}%。建议反馈已收到,快去查看。`:`Your assignment "${L}" was graded. Score: ${m.score}%. Tutoring feedback has been posted.`;b(N.current==="zh"?"🎓 作业已评分":"🎓 Assignment Graded",w,"success"),E(y.current)}}),j.on("student-picked",m=>{if(M.current==="student"&&y.current&&m.studentId===y.current){const L=N.current==="zh"?"闪电警报!您已被老师在课程随机提问点名中抽中!请立即集中注意力参与课堂。":"Attention alert! You have been randomly picked by the teacher! Please pay immediate attention.";b(N.current==="zh"?"⚡️ 随机点名提问":"⚡️ Classroom Pick Alert",L,"warning"),E(y.current)}I(L=>[{id:`feed-pick-${m.studentId}-${m.pickedTime||Date.now()}`,time:new Date(m.pickedTime||Date.now()).toLocaleTimeString(),type:"picked",message:N.current==="zh"?`点名互动:随机抽中学生【${m.studentName}】。`:`Classroom Pick: Randomly selected student "${m.studentName}".`},...L])}),j.on("student-acknowledged",m=>{const{studentId:L}=m;P(w=>{const R=new Map(w);return R.set(L,!0),R}),I(w=>[{id:`feed-ack-${L}-${Date.now()}`,time:new Date().toLocaleTimeString(),type:"checkin",message:N.current==="zh"?`学生已确认收到提问点名(学生 ID: ${L})。`:`Student acknowledged the classroom call (Student ID: ${L}).`},...w]),O()}),j.on("class-lock-status-changed",m=>{const{lessonId:L,locked:w}=m;M.current==="student"&&y.current?(Promise.resolve(O()).then(()=>{w&&L&&(_(L),S("lesson"),b(N.current==="zh"?"🔒 课程已被锁定":"🔒 Lesson Locked",N.current==="zh"?"老师已锁定当前授课,您将无法切换到其他页面。":"The teacher has locked the active lesson. You cannot leave this page.","info"))}),E(y.current)):O()}),j.on("whiteboard-sync",m=>{const{roomId:L,type:w}=m||{};w==="refresh"&&L&&(k(L),!B.current&&M.current==="student"&&(_(L),S("lesson")),j.emit("join-room",L))}),()=>{j.disconnect(),z.current=null}},[e,n,i]),o.useEffect(()=>{z.current&&n==="student"&&i&&(l==="lesson"&&a?(z.current.emit("enter-lesson",{studentId:i,lessonId:a}),fetch(`/api/students/${i}/progress`).then(j=>j.json()).then(j=>{if(Array.isArray(j)){const m=j.find(L=>L.lesson_id===a);g(m?m.progress_percent:0)}}).catch(console.error)):z.current.emit("leave-lesson",{studentId:i}))},[l,a,n,i]),o.useEffect(()=>{n==="teacher"&&a&&d&&z.current&&z.current.emit("teacher-broadcast-segment",{lessonId:a,activeSegmentId:d})},[d,a,n]),{socketRef:z}}const yd=`exports.default = {
|
|
112
|
-
manifest: {
|
|
113
|
-
id: "@my-scope/hello-world",
|
|
114
|
-
name: "Hello World Plugin",
|
|
115
|
-
version: "1.0.0",
|
|
116
|
-
capabilitiesProposed: ["lesson:read"]
|
|
117
|
-
},
|
|
118
|
-
activate: async (ctx) => {
|
|
119
|
-
ctx.log.info('Hello World plugin activated');
|
|
120
|
-
}
|
|
121
|
-
};`;function bd(s){const{host:e,lang:t,addToast:n,setChatLog:i,setTeacherTab:a,fetchLessons:d}=s,[l,h]=o.useState([]),[f,b]=o.useState([]),[v,C]=o.useState(!1),[x,p]=o.useState(null),[u,P]=o.useState(""),[I,_]=o.useState(""),[S,g]=o.useState(""),[E,O]=o.useState(""),[k,z]=o.useState(null),[M,y]=o.useState(!1),[N,D]=o.useState("store"),[A,B]=o.useState(yd),[j,m]=o.useState(!1),[L,w]=o.useState([]),[R,F]=o.useState([]),[Z,ae]=o.useState({}),G=o.useRef(new Set),q=o.useCallback(async()=>{try{const V=await fetch("/api/plugins");if(V.ok){const U=await V.json();h(U)}}catch(V){console.warn("Failed to fetch plugins",V)}},[]),Q=o.useCallback(async()=>{try{const V=await fetch("/api/ai-providers");if(V.ok){const U=await V.json();b(U)}}catch(V){console.warn("Failed to fetch AI Providers",V)}},[]),he=o.useCallback(async()=>{try{const V=await fetch("/api/events");V.ok&&w(await V.json())}catch{}},[]),ce=o.useCallback(async()=>{try{const V=await fetch("/api/approvals");V.ok&&F(await V.json())}catch{}},[]);return{plugins:l,setPlugins:h,fetchPlugins:q,aiProviders:f,setAiProviders:b,fetchAIProviders:Q,isAIProviderModalOpen:v,setIsAIProviderModalOpen:C,editingAIProvider:x,setEditingAIProvider:p,providerName:u,setProviderName:P,providerApiUrl:I,setProviderApiUrl:_,providerApiKey:S,setProviderApiKey:g,providerModelName:E,setProviderModelName:O,testingProviderId:k,setTestingProviderId:z,showPluginModal:M,setShowPluginModal:y,storeTab:N,setStoreTab:D,pluginCode:A,setPluginCode:B,installingPlugin:j,setInstallingPlugin:m,events:L,setEvents:w,fetchEvents:he,approvals:R,setApprovals:F,fetchApprovals:ce,scoreOverrides:Z,setScoreOverrides:ae,handleSaveAIProvider:async()=>{if(!u.trim()||!I.trim()||!E.trim()){n(t==="zh"?"表单不完整":"Incomplete Form",t==="zh"?"请填写提供商名称、API 基础地址与模型标识。":"Please fill in Name, API URL, and Model Name.","warning");return}try{let V;if(x?V=await fetch(`/api/ai-providers/${x.id}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:u,api_url:I,api_key:S,model_name:E})}):V=await fetch("/api/ai-providers",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:u,api_url:I,api_key:S,model_name:E})}),V.ok)n(t==="zh"?"保存成功":"Saved Successfully",t==="zh"?`AI 提供商 [${u}] 已保存。`:`AI Provider [${u}] has been updated.`,"success"),C(!1),p(null),P(""),_(""),g(""),O(""),Q();else{const U=await V.json().catch(()=>({}));n(t==="zh"?"保存失败":"Failed to Save",U.error||(t==="zh"?"无法写入数据库":"Failed to write to database"),"warning")}}catch(V){console.error(V),n(t==="zh"?"保存异常":"Execution Error",V.message||"Error occurred","warning")}},handleDeleteAIProvider:async(V,U)=>{if(confirm(t==="zh"?`确定要删除 AI 提供商 [${U}] 吗?此操作无法撤销。`:`Are you sure you want to delete AI Provider [${U}]?`))try{(await fetch(`/api/ai-providers/${V}`,{method:"DELETE"})).ok?(n(t==="zh"?"删除成功":"Deleted Successfully",t==="zh"?`AI 提供商 [${U}] 已经被清除。`:`AI Provider [${U}] has been removed.`,"success"),Q()):n(t==="zh"?"删除失败":"Failed to Delete","Database error","warning")}catch(J){console.error(J),n(t==="zh"?"操作异常":"Execution Error",J.message||"Error occurred","warning")}},handleTestAIProvider:async V=>{z(V.id);try{const U=await fetch("/api/ai-providers/test",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({api_url:V.api_url,api_key:V.api_key,model_name:V.model_name})}),J=await U.json();U.ok&&J.success?n(t==="zh"?"测试通过":"Test Succeeded",t==="zh"?`成功连接至 [${V.name}]。${J.message}`:`Successfully connected to [${V.name}]. ${J.message}`,"success"):n(t==="zh"?"测试失败":"Test Failed",J.error||"Connection error","warning")}catch(U){console.error(U),n(t==="zh"?"连接异常":"Connection Exception",U.message||"Error occurred","warning")}finally{z(null)}},handleInstallPlugin:async()=>{if(A.trim()){m(!0);try{const U=await(await fetch("/api/plugins",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sourceCode:A})})).json();U.success?(await q(),y(!1),i(J=>[...J,{role:"agent",content:`[System] Plugin "${U.manifest.name}" installed successfully. You can now prompt me to use it.`}])):alert("Plugin installation failed: "+U.error)}catch(V){alert("Error: "+V.message)}finally{m(!1)}}},handleZipPluginUpload:async(V,U,J)=>{m(!0);const le=J?.mode==="update";try{const Te={"Content-Type":"application/octet-stream","X-Filename":encodeURIComponent(V.name),"X-Execution-Mode":U,"X-Install-Mode":le?"update":"install","X-Allow-Downgrade":J?.allowDowngrade?"true":"false"};J?.targetPluginId&&(Te["X-Target-Plugin-Id"]=encodeURIComponent(J.targetPluginId));const Y=le&&J?.targetPluginId?`/api/plugins/${encodeURIComponent(J.targetPluginId)}/update-zip-raw`:"/api/plugins/upload-zip-raw",fe=await fetch(Y,{method:"POST",headers:Te,body:V}),de=await fe.json().catch(()=>({}));if(!fe.ok||!de.success){const Se=de.error||"Unknown error";throw n(t==="zh"?le?"更新失败":"安装失败":le?"Update Failed":"Installation Failed",Se,"error"),new Error(Se)}const je=de.pluginId||de.manifest?.pluginId||de.manifest?.id,qe=!!(de.updated||le);if(!qe&&je)await fetch(`/api/plugins/${encodeURIComponent(je)}/toggle`,{method:"POST"}).catch(()=>{});else if(qe&&de.wasActive&&je)try{await e.deactivatePlugin(je)}catch{}a("plugins"),D("store"),await q(),setTimeout(()=>{q()},1e3);const Ee=de.manifest?.name||je||V.name;if(qe){const Se=de.oldVersion||"?",pe=de.newVersion||de.manifest?.version||"?";n(t==="zh"?"插件更新成功":"Plugin Updated",t==="zh"?`"${Ee}" 已从 v${Se} 更新到 v${pe}(配置与数据已保留)`:`"${Ee}" updated v${Se} → v${pe} (config & data preserved)`,"success"),i(lt=>[...lt,{role:"agent",content:`[System] Plugin "${Ee}" updated ${Se} → ${pe}.`}])}else n(t==="zh"?"插件安装成功":"Plugin Installed",t==="zh"?`三方插件 "${Ee}" 已成功上传并以 [${U==="worker"?"Worker 隔离":"VM 嵌入"}] 模式激活运行!`:`Plugin "${Ee}" installed and activated in [${U}] mode!`,"success"),i(Se=>[...Se,{role:"agent",content:`[System] Plugin "${Ee}" installed successfully from ZIP file.`}])}catch(Te){const Y=Te?.message?String(Te.message):"";throw Y&&Y!=="Failed to fetch"&&Y!=="Network error"||n(t==="zh"?"网络错误":"Network Error",Y||"Network error","error"),Te}finally{m(!1)}},handleTogglePlugin:async V=>{if(!G.current.has(V)){G.current.add(V);try{const U=await fetch(`/api/plugins/${encodeURIComponent(V)}/toggle`,{method:"POST"}),J=await U.json().catch(()=>({}));if(U.ok)await q();else{const le=J.error||"Unknown error";le.includes("requires human approval")||le.includes("queued")?(alert(t==="zh"?'该操作已加入"待审批高危操作"列表,请在右侧侧边栏中通过审批以生效。':"This action has been queued. Please approve it in the Pending Approvals list on the right side."),await ce()):alert((t==="zh"?"切换插件状态失败: ":"Failed to toggle plugin: ")+le)}}catch(U){console.error("Failed to toggle plugin:",U),alert(t==="zh"?"网络错误,切换插件失败":"Network error, failed to toggle plugin")}finally{G.current.delete(V)}}},handleDeletePlugin:async V=>{if(window.confirm(t==="zh"?"确定要彻底删除该插件吗?删除后此插件相关的功能将无法使用。":"Are you sure you want to completely delete this plugin? This cannot be undone."))try{const U=await fetch(`/api/plugins/${encodeURIComponent(V)}`,{method:"DELETE"});if(U.ok)a("plugins"),D("store"),await q(),i(J=>[...J,{role:"agent",content:"[System] Plugin uninstalled and deleted."}]);else{const J=await U.json().catch(()=>({}));alert(J.error||(t==="zh"?"删除插件失败":"Failed to delete plugin"))}}catch(U){console.error("Failed to delete plugin:",U),alert(t==="zh"?"删除插件失败":"Failed to delete plugin")}},handleApprove:async(V,U)=>{try{const le=await(await fetch(`/api/approvals/${V}/approve`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({payloadOverride:U})})).json();le.success?(await ce(),await d(),await q()):alert("Action failed: "+le.error)}catch(J){console.error(J)}},handleReject:async V=>{try{await fetch(`/api/approvals/${V}/reject`,{method:"POST"}),await ce(),await q()}catch(U){console.error(U)}}}}function xd(s){const{lang:e,addToast:t,fetchLessons:n,setSelectedLesson:i,setTeacherTab:a}=s,[d,l]=o.useState(!1),[h,f]=o.useState(1),[b,v]=o.useState(""),[C,x]=o.useState("Mathematics"),[p,u]=o.useState(""),[P,I]=o.useState(""),[_,S]=o.useState([{id:"seg-w1",title:"Course Orientation / 课堂导入",type:"intro",duration:"5m",color:"bg-blue-50 text-blue-700 border-blue-200 hover:bg-blue-100",notes:"Introduce basic goals"},{id:"seg-w2",title:"Subject Core Lecture / 核心精讲",type:"lecture",duration:"20m",color:"bg-indigo-50 text-indigo-700 border-indigo-200 hover:bg-indigo-100",notes:"Present major content frameworks"},{id:"seg-w3",title:"Interactive Lab Work / 实践演练",type:"practice",duration:"15m",color:"bg-green-50 text-green-700 border-green-200 hover:bg-green-100",notes:"Provide collaborative assignments on terminal or board"},{id:"seg-w4",title:"Wrap up / 随堂总结与答疑",type:"summary",duration:"5m",color:"bg-purple-50 text-purple-700 border-purple-200 hover:bg-purple-100",notes:"Reflect and assign task"}]),[g,E]=o.useState(!1);return{isCourseWizardOpen:d,setIsCourseWizardOpen:l,wizardStep:h,setWizardStep:f,wizardCourseTitle:b,setWizardCourseTitle:v,wizardCourseCategory:C,setWizardCourseCategory:x,wizardCourseDescription:p,setWizardCourseDescription:u,wizardCourseContent:P,setWizardCourseContent:I,wizardCourseTimeline:_,setWizardCourseTimeline:S,wizardIsSubmitting:g,setWizardIsSubmitting:E,handleDeployWizardCourse:async()=>{if(!b.trim()){alert(e==="zh"?"请输入课程标题!":"Please provide a course title!");return}E(!0);try{const k=P.trim()||`Course outline for ${b} (${C})`,z=await fetch("/api/lessons",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:b,content:k})});if(z.ok){const y=(await z.json()).result?.lessonId;y&&await fetch(`/api/lessons/${y}/timeline`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({timeline:_})}),await n(),y&&(i(y),a("lesson_editor")),t(e==="zh"?"⭐ 课程发布成功":"⭐ Course Deployed Successfully",e==="zh"?`课程《${b}》已成功保存到核心SQLite并已自动激活!`:`Course "${b}" is now live in SQLite and auto-activated.`,"success"),l(!1),v(""),x("Mathematics"),u(""),I(""),f(1)}else t("Error","SQLite save failed","warning")}catch(k){console.error(k),t("Error","Launch Exception","warning")}finally{E(!1)}}}}function Sd(){const[s,e]=o.useState(!1),[t,n]=o.useState(null),[i,a]=o.useState("scan_lesson"),[d,l]=o.useState(""),[h,f]=o.useState(""),[b,v]=o.useState(!1),[C,x]=o.useState([]),[p,u]=o.useState([]),[P,I]=o.useState(!1),[_,S]=o.useState({}),[g,E]=o.useState(10),[O,k]=o.useState("quiz"),z=o.useRef(_);return o.useEffect(()=>{z.current=_},[_]),{isQuizGeneratorOpen:s,setIsQuizGeneratorOpen:e,quizGeneratorClassId:t,setQuizGeneratorClassId:n,quizGenMode:i,setQuizGenMode:a,quizGenSelectedLessonId:d,setQuizGenSelectedLessonId:l,quizGenTopic:h,setQuizGenTopic:f,isGeneratingSuggestions:b,setIsGeneratingSuggestions:v,suggestedObjectives:C,setSuggestedObjectives:x,suggestedQuestions:p,setSuggestedQuestions:u,savingQuiz:P,setSavingQuiz:I,quizStudentAnswers:_,setQuizStudentAnswers:S,quizGenTimeLimit:g,setQuizGenTimeLimit:E,quizStudentAnswersRef:z,subAssignmentTab:O,setSubAssignmentTab:k}}function vd(s){const{lang:e,classes:t,expandedClassId:n,fetchClasses:i,fetchClassStudents:a,handleExportAllClassesCombined:d}=s,[l,h]=o.useState(!1),[f,b]=o.useState(new Set),[v,C]=o.useState(new Set),[x,p]=o.useState(null),[u,P]=o.useState(""),[I,_]=o.useState(""),[S,g]=o.useState("");return{batchMode:l,setBatchMode:h,selectedClassIds:f,setSelectedClassIds:b,selectedStudentIds:v,setSelectedStudentIds:C,batchPicker:x,setBatchPicker:p,batchPickerLesson:u,setBatchPickerLesson:P,batchPickerDate:I,setBatchPickerDate:_,batchPickerTargetClass:S,setBatchPickerTargetClass:g,toggleClassSelection:w=>{b(R=>{const F=new Set(R);return F.has(w)?F.delete(w):F.add(w),F})},toggleSelectAllClasses:()=>{b(w=>w.size===t.length&&t.length>0?new Set:new Set(t.map(R=>R.id)))},toggleStudentSelection:w=>{C(R=>{const F=new Set(R);return F.has(w)?F.delete(w):F.add(w),F})},toggleSelectAllStudents:w=>{C(R=>R.size===w.length&&w.length>0?new Set:new Set(w.map(F=>F.id)))},handleBatchDeleteClasses:async()=>{if(f.size!==0&&confirm(e==="zh"?`确认彻底删除选中的 ${f.size} 个班级吗?该操作不可恢复。`:`Delete ${f.size} selected classes permanently?`)){for(const w of f)await fetch(`/api/classes/${w}`,{method:"DELETE"});b(new Set),await i()}},handleBatchExportClasses:async()=>{f.size!==0&&await d(t.filter(w=>f.has(w.id)))},handleBatchSetPasscode:async()=>{if(f.size===0)return;const w=window.prompt(e==="zh"?"请输入临时班级密码(留空则清除):":"Enter temporary passcode (leave empty to clear):");if(w!==null){for(const R of f)await fetch(`/api/classes/${R}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({class_passcode:w===""?null:w})});b(new Set),await i()}},handleBatchScheduleClasses:()=>{f.size!==0&&(P(""),_(new Date().toISOString().split("T")[0]),p("schedule"))},handleBatchDeleteStudents:async()=>{if(!(v.size===0||!n)&&confirm(e==="zh"?`确认彻底删除选中的 ${v.size} 名学生账号吗?将删除其全部关联数据,不可恢复。`:`Permanently delete ${v.size} selected student accounts?`)){for(const w of v)await fetch(`/api/students/${w}`,{method:"DELETE"});C(new Set),await a(n)}},handleBatchResetPassword:async()=>{if(v.size===0||!n)return;const w=window.prompt(e==="zh"?"请输入要为选中学生设置的新密码:":"Enter new password for selected students:");if(!(w===null||w.trim()==="")){for(const R of v)await fetch(`/api/students/${R}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:w})});C(new Set),await a(n)}},handleBatchTransferStudents:()=>{v.size===0||!n||(g(""),p("transfer"))},handleBatchSetLockedLesson:()=>{v.size===0||!n||(P(""),p("lockedLesson"))},confirmBatchPicker:async()=>{if(n){if(x==="schedule"){if(!u){alert(e==="zh"?"请选择课程":"Please select a lesson");return}for(const w of f)await fetch(`/api/classes/${w}/schedules`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({lessonId:u,scheduledDate:I+" 09:00:00",status:"scheduled"})});b(new Set)}else if(x==="lockedLesson"){if(!u){alert(e==="zh"?"请选择课程":"Please select a lesson");return}for(const w of v)await fetch(`/api/students/${w}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({locked_lesson_id:u})});C(new Set)}else if(x==="transfer"){if(!S||S===n){alert(e==="zh"?"请选择不同的目标班级":"Please select a different target class");return}for(const w of v)await fetch(`/api/classes/${n}/students/${w}`,{method:"DELETE"}),await fetch(`/api/classes/${S}/students`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({studentId:w})});C(new Set)}p(null),n&&await a(n)}}}}function wd(){const[s,e]=o.useState([]),[t,n]=o.useState(!1),[i,a]=o.useState({lab_id:null,seats:[]}),[d,l]=o.useState(!1),[h,f]=o.useState([]),[b,v]=o.useState({}),[C,x]=o.useState({}),[p,u]=o.useState(null),[P,I]=o.useState(""),[_,S]=o.useState(""),g=o.useCallback(async()=>{try{n(!0);const M=await fetch("/api/labs");M.ok&&e(await M.json())}catch(M){console.error(M)}finally{n(!1)}},[]),E=o.useCallback(async M=>{try{const y=await fetch(`/api/classes/${M}/seats`);if(y.ok){const N=await y.json();a(N)}}catch(y){console.error(y)}},[]),O=o.useCallback(async()=>{try{const M=new Date().toISOString().split("T")[0],y=await fetch(`/api/schedules/today?date=${M}`);if(y.ok){const N=await y.json();N.success&&N.schedules&&f(N.schedules)}}catch(M){console.warn("Failed to fetch today schedules",M)}},[]),k=o.useCallback(async M=>{try{const y=await fetch(`/api/classes/${M}/schedules`);if(y.ok){const N=await y.json();v(D=>({...D,[M]:N}))}}catch{}},[]),z=o.useCallback(async M=>{try{const y=await fetch(`/api/schedules/${M}/attendance`);if(y.ok){const N=await y.json();x(D=>({...D,[M]:N}))}}catch{}},[]);return{computerLabs:s,setComputerLabs:e,loadingLabs:t,setLoadingLabs:n,fetchLabs:g,classSeats:i,setClassSeats:a,savingSeats:d,setSavingSeats:l,fetchClassSeats:E,todaySchedules:h,setTodaySchedules:f,fetchTodaySchedules:O,classSchedulesMap:b,setClassSchedulesMap:v,fetchClassSchedules:k,scheduleAttendanceMap:C,setScheduleAttendanceMap:x,fetchScheduleAttendance:z,expandedScheduleId:p,setExpandedScheduleId:u,newScheduleDate:P,setNewScheduleDate:I,newScheduleLessonId:_,setNewScheduleLessonId:S}}function Cd(s){const{selectedLesson:e,lessons:t,setLessons:n}=s,[i,a]=o.useState([]),[d,l]=o.useState("seg-1"),[h,f]=o.useState(null),[b,v]=o.useState(null),[C,x]=o.useState("none"),[p,u]=o.useState(null),[P,I]=o.useState(!0),_=o.useRef(null),S=async(g,E)=>{x("saving");try{(await fetch(`/api/lessons/${g}/timeline`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({timeline:E})})).ok?(n(k=>k.map(z=>z.id===g?{...z,timeline:JSON.stringify(E)}:z)),a(E),x("saved"),u(new Date)):x("error")}catch(O){console.error("Failed to save timeline:",O),x("error")}};return o.useEffect(()=>{if(e){const g=t.find(E=>E.id===e);if(g){let E=[];if(g.timeline)try{E=typeof g.timeline=="string"?JSON.parse(g.timeline):g.timeline}catch{E=[{id:"seg-1",title:"开场准备",type:"intro",duration:"5m",color:"bg-blue-50 text-blue-700 border-blue-200 hover:bg-blue-100"},{id:"seg-2",title:"讲授新课",type:"lecture",duration:"20m",color:"bg-indigo-50 text-indigo-700 border-indigo-200 hover:bg-indigo-100"},{id:"seg-3",title:"互动练习",type:"practice",duration:"15m",color:"bg-green-50 text-green-700 border-green-200 hover:bg-green-100"},{id:"seg-4",title:"课堂总结",type:"summary",duration:"5m",color:"bg-purple-50 text-purple-700 border-purple-200 hover:bg-purple-100"}]}else E=[{id:"seg-1",title:"开场准备",type:"intro",duration:"5m",color:"bg-blue-50 text-blue-700 border-blue-200 hover:bg-blue-100"},{id:"seg-2",title:"讲授新课",type:"lecture",duration:"20m",color:"bg-indigo-50 text-indigo-700 border-indigo-200 hover:bg-indigo-100"},{id:"seg-3",title:"互动练习",type:"practice",duration:"15m",color:"bg-green-50 text-green-700 border-green-200 hover:bg-green-100"},{id:"seg-4",title:"课堂总结",type:"summary",duration:"5m",color:"bg-purple-50 text-purple-700 border-purple-200 hover:bg-purple-100"}];a(E);const O=_.current!==e;_.current=e,E.length>0?(O||!E.some(k=>k.id===d))&&l(E[0].id):l(null)}}},[e,t]),{timelineSegments:i,setTimelineSegments:a,activeSegmentId:d,setActiveSegmentId:l,segmentToEdit:h,setSegmentToEdit:f,draggedSegmentIdx:b,setDraggedSegmentIdx:v,editorSaveStatus:C,setEditorSaveStatus:x,editorLastSavedTime:p,setEditorLastSavedTime:u,editorPanelsExpanded:P,setEditorPanelsExpanded:I,saveTimeline:S}}function Ed(s,e,t){const[n,i]=o.useState(new Set),[a,d]=o.useState(null),[l,h]=o.useState(!1),f=o.useMemo(()=>{if(s!=="student"||!e)return[];const v=[],C=e.assignments||[];for(const p of C)if(!p.submission_status)v.push({id:`new-${p.id}`,type:"new_assignment",title:t==="zh"?"新发布作业":"New Assignment",message:t==="zh"?`您有一项新作业:"${p.title}"`:`You have a new assignment: ${p.title}`,date:p.created_at,relatedId:p.id});else if(p.submission_status==="graded"){const u=!!p.feedback;v.push({id:`graded-${p.id}`,type:"graded",title:u?t==="zh"?"收到新成绩与反馈":"Grade & Feedback Posted":t==="zh"?"新成绩发布":"Assignment Graded",message:u?t==="zh"?`您的作业"${p.title}"已评分,得分:${p.score}%。反馈:"${p.feedback}"`:`Your assignment "${p.title}" was graded. Score: ${p.score}%. Teacher feedback: "${p.feedback}"`:t==="zh"?`您的作业"${p.title}"已评分,得分:${p.score}%`:`Your assignment "${p.title}" was graded. Score: ${p.score}%`,date:p.submitted_at||p.created_at,relatedId:p.id})}const x=e.rollcalls||[];for(const p of x)v.push({id:p.id,type:"rollcall_picked",title:t==="zh"?"⚡️ 随机提问选中通知":"⚡️ Random Pick Notification",message:t==="zh"?`您已被老师在课程"${p.lesson_title||"课堂"}"中随机选中提问!请立即确认您的出勤与注意。`:`You have been randomly picked by the teacher in lesson "${p.lesson_title||"Class"}"! Please pay immediate attention.`,date:p.picked_time,relatedId:p.lesson_id});return v.sort((p,u)=>u.date-p.date)},[s,e,t]),b=o.useMemo(()=>f.filter(v=>!n.has(v.id)),[f,n]);return{studentNotifications:f,unreadNotifications:b,readNotifications:n,setReadNotifications:i,selectedNotificationForModal:a,setSelectedNotificationForModal:d,isNotificationsOpen:l,setIsNotificationsOpen:h}}function _r(s){if(s==null)return"";const e=String(s);return e.includes(",")||e.includes('"')||e.includes(`
|
|
122
|
-
`)?`"${e.replace(/"/g,'""')}"`:e}async function Pd(s){const{classId:e,className:t,students:n,dashData:i,lang:a,addToast:d,setIsGeneratingPDFReport:l}=s;l(h=>({...h,[e]:!0}));try{if(!i){d(a==="zh"?"暂无班级评分数据":"No Class Performance Data",a==="zh"?"请确保在此班级加载了作业与测验。":"Please check if assignments or quizzes are present for this class.","warning");return}const h=i.performance||[],f=i.assignments||[],b={};n.forEach(m=>{b[m.id]={id:m.id,name:m.name,totalGradesSum:0,gradedCount:0,submittedCount:0,totalCount:0}}),h.forEach(m=>{const L=m.student_id;b[L]&&(b[L].totalCount++,(m.submission_status==="submitted"||m.submission_status==="graded")&&b[L].submittedCount++,m.score!==null&&m.score!==void 0&&(b[L].totalGradesSum+=m.score,b[L].gradedCount++))});const v=Object.values(b).map(m=>{const L=m.gradedCount>0?m.totalGradesSum/m.gradedCount:0,w=m.totalCount>0?m.submittedCount/m.totalCount*100:0;return{...m,avgScore:L,submissionRate:w}});v.sort((m,L)=>L.avgScore-m.avgScore);let C=0,x=0,p=0,u=0;h.forEach(m=>{u++,(m.submission_status==="submitted"||m.submission_status==="graded")&&p++,m.score!==null&&m.score!==void 0&&(C+=m.score,x++)});const P=x>0?C/x:0,I=u>0?p/u*100:0,_={};f.forEach(m=>{_[m.id]={id:m.id,title:m.title,scores:[],submittedCount:0,totalCount:0}}),h.forEach(m=>{const L=m.assignment_id;_[L]&&(_[L].totalCount++,(m.submission_status==="submitted"||m.submission_status==="graded")&&_[L].submittedCount++,m.score!==null&&m.score!==void 0&&_[L].scores.push(m.score))});const S=Object.values(_).map(m=>{const L=m.scores.length,w=m.scores.reduce((G,q)=>G+q,0),R=L>0?w/L:0,F=L>0?Math.max(...m.scores):0,Z=L>0?Math.min(...m.scores):0,ae=m.totalCount>0?m.submittedCount/m.totalCount*100:0;return{...m,avg:R,max:F,min:Z,subRate:ae}}),g=new mc({orientation:"p",unit:"mm",format:"a4"}),E=[15,23,42],O=[79,70,229],k=[51,65,85],z=[226,232,240],M=m=>{g.setDrawColor(z[0],z[1],z[2]),g.setLineWidth(.3),g.line(14,m,196,m)};g.setFillColor(E[0],E[1],E[2]),g.rect(0,0,210,42,"F"),g.setTextColor(255,255,255),g.setFont("helvetica","bold"),g.setFontSize(20),g.text("CLASS PERFORMANCE REPORT",14,18),g.setFont("helvetica","normal"),g.setFontSize(10),g.setTextColor(194,205,225),g.text("Academic Insights • Generative Report Summary",14,25),g.text(`Classroom: ${t} | Date: ${new Date().toLocaleDateString()} ${new Date().toLocaleTimeString()}`,14,32),g.setFillColor(O[0],O[1],O[2]),g.rect(172,10,24,24,"F"),g.setFont("helvetica","bold"),g.setFontSize(14),g.setTextColor(255,255,255),g.text("OS",180,26);let y=52;g.setTextColor(E[0],E[1],E[2]),g.setFont("helvetica","bold"),g.setFontSize(12),g.text("I. EXECUTIVE OVERVIEW",14,y),y+=6;const N=[["Classroom/Subject Name",t],["Total Enrolled Students",`${n.length} student(s)`],["Curriculum Items (Assignments/Quizzes)",`${f.length} items`],["Global Assignment Submission Rate",`${I.toFixed(1)}%`],["Class Average Performance Score",`${P.toFixed(1)}%`]];g.autoTable({startY:y,head:[["Metric Indicator","Class-wide Metric Value"]],body:N,theme:"striped",headStyles:{fillColor:E,textColor:[255,255,255],fontStyle:"bold",fontSize:9},bodyStyles:{textColor:k,fontSize:8.5},margin:{left:14,right:14}}),y=g.lastAutoTable.finalY+12,g.setTextColor(E[0],E[1],E[2]),g.setFont("helvetica","bold"),g.setFontSize(12),g.text("II. STUDENT RANKING DISTRIBUTION",14,y),y+=6;const D=v.map((m,L)=>{let w="Excellent";return m.avgScore>=90?w="Excellent (A)":m.avgScore>=75?w="Good (B)":m.avgScore>=60?w="Satisfactory (C)":w="Needs Improvement (D)",[`${L+1}`,m.name,`${m.submittedCount}/${m.totalCount} (${m.submissionRate.toFixed(0)}%)`,`${m.avgScore.toFixed(1)}%`,w]});g.autoTable({startY:y,head:[["Rank","Student Name","Completion Rate","Average Score","Academic Standing Tier"]],body:D,theme:"grid",headStyles:{fillColor:O,textColor:[255,255,255],fontStyle:"bold",fontSize:8.5},bodyStyles:{textColor:k,fontSize:8},alternateRowStyles:{fillColor:[248,250,252]},columnStyles:{0:{cellWidth:15,halign:"center",fontStyle:"bold"},1:{fontStyle:"bold"},2:{halign:"center"},3:{halign:"center",fontStyle:"bold"}},margin:{left:14,right:14}}),y=g.lastAutoTable.finalY+12,y>210&&(g.addPage(),y=20),g.setTextColor(E[0],E[1],E[2]),g.setFont("helvetica","bold"),g.setFontSize(12),g.text("III. ASSIGNMENT PERFORMANCE METRICS",14,y),y+=6;const A=S.map(m=>[m.title,`${m.subRate.toFixed(0)}%`,`${m.avg.toFixed(1)}%`,`${m.min.toFixed(0)}% - ${m.max.toFixed(0)}%`]);g.autoTable({startY:y,head:[["Assignment/Quiz Title","Submission Rate","Average Grade","Range (Min - Max)"]],body:A.length>0?A:[["No assignment performance records found.","-","-","-"]],theme:"striped",headStyles:{fillColor:[100,116,139],textColor:[255,255,255],fontStyle:"bold",fontSize:8.5},bodyStyles:{textColor:k,fontSize:8},columnStyles:{1:{halign:"center"},2:{halign:"center",fontStyle:"bold"},3:{halign:"center"}},margin:{left:14,right:14}}),y=g.lastAutoTable.finalY+15,M(275),g.setFontSize(8),g.setTextColor(148,163,184),g.text("Generated by OpenLearn Next • Educational Operating System",14,282),g.text("Page 1 of 1 • Internal Educational Audit",196,282,{align:"right"});const B=t.replace(/[^a-z0-9]/gi,"_").toLowerCase(),j=new Date().toISOString().split("T")[0];g.save(`Class_Report_${B}_${j}.pdf`),d(a==="zh"?"📄 PDF 报告导出完成":"📄 PDF Report Generated",a==="zh"?`班级【${t}】的综合学情 PDF 报告已生成并下载。`:`Class performance report for ${t} saved to your device.`,"success")}catch(h){console.error("PDF Generation Failed:",h),d(a==="zh"?"❌ PDF 报告生成失败":"❌ PDF Report Failed",h.message||"Error occurred during PDF generation","warning")}finally{l(h=>({...h,[e]:!1}))}}function Td(s){const{className:e,students:t,dashData:n,qWeight:i=40,aWeight:a=60,overrides:d={}}=s;if(!n||!n.assignments){alert("No performance data available to export. Please open the dashboard to load class data first.");return}if(t.length===0){alert("No students in this class to export grades for.");return}const l=n.assignments||[],h=n.performance||[],f=l.map(S=>{let g="assignment";if(d[S.id])g=d[S.id];else{const E=S.content&&S.content.startsWith('{"quizType":"mcq_learning_objectives"'),O=S.title&&(S.title.toLowerCase().includes("quiz")||S.title.toLowerCase().includes("test")||S.title.includes("测验")||S.title.includes("测试"));g=E||O?"quiz":"assignment"}return{...S,category:g}}),b=["Student Name","Student Email"];f.forEach(S=>{const g=S.category==="quiz"?"Quiz":"Assignment";b.push(`${g}: ${S.title}`)}),b.push("Quizzes Average","Assignments Average",`Weighted Average (${i}% Quizzes, ${a}% Assignments)`,"Simple Average Score","Submitted Count","Total Items");const v=[b];t.forEach(S=>{const g=[S.name,S.email];let E=0,O=0,k=0,z=0,M=0,y=0,N=0;f.forEach(w=>{const R=h.find(F=>F.assignment_id===w.id&&F.student_id===S.id);if(R&&R.score!==null&&R.score!==void 0){g.push(`${R.score}%`);const F=Number(R.score);w.category==="quiz"?(E+=F,O++):(k+=F,z++),M+=F,y++,N++}else R&&R.submission_status==="submitted"?(g.push("Pending Grade"),N++):g.push("Not Submitted")});const D=O>0?Math.round(E/O):null,A=z>0?Math.round(k/z):null;let B="N/A";if(D!==null&&A!==null){const w=D*(i/100)+A*(a/100);B=`${Math.round(w)}%`}else D!==null?B=`${D}%`:A!==null&&(B=`${A}%`);const j=D!==null?`${D}%`:"N/A",m=A!==null?`${A}%`:"N/A",L=y>0?`${Math.round(M/y)}%`:"N/A";g.push(j,m,B,L,`${N}`,`${l.length}`),v.push(g.map(_r))});const C=v.map(S=>S.join(",")).join(`
|
|
123
|
-
`),x=new Blob(["\uFEFF"+C],{type:"text/csv;charset=utf-8;"}),p=URL.createObjectURL(x),u=document.createElement("a"),P=e.replace(/[^a-z0-9]/gi,"_").toLowerCase(),I=new Date().toISOString().split("T")[0],_=`${P}_grades_report_${I}.csv`;u.setAttribute("href",p),u.setAttribute("download",_),u.style.visibility="hidden",document.body.appendChild(u),u.click(),document.body.removeChild(u),URL.revokeObjectURL(p)}function kd(s){const{exportClassId:e,classStudentsMap:t,classDashboardMap:n,quizzesWeight:i,assignmentsWeight:a,customCategoryOverrides:d,lang:l}=s;if(!e)return null;const h=t[e]||[],f=n[e];if(!f||!f.assignments||h.length===0)return null;const b=f.assignments||[],v=f.performance||[],C=b.map(P=>{let I="assignment";if(d[P.id])I=d[P.id];else{const _=P.content&&P.content.startsWith('{"quizType":"mcq_learning_objectives"'),S=P.title&&(P.title.toLowerCase().includes("quiz")||P.title.toLowerCase().includes("test")||P.title.includes("测验")||P.title.includes("测试"));I=_||S?"quiz":"assignment"}return{...P,category:I}}),x=["Student Name","Student Email"];C.forEach(P=>{const I=P.category==="quiz"?"Quiz":"Assignment";x.push(`${I}: ${P.title}`)}),x.push("Quizzes Average","Assignments Average",`Weighted Average (${i}% Quizzes, ${a}% Assignments)`,"Simple Average Score","Submitted Count","Total Items");const p=[];return h.slice(0,5).forEach(P=>{const I=[P.name,P.email];let _=0,S=0,g=0,E=0,O=0,k=0,z=0;C.forEach(j=>{const m=v.find(L=>L.assignment_id===j.id&&L.student_id===P.id);if(m&&m.score!==null&&m.score!==void 0){I.push(`${m.score}%`);const L=Number(m.score);j.category==="quiz"?(_+=L,S++):(g+=L,E++),O+=L,k++,z++}else m&&m.submission_status==="submitted"?(I.push(l==="zh"?"待评分":"Pending Grade"),z++):I.push(l==="zh"?"未提交":"Not Submitted")});const M=S>0?Math.round(_/S):null,y=E>0?Math.round(g/E):null;let N="N/A";if(M!==null&&y!==null){const j=M*(i/100)+y*(a/100);N=`${Math.round(j)}%`}else M!==null?N=`${M}%`:y!==null&&(N=`${y}%`);const D=M!==null?`${M}%`:"N/A",A=y!==null?`${y}%`:"N/A",B=k>0?`${Math.round(O/k)}%`:"N/A";I.push(D,A,N,B,`${z}`,`${b.length}`),p.push(I)}),{headers:x,rows:p,totalStudents:h.length}}function Nd(s){const{classes:e,classStudentsMap:t,classDashboardMap:n,lang:i}=s,d=[["Class Name","Student Name","Student Email","Quizzes Average","Assignments Average","Calculated Weighted Score (40% Quiz / 60% Assignment)","Simple Average Score","Submitted Count","Total Items"]];if(e.forEach(b=>{const v=t[b.id]||[],C=n[b.id];if(!C||!C.assignments||v.length===0)return;const x=C.assignments||[],p=x.map(u=>{const P=u.content&&u.content.startsWith('{"quizType":"mcq_learning_objectives"'),I=u.title&&(u.title.toLowerCase().includes("quiz")||u.title.toLowerCase().includes("test")||u.title.includes("测验")||u.title.includes("测试"));return{...u,category:P||I?"quiz":"assignment"}});v.forEach(u=>{let P=0,I=0,_=0,S=0,g=0,E=0;p.forEach(N=>{const D=C.performance?.find(A=>A.student_id===u.id&&A.assignment_id===N.id&&A.submission_status==="graded"&&A.score!==null);if(D){const A=Number(D.score);g+=A,E++,N.category==="quiz"?(P+=A,I++):(_+=A,S++)}});const O=I>0?Math.round(P/I):null,k=S>0?Math.round(_/S):null;let z=0;O!==null&&k!==null?z=Math.round(O*.4+k*.6):O!==null?z=Math.round(O):k!==null&&(z=Math.round(k));const M=E>0?Math.round(g/E):0,y=[b.name,u.name,u.email,O!==null?`${O}%`:"N/A",k!==null?`${k}%`:"N/A",`${z}%`,`${M}%`,`${E}`,`${x.length}`];d.push(y)})}),d.length<=1){alert(i==="zh"?"暂无可导出的成绩数据。请确保班级中有已评分的作业。":"No graded performance data available to export.");return}const l="data:text/csv;charset=utf-8,\uFEFF"+d.map(b=>b.map(_r).join(",")).join(`
|
|
124
|
-
`),h=encodeURI(l),f=document.createElement("a");f.setAttribute("href",h),f.setAttribute("download",`All_Classes_Combined_Grades_${new Date().toISOString().slice(0,10)}.csv`),document.body.appendChild(f),f.click(),document.body.removeChild(f)}function Ad(s){const{lang:e,classes:t,classStudentsMap:n,classDashboardMap:i,fetchClassStudents:a,fetchClassDashboard:d,fetchClassProgress:l,addToast:h=()=>{}}=s,[f,b]=o.useState(!1),[v,C]=o.useState(""),[x,p]=o.useState(""),[u,P]=o.useState(40),[I,_]=o.useState(60),[S,g]=o.useState({}),[E,O]=o.useState(!1),[k,z]=o.useState(!1),[M,y]=o.useState(null),[N,D]=o.useState(!1),[A,B]=o.useState({}),j=o.useCallback(G=>{const q=Math.min(100,Math.max(0,G));P(q),_(100-q)},[]),m=o.useCallback(G=>{const q=Math.min(100,Math.max(0,G));_(q),P(100-q)},[]),L=o.useMemo(()=>kd({exportClassId:v,classStudentsMap:n,classDashboardMap:i,quizzesWeight:u,assignmentsWeight:I,customCategoryOverrides:S,lang:e}),[v,u,I,S,n,i,e]),w=o.useCallback(async(G,q)=>{y(G);try{await a(G),await d(G),await l(G),C(G),p(q),P(40),_(60),g({}),b(!0)}catch(Q){console.error(Q)}finally{y(null),O(!1)}},[a,d,l]),R=o.useCallback((G,q,Q=40,he=60,ce={})=>{Td({className:q,students:n[G]||[],dashData:i[G],qWeight:Q,aWeight:he,overrides:ce})},[n,i]),F=o.useCallback(async(G,q)=>{await a(G),await d(G),await l(G),await Pd({classId:G,className:q,students:n[G]||[],dashData:i[G],lang:e,addToast:h,setIsGeneratingPDFReport:B})},[n,i,e,h,a,d,l]),Z=o.useCallback(async()=>{D(!0);try{await Nd({classes:t,classStudentsMap:n,classDashboardMap:i,lang:e})}catch(G){console.error("Export all classes error:",G)}finally{D(!1),O(!1)}},[t,n,i,e]),ae=o.useCallback((G,q)=>{const Q=i[q];if(!Q||!Q.performance)return null;const he=Date.now()-2592e6,Ce=Q.performance.filter(se=>se.student_id===G).filter(se=>se.submitted_at&&se.submitted_at>=he&&se.score!==null&&se.score!==void 0);if(Ce.length===0)return null;const ze=Ce.reduce((se,Ke)=>se+Number(Ke.score),0)/Ce.length;return ze<60?Math.round(ze):null},[i]);return{isExportWeightModalOpen:f,setIsExportWeightModalOpen:b,exportClassId:v,setExportClassId:C,exportClassName:x,setExportClassName:p,quizzesWeight:u,setQuizzesWeight:P,assignmentsWeight:I,setAssignmentsWeight:_,customCategoryOverrides:S,setCustomCategoryOverrides:g,exportDropdownOpen:E,setExportDropdownOpen:O,exportTooltipOpen:k,setExportTooltipOpen:z,loadingExportClassId:M,setLoadingExportClassId:y,isExportingAllCombined:N,setIsExportingAllCombined:D,isGeneratingPDFReport:A,setIsGeneratingPDFReport:B,handleQuizzesWeightChange:j,handleAssignmentsWeightChange:m,csvPreviewData:L,triggerExportForClass:w,handleExportGrades:R,handleGeneratePDFReport:F,handleExportAllClassesCombined:Z,get30DayAverageWarning:ae}}function _d(s){const[e,t]=o.useState(""),[n,i]=o.useState("recent"),[a,d]=o.useState(!1),[l,h]=o.useState(!1),[f,b]=o.useState(!1),[v,C]=o.useState(null),x=o.useMemo(()=>{let p=[...s];if(e.trim()){const u=e.toLowerCase();p=p.filter(P=>P.title.toLowerCase().includes(u)||P.content.toLowerCase().includes(u))}if(a&&(p=p.filter(u=>(u.enrollment_count||0)>0)),l&&(p=p.filter(u=>u.content&&u.content.trim().length>0)),f){const u=new Date(new Date().getFullYear(),new Date().getMonth(),1).getTime();p=p.filter(P=>(P.created_at||0)>=u)}return n==="recent"?p.sort((u,P)=>(P.created_at||0)-(u.created_at||0)):n==="alphabetical"?p.sort((u,P)=>u.title.localeCompare(P.title)):n==="enrollment"&&p.sort((u,P)=>(P.enrollment_count||0)-(u.enrollment_count||0)),p},[s,e,n,a,l,f]);return{lessonsSearchQuery:e,setLessonsSearchQuery:t,lessonsSortOrder:n,setLessonsSortOrder:i,filterEnrollment:a,setFilterEnrollment:d,filterHasContent:l,setFilterHasContent:h,filterThisMonth:f,setFilterThisMonth:b,copyingLessonId:v,setCopyingLessonId:C,filteredAndSortedLessons:x}}function nr(s,e){let t="",n="",i="";s==="class"?(t=e==="zh"?"班级及学生批量导入模板.csv":"class_import_template.csv",n="Class Name,Class Desc,Student Name,Student Email",i=e==="zh"?`高一A班,基础英语课程,李明,liming@example.com
|
|
125
|
-
高一A班,基础英语课程,王华,wanghua@example.com`:`Class 101,Introduction to English,John Doe,john@example.com
|
|
126
|
-
Class 101,Introduction to English,Jane Smith,jane@example.com`):(t=e==="zh"?"学生批量导入模板.csv":"student_import_template.csv",n="Student Name,Student Email",i=e==="zh"?`张三,zhangsan@example.com
|
|
127
|
-
李四,lisi@example.com`:`Alice Cooper,alice@example.com
|
|
128
|
-
Bob Dylan,bob@example.com`);const a=new Blob(["\uFEFF"+n+`
|
|
129
|
-
`+i],{type:"text/csv;charset=utf-8;"}),d=URL.createObjectURL(a),l=document.createElement("a");l.href=d,l.setAttribute("download",t),document.body.appendChild(l),l.click(),document.body.removeChild(l)}async function zd(s,e){const{lang:t,fetchClasses:n,fetchStudents:i}=e;return new Promise((a,d)=>{const l=new FileReader;l.onload=async h=>{try{const f=h.target?.result;if(!f)throw new Error("File content is empty");let b=[],v=[],C=!0;if(s.name.endsWith(".json")){const x=JSON.parse(f);if(!Array.isArray(x))throw new Error("JSON structure must be an array");x.some(u=>u.className||u.name&&(u.students||u.classDescription))?(C=!0,b=x.map(u=>{const P=u.name||u.className||u.class_name,I=u.description||u.classDescription||"",_=u.students||u.studentList||[],S=(Array.isArray(_)?_:[]).map(g=>({name:g.name||g.studentName||"",email:g.email||g.studentEmail||""})).filter(g=>g.name);return{name:P,description:I,students:S}}).filter(u=>u.name)):(C=!1,v=x.map(u=>({name:u.name||u.studentName||u.student_name||"",email:u.email||u.studentEmail||u.student_email||""})).filter(u=>u.name))}else{const x=f.split(/\r?\n/);if(x.length<2)throw new Error("CSV has empty or insufficient data");const p=x[0].split(",").map(S=>S.trim().toLowerCase()),u=p.findIndex(S=>S.includes("class name")||S.includes("班级名称")||S.includes("班级")||S.includes("classname")||S.includes("class_name")),P=p.findIndex(S=>S.includes("class desc")||S.includes("班级描述")||S.includes("描述")||S.includes("class_desc")),I=p.findIndex(S=>S.includes("student name")||S.includes("学生姓名")||S.includes("姓名")||S.includes("学生")||S.includes("studentname")||S.includes("student_name")),_=p.findIndex(S=>S.includes("student email")||S.includes("学生邮箱")||S.includes("邮箱")||S.includes("email")||S.includes("studentemail")||S.includes("student_email"));if(I===-1)throw new Error('CSV is missing column: "Student Name" (学生姓名/姓名/学生)');if(u!==-1){C=!0;const S={};for(let g=1;g<x.length;g++){const E=x[g].trim();if(!E)continue;const k=(E.match(/(".*?"|[^",]+)(?=\s*,|\s*$)/g)||E.split(",")).map(D=>D.replace(/^"|"$/g,"").trim()),z=k[u];if(!z)continue;const M=P!==-1&&k[P]||"",y=I!==-1&&k[I]||"",N=_!==-1&&k[_]||"";S[z]||(S[z]={name:z,description:M,students:[]}),y&&S[z].students.push({name:y,email:N})}b=Object.values(S)}else{C=!1;for(let S=1;S<x.length;S++){const g=x[S].trim();if(!g)continue;const O=(g.match(/(".*?"|[^",]+)(?=\s*,|\s*$)/g)||g.split(",")).map(M=>M.replace(/^"|"$/g,"").trim()),k=I!==-1&&O[I]||"",z=_!==-1&&O[_]||"";k&&v.push({name:k,email:z})}}}if(C){if(b.length===0)throw new Error("No valid class elements found inside file.");const x=await fetch("/api/classes/import",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({classes:b})});if(!x.ok){const u=await x.json();throw new Error(u.error||"Server importation failed")}const p=await x.json();await n(),await i(),a({success:!0,message:t==="zh"?`成功导入 ${p.imported.length} 个班级数据!`:`Successfully imported ${p.imported.length} classes data!`})}else{if(v.length===0)throw new Error("No valid student elements found inside file.");const x=await fetch("/api/students/import",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({students:v})});if(!x.ok){const u=await x.json();throw new Error(u.error||"Server student importation failed")}const p=await x.json();await i(),a({success:!0,message:t==="zh"?`成功导入 ${p.imported.filter(u=>u.new).length} 名新学者,匹配并更新了其中的 ${p.imported.filter(u=>!u.new).length} 名同学!`:`Successfully imported ${p.imported.filter(u=>u.new).length} new students and updated ${p.imported.filter(u=>!u.new).length} existing ones!`})}}catch(f){d(f)}},l.onerror=()=>{d(new Error("Failed to read file from disk."))},l.readAsText(s)})}function jd(s,e){return new Promise((t,n)=>{const i=new FileReader;i.onload=a=>{try{const d=a.target?.result;if(!d)throw new Error("Empty CSV file");const l=d.split(/\r?\n/);if(l.length<2)throw new Error(e==="zh"?"CSV 文件行数不足,请包含标题和至少一行数据。":"CSV is missing content or headers.");const h=l[0].split(",").map(C=>C.trim().toLowerCase()),f=h.findIndex(C=>C.includes("title")||C.includes("标题")||C.includes("课程")),b=h.findIndex(C=>C.includes("content")||C.includes("内容")||C.includes("正文"));if(f===-1||b===-1)throw new Error(e==="zh"?'CSV 缺少必要表头列:必须包含 "Title"(课程标题)和 "Content"(课程内容)。':'CSV must contain "Title" and "Content" headers.');const v=[];for(let C=1;C<l.length;C++){const x=l[C].trim();if(!x)continue;const u=(x.match(/(".*?"|[^",]+)(?=\s*,|\s*$)/g)||x.split(",")).map(_=>_.replace(/^"|"$/g,"").trim()),P=u[f],I=u[b];P&&I&&v.push({title:P,content:I})}if(v.length===0)throw new Error(e==="zh"?"未能从 CSV 解析出有效课程数据。":"No valid courses found in CSV.");t(v)}catch(d){n(d)}},i.onerror=()=>{n(new Error(e==="zh"?"无法读取选取的 CSV 文件!":"Failure to read the CSV!"))},i.readAsText(s)})}async function Id(s,e){const{lang:t,setImportProgress:n,fetchLessons:i}=e;let a=0;for(let d=0;d<s.length;d++){const l=s[d];try{const h=await fetch("/api/lessons",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:l.title,content:l.content})});if(h.ok)a++;else{const f=await h.json();console.warn(`Failed to import item ${d+1}:`,f)}}catch(h){console.warn(`Error importing item ${d+1}:`,h)}n(d+1)}return a>0?(await i(),{success:!0}):{success:!1,errorMsg:t==="zh"?"所有课程项导入均失败。请检查控制台或格式。":"Failed to import any of the courses. Please check your console or schema."}}function Ld(s){return"#/"+s}function rr(s){const e=s.replace(/^#/,"");return!e||e==="/"?null:e.replace(/^\//,"")}Hc();const ir="openlearnv2.agentProviderId";function Rd(){const s=K(c=>c.lang),e=K(c=>c.setLang),t=qn[s]??qn.zh,[n,i]=o.useState(!1),a=K(c=>c.liveClassSelectedClassId),d=K(c=>c.setLiveClassSelectedClassId),l=K(c=>c.liveClassIsActive),h=K(c=>c.setLiveClassIsActive),[f,b]=o.useState(0),[v,C]=o.useState([]),[x,p]=o.useState(new Map),u=pr(),[P,I]=o.useState([]),[_,S]=o.useState({}),[g,E]=o.useState([]),[O,k]=o.useState(0),[z,M]=o.useState(!1),[y,N]=o.useState(null),[D,A]=o.useState(!1),[B,j]=o.useState("system"),[m,L]=o.useState(null),[w,R]=o.useState([]),[F,Z]=o.useState(!1),[ae,G]=o.useState(!1),q=async()=>{try{Z(!0);const c=await fetch("/api/resources");if(c.ok){const T=await c.json();R(T)}}catch(c){console.warn("Error fetching library resources:",c)}finally{Z(!1)}};Ve.useEffect(()=>{D&&q()},[D]);const Q=K(c=>c.lessons),he=K(c=>c.setLessons),{lessonsSearchQuery:ce,setLessonsSearchQuery:Ce,lessonsSortOrder:We,setLessonsSortOrder:ze,filterEnrollment:se,setFilterEnrollment:Ke,filterHasContent:Et,setFilterHasContent:Pt,filterThisMonth:at,setFilterThisMonth:ct,copyingLessonId:V,setCopyingLessonId:U,filteredAndSortedLessons:J}=_d(Q),[le,Te]=o.useState([]),Y=K(c=>c.selectedLesson),fe=K(c=>c.setSelectedLesson),de=K(c=>c.elements),je=K(c=>c.setElements),[qe,Ee]=o.useState(!1),[Se,pe]=o.useState("idle"),[lt,dt]=o.useState(0),[Kt,Tt]=o.useState(0),[Yt,Me]=o.useState(""),[Ye,ut]=o.useState([]),[Xt,es]=o.useState(!1),[ts,ss]=o.useState(!1),[ns,rs]=o.useState("agent"),[is,os]=o.useState(!1),[kt,as]=o.useState([]),[cs,ls]=o.useState([]),[ht,ft]=o.useState(null),[Nt,re]=o.useState(""),Xe=K(c=>c.classes),ds=K(c=>c.setClasses),ke=K(c=>c.students),At=K(c=>c.setStudents),{computerLabs:us,fetchLabs:_t,todaySchedules:hs,fetchTodaySchedules:et,classSchedulesMap:fs,fetchClassSchedules:zt,scheduleAttendanceMap:ps,fetchScheduleAttendance:gs,expandedScheduleId:ms,setExpandedScheduleId:ys,newScheduleDate:bs,setNewScheduleDate:xs,newScheduleLessonId:ee,setNewScheduleLessonId:Ss}=wd(),[Ue,vs]=o.useState(null),ws=o.useRef(null),Cs=c=>{vs(c),ws.current=c},[jt,It]=o.useState({}),[Es,Ps]=o.useState(null),Lt=o.useRef(null),[pt,gt]=o.useState(null),Ts=c=>{const T=Tc[c];T&>({type:c,data:{...T.defaultData}})},ks=async c=>{pt&&await Lt.current?.addElementAtCenter(pt.type,c),gt(null)},ne=K(c=>c.session),Ge=K(c=>c.setSession),Rt=K(c=>c.siteInfo),Ot=K(c=>c.setSiteInfo),[ye,me]=o.useState("teacher"),[Ns,As]=o.useState(!0),[_s,tt]=o.useState(!0),[zs,He]=o.useState("normal");o.useEffect(()=>{if(!ne)return;const c=async()=>{try{const $=await fetch("/api/db-status");if($.ok){const W=await $.json().catch(()=>({}));W.status==="warning"||W.warning?He("warning"):He("normal"),tt(!0)}else $.status===429||$.status===503?(He("warning"),tt(!0)):(He("error"),tt(!1))}catch{He("error"),tt(!1)}};c();const T=setInterval(c,5e3);return()=>clearInterval(T)},[ne]),o.useEffect(()=>{(async()=>{try{const T=await fetch("/api/auth/session");if(T.ok){const $=await T.json();$.session&&(Ge($.session),me($.session.role),$.session.role==="student"&&$.session.studentId&&(Mt($.session.studentId),Ze()))}}catch(T){console.warn("Session check failed",T)}finally{As(!1)}})()},[]),o.useEffect(()=>{(async()=>{try{const T=await fetch("/api/site-settings");if(T.ok){const $=await T.json();Ot({siteName:$.siteName||"",slogan:$.slogan||"",logoUrl:$.logoUrl||null})}}catch(T){console.warn("Failed to fetch site settings:",T)}})()},[]);const De=K(c=>c.teacherTab),be=K(c=>c.setTeacherTab);o.useEffect(()=>{const c=()=>{const $=rr(window.location.hash);$&&$!==ge.getState().teacherTab&&be($)};window.addEventListener("hashchange",c);const T=rr(window.location.hash);return T&&be(T),()=>window.removeEventListener("hashchange",c)},[be]),o.useEffect(()=>{const c=Ld(De);window.location.hash!==c&&(window.location.hash=c)},[De,be]);const[js,st]=o.useState(!1),[Is,Ls]=o.useState(!1),[mt,zr]=o.useState(!1);o.useEffect(()=>{ne?.subRole==="administrator"&&localStorage.getItem("edu_os_tour_completed")!=="true"&&st(!0)},[ne]);const jr=async c=>{await nt(),await Ie(),await et().catch(()=>{}),d(c.classId),fe(c.lessonId),h(!0),ve(s==="zh"?"示范课堂准备就绪":"Demo Classroom Ready",s==="zh"?"示范班级与课件已加载,已自动开启授课状态!":"Demo class & courseware loaded. Live class session is now active!","success")};o.useEffect(()=>{De==="live_class"&&i(!0)},[De]);const{timelineSegments:Ir,activeSegmentId:Rs,setActiveSegmentId:Os,draggedSegmentIdx:Lr,setDraggedSegmentIdx:Rr,editorSaveStatus:Or,setEditorSaveStatus:Mr,editorLastSavedTime:Dr,setEditorLastSavedTime:$r,editorPanelsExpanded:Fr,setEditorPanelsExpanded:Br,saveTimeline:Vr}=Cd({selectedLesson:Y,lessons:Q,setLessons:he}),[ie,Mt]=o.useState(null),[Ms,Wr]=o.useState(null),ve=(c,T,$="info")=>{const W=Math.random().toString(36).substring(2,9);ge.getState().addToast({id:W,title:c,message:T,type:$}),setTimeout(()=>{ge.getState().removeToast(W)},6e3)},Ie=async()=>{try{const c=await fetch("/api/lessons");if(c.ok){const T=await c.json();he(T),!ge.getState().selectedLesson&&T.length>0&&fe(T[0].id)}}catch(c){console.warn("Failed to fetch lessons",c)}},gn=o.useRef(()=>{}),mn=xd({lang:s,addToast:ve,fetchLessons:Ie,setSelectedLesson:fe,setTeacherTab:be}),{isCourseWizardOpen:Wd,setIsCourseWizardOpen:qr,wizardStep:qd,setWizardStep:Ur,wizardCourseTitle:Ud,setWizardCourseTitle:Gd,wizardCourseCategory:Hd,setWizardCourseCategory:Qd,wizardCourseDescription:Jd,setWizardCourseDescription:Zd,wizardCourseContent:Kd,setWizardCourseContent:Yd,wizardCourseTimeline:Xd,setWizardCourseTimeline:eu,wizardIsSubmitting:tu,handleDeployWizardCourse:su}=mn,{plugins:$e,fetchPlugins:Gr,aiProviders:Qe,fetchAIProviders:Hr,testingProviderId:Qr,storeTab:Jr,setStoreTab:Zr,pluginCode:Kr,setPluginCode:Yr,installingPlugin:Xr,events:ei,fetchEvents:ti,approvals:si,fetchApprovals:ni,scoreOverrides:ri,setScoreOverrides:ii,handleInstallPlugin:oi,handleZipPluginUpload:ai,handleTogglePlugin:ci,handleDeletePlugin:li,handleApprove:di,handleReject:ui}=bd({host:u,lang:s,addToast:ve,setChatLog:c=>gn.current(c),setTeacherTab:be,fetchLessons:Ie}),[Le,yn]=o.useState(()=>typeof window>"u"?"system":window.localStorage.getItem(ir)||"system"),Ds=Le==="system"||Qe.some(c=>c.id===Le)?Le:"system",hi=Qe.find(c=>c.id===Ds)||null,[yt,Je]=o.useState("dashboard"),[fi,pi]=o.useState("whiteboard"),[gi,mi]=o.useState(null),[Fe,$s]=o.useState(null),[yi,bn]=o.useState(!1),[bi,xn]=o.useState(null),[xi,Sn]=o.useState("whiteboard"),[Si,vi]=o.useState("none"),[wi,Ci]=o.useState("none"),[Ei,vn]=o.useState(!0);o.useEffect(()=>{yt!=="lesson"&&vn(!0)},[yt]);const wn=Sd(),{isQuizGeneratorOpen:nu,setIsQuizGeneratorOpen:Pi,quizGeneratorClassId:ru,setQuizGeneratorClassId:Ti,quizGenMode:iu,setQuizGenMode:ki,quizGenSelectedLessonId:ou,setQuizGenSelectedLessonId:Ni,quizGenTopic:au,setQuizGenTopic:Ai,isGeneratingSuggestions:cu,setIsGeneratingSuggestions:lu,suggestedObjectives:du,setSuggestedObjectives:_i,suggestedQuestions:uu,setSuggestedQuestions:zi,savingQuiz:hu,setSavingQuiz:fu,quizStudentAnswers:ji,setQuizStudentAnswers:Cn,quizGenTimeLimit:pu,setQuizGenTimeLimit:gu,quizStudentAnswersRef:Ii,subAssignmentTab:Li,setSubAssignmentTab:En}=wn,[Ri,Oi]=o.useState(""),[Mi,Di]=o.useState("all"),[$i,Fi]=o.useState("grid"),[Bi,Vi]=o.useState({}),[Wi,qi]=o.useState({}),[Ui,Gi]=o.useState({}),Pn=Ed(ye,Ms,s),{studentNotifications:Hi,unreadNotifications:Qi,readNotifications:Tn,setReadNotifications:Dt,selectedNotificationForModal:Ji,setSelectedNotificationForModal:Zi,isNotificationsOpen:Ki,setIsNotificationsOpen:Yi}=Pn;o.useEffect(()=>{ie&&fetch(`/api/students/${ie}/read_notifications`).then(c=>c.ok?c.json():[]).then(c=>{Dt(new Set(c))}).catch(c=>{console.warn("Failed to load read notifications from DB",c),Dt(new Set)})},[ie]);const Xi=o.useRef(null),eo=c=>{Ps(c),Xi.current=c},[to,so]=o.useState({}),[no,ro]=o.useState({}),[mu,yu]=o.useState({}),[bu,xu]=o.useState({}),[io,Su]=o.useState(null),[oo,ao]=o.useState("dueDate"),[vu,wu]=o.useState(null),[co,lo]=o.useState({}),[uo,kn]=o.useState(!1),[ho,Nn]=o.useState(!1),[fo,Fs]=o.useState(null),[po,Bs]=o.useState(null),[Vs,go]=o.useState(null),mo=o.useRef(null),An=c=>{go(c),mo.current=c};o.useEffect(()=>{typeof window<"u"&&window.localStorage.setItem(ir,Le)},[Le]),o.useEffect(()=>{Le!=="system"&&Qe.length>0&&!Qe.some(c=>c.id===Le)&&yn("system")},[Qe,Le]);const yo=async(c,T,$)=>{try{if((await fetch(`/api/classes/${c}/schedules`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({lessonId:T,scheduledDate:$})})).ok)return await zt(c),!0}catch(W){console.error("Quick schedule class failed",W)}return!1},bo=async(c,T,$)=>{try{const W=T||$||"Assignment",xe=await fetch(`/api/classes/${c}/assignments/generate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({topic:W})});if(xe.ok){const Re=await xe.json().catch(()=>({}));return await bt(c),Re.id||"assignment-created"}}catch(W){console.error("Quick generate assignment failed",W)}return null},xo=async(c,T)=>{try{const $=await fetch("/api/lessons",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:c,content:T})});if($.ok){const W=await $.json().catch(()=>({}));return await Ie(),W.id||"lesson-created"}}catch($){console.error("Quick create lesson failed",$)}return""},So=()=>{nr("class",s)},vo=async c=>{if(c){if(!c.name.toLowerCase().endsWith(".csv")){pe("error"),Me(s==="zh"?"只支持包含 .csv 后缀名的文件!":"Only files ending in .csv are supported!");return}pe("parsing"),Me("");try{const T=await jd(c,s);ut(T),pe("idle")}catch(T){pe("error"),Me(T.message||String(T))}}},wo=async()=>{if(Ye.length===0)return;pe("importing"),dt(0),Tt(Ye.length);const c=await Id(Ye,{lang:s,setImportProgress:dt,fetchLessons:Ie});c.success?pe("success"):(pe("error"),Me(c.errorMsg||""))},Co=async c=>{const T=await fetch(`/api/lessons/${c}`,{method:"DELETE"});if(!T.ok){const $=await T.json().catch(()=>({}));throw new Error($.error||"Failed to delete course")}await Ie(),Y===c&&fe(null),ve(s==="zh"?"课程已删除":"Course Deleted",s==="zh"?"课程及其所有关联数据已被删除。":"The course and all associated data have been deleted.","success")},Eo=async c=>{U(c);try{const T=await fetch(`/api/lessons/${c}/clone`,{method:"POST"});if(!T.ok){const $=await T.json().catch(()=>({}));throw new Error($.error||"Failed to copy course")}await Ie(),ve(s==="zh"?"复制成功":"Course Copied",s==="zh"?"课程已成功复制。":"Course has been copied successfully.","success")}catch(T){ve(s==="zh"?"复制失败":"Copy Failed",T.message||(s==="zh"?"复制课程时发生错误。":"An error occurred while copying the course."),"error")}finally{U(null)}},_n=async()=>{try{const c=await fetch("/api/commands/registered");if(!c.ok)return;const T=c.headers.get("content-type");if(T&&T.includes("application/json")){const $=await c.json();Array.isArray($)&&Te($)}}catch(c){console.warn("Failed to fetch registered commands",c)}},Po=async c=>{try{const T=await fetch(`/api/vfs${c?`?parentId=${c}`:""}`);if(T.ok){const $=await T.json();as($)}}catch(T){console.warn("Failed to fetch VFS nodes",T)}},To=async()=>{try{const c=await fetch("/api/processes");c.ok&&ls(await c.json())}catch{}},nt=async()=>{try{const c=await fetch("/api/classes");c.ok&&ds(await c.json())}catch{}},Ze=async()=>{try{const c=await fetch("/api/students");c.ok&&At(await c.json())}catch{}},rt=async c=>{try{const T=await fetch(`/api/classes/${c}/students`);if(T.ok){const $=await T.json();It(W=>({...W,[c]:$}))}}catch{}},Ws=async c=>{try{const T=await fetch(`/api/classes/${c}/progress`);if(T.ok){const $=await T.json();ro(W=>({...W,[c]:$}))}}catch{}},[qs,ko]=o.useState({}),bt=async c=>{try{const T=await fetch(`/api/classes/${c}/dashboard`);if(T.ok){const $=await T.json();ko(W=>({...W,[c]:$}))}}catch{}},No=Ad({lang:s,classes:Xe,classStudentsMap:jt,classDashboardMap:qs,fetchClassStudents:rt,fetchClassDashboard:bt,fetchClassProgress:Ws}),{isExportWeightModalOpen:Ao,setIsExportWeightModalOpen:zn,exportClassId:_o,setExportClassId:zo,exportClassName:jo,setExportClassName:Io,quizzesWeight:Lo,setQuizzesWeight:jn,assignmentsWeight:Ro,setAssignmentsWeight:In,customCategoryOverrides:Oo,setCustomCategoryOverrides:Ln,exportDropdownOpen:Mo,setExportDropdownOpen:Do,exportTooltipOpen:$o,setExportTooltipOpen:Fo,loadingExportClassId:Bo,isExportingAllCombined:Vo,isGeneratingPDFReport:Wo,handleQuizzesWeightChange:qo,handleAssignmentsWeightChange:Uo,csvPreviewData:Go,triggerExportForClass:Ho,handleExportGrades:Qo,handleGeneratePDFReport:Jo,handleExportAllClassesCombined:Rn,get30DayAverageWarning:Zo}=No,On=vd({lang:s,classes:Xe,expandedClassId:Ue,fetchClasses:nt,fetchClassStudents:rt,handleExportAllClassesCombined:Rn}),{batchMode:Ko,setBatchMode:Yo,selectedClassIds:Xo,setSelectedClassIds:ea,selectedStudentIds:ta,setSelectedStudentIds:sa,batchPicker:Cu,setBatchPicker:Eu,batchPickerLesson:Pu,setBatchPickerLesson:Tu,batchPickerDate:ku,setBatchPickerDate:Nu,batchPickerTargetClass:Au,setBatchPickerTargetClass:_u,toggleClassSelection:na,toggleSelectAllClasses:ra,toggleStudentSelection:ia,toggleSelectAllStudents:oa,handleBatchDeleteClasses:aa,handleBatchExportClasses:ca,handleBatchSetPasscode:la,handleBatchScheduleClasses:da,handleBatchDeleteStudents:ua,handleBatchResetPassword:ha,handleBatchTransferStudents:fa,handleBatchSetLockedLesson:pa,confirmBatchPicker:zu}=On,Us=async c=>{try{const T=await fetch(`/api/students/${c}/dashboard`);if(T.ok){const $=await T.json();Wr($),$.profile&&$.profile.locked_lesson_id&&(fe($.profile.locked_lesson_id),Je("lesson"))}}catch{}},ga=async(c=!1)=>{if(!Fe)return;const $=Fe?.content&&Fe.content.startsWith('{"quizType":"mcq_learning_objectives"')?JSON.stringify(Ii.current):"Submitted via Whiteboard";try{(await fetch(`/api/assignments/${Fe.id}/submissions`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({studentId:ie,content:$})})).ok&&(c&&alert("Time is up! Your assessment was successfully submitted automatically."),await Us(ie),Je("dashboard"),$s(null))}catch(W){console.error(W)}};o.useEffect(()=>{if(ne&&ye==="student"&&ie){Us(ie);const c=ke.find(T=>T.id===ie);c&&c.locked_lesson_id&&(fe(c.locked_lesson_id),Je("lesson"))}},[ne,ye,ie,ke]);const ma=o.useRef(ye),ya=o.useRef(ie),ba=o.useRef(s),xa=o.useRef(ke),Sa=o.useRef(ve),$t=o.useRef(new Set);o.useRef(new Set),o.useEffect(()=>{ma.current=ye},[ye]),o.useEffect(()=>{ya.current=ie},[ie]),o.useEffect(()=>{ba.current=s},[s]),o.useEffect(()=>{xa.current=ke},[ke]),o.useEffect(()=>{Sa.current=ve},[ve]),o.useEffect(()=>{if(!u.isInitialized()||$e.length===0)return;const c=oe.getState(),T=$e.filter(W=>W.status==="active");for(const W of T){if(!W.has_frontend||$t.current.has(W.id))continue;const xe=c.activePlugins.find(Oe=>Oe.id===W.id),Re=!!(xe&&W.version&&xe.version!==W.version);if(!(!xe||Re||xe.state!==X.ACTIVE&&xe.state!==X.ACTIVATING))continue;$t.current.add(W.id);const $n=()=>{if(!c.activePlugins.find(Oe=>Oe.id===W.id))c.addPlugin({id:W.id,name:W.name,version:W.version,state:X.INSTALLED,executionMode:"inline"});else if(Re)try{oe.setState(Oe=>({activePlugins:Oe.activePlugins.map(St=>St.id===W.id?{...St,version:W.version,name:W.name}:St)}))}catch{}try{const Oe=JSON.parse(W.manifest);u.activateRemotePlugin(W.id,Oe).catch(St=>{console.error(`[App] Failed to activate remote plugin "${W.name}":`,St)}).finally(()=>{$t.current.delete(W.id)})}catch(Oe){$t.current.delete(W.id),console.error(`[App] Failed to parse manifest for plugin "${W.name}":`,Oe)}};xe&&xe.state===X.ACTIVE&&Re?u.deactivatePlugin(W.id).catch(()=>{}).finally($n):$n()}const $=$e.filter(W=>W.status!=="active");for(const W of $){if(!W.has_frontend)continue;const xe=c.activePlugins.find(Re=>Re.id===W.id);xe&&xe.state===X.ACTIVE&&u.deactivatePlugin(W.id).catch(Re=>{console.error(`[App] Failed to deactivate remote plugin "${W.name}":`,Re)})}},[$e,u]),Ve.useEffect(()=>{if(!u.isInitialized()||$e.length===0)return;const c=oe.getState();for(const T of $e)T.status==="active"&&(c.dashboardVisibility.has(T.id)||c.setDashboardVisibility(T.id,!0))},[$e,u]);const va=async c=>{if(ye==="student"&&ie&&Y)try{await fetch(`/api/students/${ie}/progress`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({lessonId:Y,completed:c===100,progressPercent:c})})}catch(T){console.error("Failed to update student progress:",T)}},wa=async(c,T)=>{try{const $=await fetch(`/api/classes/${c}/lessons/${T}/progress`);$.ok&&E(await $.json())}catch{}};o.useEffect(()=>{a&&Y?wa(a,Y):E([])},[a,Y]),o.useEffect(()=>{a&&rt(a)},[a]);const Ca=async c=>{try{const T=await fetch(`/api/students/${c}/progress`);if(T.ok){const $=await T.json();so(W=>({...W,[c]:$}))}}catch{}},Mn=async c=>{try{const T=await fetch(`/api/processes/${c}/logs`);if(T.ok){const $=await T.json();re($.logs||""),ft(c)}}catch{}},xt=async c=>{const $=await(await fetch(`/api/lessons/${c}/whiteboard`)).json();je($)},Ea=o.useRef(null);o.useRef(null);const Pa=o.useRef(null);o.useEffect(()=>{Ea.current=Y},[Y]),o.useEffect(()=>{Pa.current=Fe},[Fe]),gl(ne);const{chatLog:Ta,setChatLog:ka,input:Na,setInput:Aa,loading:_a,chatAttachments:za,setChatAttachments:ja,handleChatFileChange:Ia,handleChatDrop:La,handleSend:Ra,handleClearAgentMemory:Oa}=yl({lang:s,t,selectedLesson:Y,effectiveAgentProviderId:Ds,expandedClassId:Ue,fetchLessons:Ie,fetchClasses:nt,fetchStudents:Ze,fetchClassStudents:rt,fetchClassProgress:Ws,fetchClassDashboard:bt,fetchElements:xt});gn.current=ka,ml({session:ne,showProcessLogs:ht,activeStudentId:ie,currentVfsParent:Vs,selectedLesson:Y,selectedAssignment:Fe,expandedClassId:Ue,fetchLessons:Ie,fetchPlugins:Gr,fetchRegisteredCommands:_n,fetchEvents:ti,fetchApprovals:ni,fetchProcesses:To,fetchClasses:nt,fetchTodaySchedules:et,fetchStudents:Ze,fetchLabs:_t,fetchVfs:Po,fetchProcessLogs:Mn,fetchClassStudents:rt,fetchElements:xt});const{socketRef:Ma}=md({session:ne,host:u,activeRole:ye,activeStudentId:ie,selectedLesson:Y,activeSegmentId:Rs,studentViewStatus:yt,lang:s,students:ke,addToast:ve,setOnlineStudentIds:I,setActiveStudentLessons:S,setLessons:he,setActiveSegmentId:Os,setLiveClassStudentProgress:E,setLiveClassAcknowledgedMap:p,setLiveClassFeed:C,setSelectedLesson:fe,setStudentViewStatus:Je,setLocalProgressPercent:k,fetchStudentDashboard:Us,fetchStudents:Ze,fetchElements:xt}),Da=c=>{nr(c,s)},$a=async c=>{Nn(!0),Fs(null),Bs(null);try{const T=await zd(c,{lang:s,fetchClasses:nt,fetchStudents:Ze});Bs(T.message)}catch(T){Fs(T.message||String(T))}finally{Nn(!1)}},Fa=()=>{e(s==="zh"?"en":"zh")},Ba=o.useCallback(c=>{Ge(c),c.role==="teacher"?(me("teacher"),be("dashboard")):(me("student"),Mt(c.studentId),Ze())},[]),Dn=async()=>{try{await fetch("/api/auth/logout",{method:"POST"})}catch(c){console.error("Logout failed",c)}Ge(null)},[Va,Gs]=o.useState(!1);return Ns?r.jsxs("div",{className:"min-h-screen bg-slate-900 flex flex-col items-center justify-center p-4 relative overflow-hidden font-sans",children:[r.jsx(ln,{size:48,className:"text-indigo-500 animate-spin"}),r.jsx("span",{className:"text-white text-sm mt-4 font-semibold tracking-wide",children:s==="zh"?"正在连接安全核心数据库...":"Connecting Secure OS Core Database..."})]}):ne?r.jsx(r.Fragment,{children:r.jsxs("div",{className:"flex h-screen bg-gray-50 text-gray-900 font-sans",children:[r.jsxs("div",{className:"flex-1 flex flex-col bg-gray-50 h-full overflow-hidden",children:[r.jsx(Cc,{activeRole:ye,lang:s,teacherTab:De,studentViewStatus:yt,session:ne,activeStudentId:ie,students:ke,studentDashboardData:Ms,isNotificationsOpen:Ki,studentNotifications:Hi,unreadNotifications:Qi,readNotifications:Tn,selectedNotificationForModal:Ji,dbConnected:_s,dbStatus:zs,siteInfo:Rt,setActiveStudentId:Mt,setReadNotifications:Dt,setIsSystemResourceLibraryOpen:A,setProfileOpen:Gs,setTeacherTab:be,setStudentViewStatus:Je,setIsNotificationsOpen:Yi,setSelectedNotificationForModal:Zi,handleLogout:Dn,toggleLanguage:Fa}),r.jsx(Ec,{open:Va,session:ne,lang:s,onClose:()=>Gs(!1),onSaved:c=>{ne&&Ge({...ne,name:c}),Gs(!1)},onAvatar:c=>{ne&&Ge({...ne,avatar:c??void 0})}}),r.jsx(Kc,{students:ke,activeStudentId:ie,studentViewStatus:yt,studentDashboardData:Ms,readNotifications:Tn,setReadNotifications:Dt,addToast:ve,lang:s,setSelectedLesson:fe,setStudentViewStatus:Je,setSelectedAssignment:$s,setQuizStudentAnswers:Cn,setSubAssignmentTab:En,lessons:Q,selectedLesson:Y,studentFullscreenPanel:wi,setStudentFullscreenPanel:Ci,timelineSegments:Ir,activeSegmentId:Rs,setActiveSegmentId:Os,localProgressPercent:O,setLocalProgressPercent:k,updateStudentProgress:va,isStudentLessonContentCollapsed:Ei,setIsStudentLessonContentCollapsed:vn,studentLessonTab:fi,setStudentLessonTab:pi,elements:de,activeRole:ye,fetchElements:xt,currentVfsParent:Vs,setCurrentVfsParent:An,vfsNodes:kt,studentSelectedCourseware:gi,setStudentSelectedCourseware:mi,selectedAssignment:Fe,quizStudentAnswers:ji,submitQuizAssignment:ga,subAssignmentTab:Li,mainNavCollapsed:n,setMainNavCollapsed:i,teacherTab:De,setTeacherTab:be,session:ne,todaySchedules:hs,t,classes:Xe,approvals:si,processes:cs,isApprovalsCollapsed:Is,setIsApprovalsCollapsed:Ls,isProcessesCollapsed:mt,setIsProcessesCollapsed:zr,scoreOverrides:ri,setScoreOverrides:ii,handleApprove:di,handleReject:ui,showLogs:is,setShowLogs:os,processLogsContent:Nt,showProcessLogs:ht,fetchProcessLogs:Mn,setShowProcessLogs:ft,handleQuickScheduleClass:yo,handleQuickGenerateAssignment:bo,handleQuickCreateLesson:xo,setActiveRole:me,editorSaveStatus:Or,setEditorSaveStatus:Mr,editorLastSavedTime:Dr,setEditorLastSavedTime:$r,setIsLessonPreviewVisible:bn,setPreviewLessonTab:Sn,setPreviewSelectedCourseware:xn,handlePaletteActivate:Ts,draggedSegmentIdx:Lr,setDraggedSegmentIdx:Rr,saveTimeline:Vr,editorPanelsExpanded:Fr,setEditorPanelsExpanded:Br,whiteboardRef:Lt,paletteEdit:pt,handlePaletteConfirm:ks,setPaletteEdit:gt,plugins:$e,liveClassSelectedClassId:a,setLiveClassSelectedClassId:d,liveClassIsActive:l,setLiveClassIsActive:h,liveClassTimeRemaining:f,setLiveClassTimeRemaining:b,liveClassFeed:v,setLiveClassFeed:C,liveClassAcknowledgedMap:x,setLiveClassAcknowledgedMap:p,onlineStudentIds:P,activeStudentLessons:_,liveClassStudentProgress:g,storeTab:Jr,setStoreTab:Zr,pluginCode:Kr,setPluginCode:Yr,installingPlugin:Xr,onInstall:oi,onZipUpload:ai,onToggle:ci,onDelete:li,lessonsSearchQuery:ce,setLessonsSearchQuery:Ce,lessonsSortOrder:We,setLessonsSortOrder:ze,filteredLessons:J,onOpenImportLessons:()=>{pe("idle"),dt(0),Tt(0),Me(""),ut([]),Ee(!0)},onOpenCourseWizard:()=>{Ur(1),qr(!0)},onViewCourse:c=>{be("lesson_editor"),fe(c)},onDeleteCourse:Co,onCopyCourse:Eo,filterEnrollment:se,setFilterEnrollment:Ke,filterHasContent:Et,setFilterHasContent:Pt,filterThisMonth:at,setFilterThisMonth:ct,copyingLessonId:V,onSchedulesUpdated:et,onLogout:Dn,aiProviders:Qe,testingProviderId:Qr,onAIProvidersChanged:Hr,onTriggerTour:()=>st(!0),siteInfo:Rt,onSiteInfoChanged:Ot,computerLabs:us,onRefresh:_t,registeredCommands:le,fetchRegisteredCommands:_n,batchMode:Ko,selectedClassIds:Xo,setSelectedClassIds:ea,setSelectedStudentIds:sa,setBatchMode:Yo,expandedClassId:Ue,setExpandedClassId:Cs,exportTooltipOpen:$o,setExportTooltipOpen:Fo,exportDropdownOpen:Mo,setExportDropdownOpen:Do,isExportingAllCombined:Vo,loadingExportClassId:Bo,classStudentsMap:jt,setClassStudentsMap:It,expandedStudentId:Es,setExpandedStudentId:eo,selectedStudentIds:ta,rosterViewMode:$i,setRosterViewMode:Fi,rosterSearchQuery:Ri,setRosterSearchQuery:Oi,rosterTagFilter:Mi,setRosterTagFilter:Di,toggleSelectAllStudents:oa,handleBatchDeleteStudents:ua,handleBatchResetPassword:ha,handleBatchTransferStudents:fa,handleBatchSetLockedLesson:pa,toggleStudentSelection:ia,get30DayAverageWarning:Zo,studentProgressMap:to,studentActiveTabs:Ui,setStudentActiveTabs:Gi,setStudents:At,fetchClassStudents:rt,fetchStudents:Ze,parseCSV:Sc,setImportError:Fs,setImportSuccess:Bs,setShowImportModal:kn,fetchClasses:nt,classSubmissionFilters:Bi,setClassSubmissionFilters:Vi,classActiveTabs:Wi,setClassActiveTabs:qi,classProgressMap:no,classSchedulesMap:fs,classDashboardMap:qs,assignmentSortOrder:oo,setAssignmentSortOrder:ao,isGeneratingPDFReport:Wo,handleGeneratePDFReport:Jo,setExportClassId:zo,setExportClassName:Io,setQuizzesWeight:jn,setAssignmentsWeight:In,setCustomCategoryOverrides:Ln,setIsExportWeightModalOpen:zn,isGeneratingAssignment:io,setQuizGeneratorClassId:Ti,setQuizGenMode:ki,setQuizGenSelectedLessonId:Ni,setQuizGenTopic:Ai,setSuggestedObjectives:_i,setSuggestedQuestions:zi,setIsQuizGeneratorOpen:Pi,setActiveStudentId:Mt,isGrading:co,setIsGrading:lo,fetchClassDashboard:bt,newScheduleDate:bs,setNewScheduleDate:xs,newScheduleLessonId:ee,setNewScheduleLessonId:Ss,expandedScheduleId:ms,setExpandedScheduleId:ys,fetchScheduleAttendance:gs,scheduleAttendanceMap:ps,toggleSelectAllClasses:ra,handleBatchDeleteClasses:aa,handleBatchExportClasses:ca,handleBatchSetPasscode:la,handleBatchScheduleClasses:da,handleExportAllClassesCombined:Rn,triggerExportForClass:Ho,fetchClassProgress:Ws,fetchClassSchedules:zt,fetchStudentProgress:Ca,toggleClassSelection:na,socketRef:Ma,setShowCoursewareHub:G,fetchTodaySchedules:et})]}),r.jsx(Xc,{showRightSidebar:ts,setShowRightSidebar:ss,rightSidebarTab:ns,setRightSidebarTab:rs,effectiveAgentProviderId:Ds,agentProviderId:Le,setAgentProviderId:yn,aiProviders:Qe,selectedAgentProvider:hi,chatLog:Ta,loading:_a,input:Na,setInput:Aa,handleSend:Ra,chatAttachments:za,setChatAttachments:ja,handleChatFileChange:Ia,handleChatDrop:La,onClearAgentMemory:Oa,events:ei,lang:s,t}),r.jsx(fl,{lang:s,t,courseWizard:mn,quizGenerator:wn,classBatch:On,studentNotificationsHook:Pn,showImportModal:uo,setShowImportModal:kn,handleImportFile:$a,importError:fo,importSuccess:po,isImporting:ho,downloadCSVTemplate:Da,addToast:ve,generateTemplateContent:Mc,isImportLessonsOpen:qe,setIsImportLessonsOpen:Ee,importStatus:Se,setIsDraggingImport:es,handleCSVFileChange:vo,downloadCsvTemplate:So,isDraggingImport:Xt,previewImportData:Ye,setPreviewImportData:ut,setImportStatus:pe,importProgress:lt,importProgressTotal:Kt,importErrorMsg:Yt,setImportErrorMsg:Me,handleCSVImportSubmit:wo,lessons:Q,fetchClassDashboard:bt,isLessonPreviewVisible:yi,setIsLessonPreviewVisible:bn,selectedLesson:Y,previewFullscreenPanel:Si,setPreviewFullscreenPanel:vi,previewLessonTab:xi,setPreviewLessonTab:Sn,activeRole:ye,elements:de,activeSegmentId:Rs,setActiveSegmentId:Os,fetchElements:xt,currentVfsParent:Vs,setCurrentVfsParent:An,vfsNodes:kt,previewSelectedCourseware:bi,setPreviewSelectedCourseware:xn,showProcessLogs:ht,setShowProcessLogs:ft,processLogsContent:Nt,isCloudDriveOpen:z,setIsCloudDriveOpen:M,cloudDrivePreviewNode:y,setCloudDrivePreviewNode:N,isSystemResourceLibraryOpen:D,setIsSystemResourceLibraryOpen:A,systemResourceTab:B,setSystemResourceTab:j,selectedLibraryResourceId:m,setSelectedLibraryResourceId:L,loadingLibraryResources:F,libraryResources:w,fetchLibraryResources:q,classes:Xe,expandedClassId:Ue,isExportWeightModalOpen:Ao,setIsExportWeightModalOpen:zn,quizzesWeight:Lo,setQuizzesWeight:jn,assignmentsWeight:Ro,setAssignmentsWeight:In,handleQuizzesWeightChange:qo,handleAssignmentsWeightChange:Uo,customCategoryOverrides:Oo,setCustomCategoryOverrides:Ln,classDashboardMap:qs,exportClassId:_o,exportClassName:jo,csvPreviewData:Go,handleExportGrades:Qo,setSelectedAssignment:$s,setStudentViewStatus:Je,setQuizStudentAnswers:Cn,setSubAssignmentTab:En,isTourOpen:js,setIsTourOpen:st,handleSeedSuccess:jr,setTeacherTab:be,showCoursewareHub:ae,setShowCoursewareHub:G}),r.jsx(Yc,{})]})}):r.jsx(vc,{onLoginSuccess:Ba,lang:s})}class Od{constructor(){this.services=new Map}async register(e,t){if(this.services.has(e))throw new Error(`Service already registered: ${e}`);this.services.set(e,t)}async resolve(e){const t=this.services.get(e);if(!t)throw new Error(`No provider registered for token: ${e}`);return t}async unregister(e){this.services.delete(e)}has(e){return this.services.has(e)}list(){return Array.from(this.services.entries()).map(([e,t])=>({name:e,instance:t}))}}const Md=/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[0-9a-f]{4}-[0-9a-f]{12}\./i;function Dd(s,e){const t=e+".";return s.startsWith(t)||Md.test(s)?s:t+s}const $d=["@openlearn/frontend:IFrontendAPI","@openlearn/frontend:ISocketService","@openlearn/frontend:IUIService","@openlearn/frontend:IStorageService","@openlearn/frontend:ISemesterGradeService"];class Fd{constructor(e){this.registry=null,this.initialized=!1,this.sourceCodes=new Map,this.pluginModules=new Map,this.workerManager=null,this.moduleLoader=e?.moduleLoader??this.defaultModuleLoader}setWorkerManager(e){this.workerManager=e}async initialize(e,t,n,i){const a=new Od;await a.register(Qn,e),await a.register(Jn,t),await a.register(Zn,n),await a.register(Kn,i),await a.register(Qc,new Bd(e)),this.registry=a,this.initialized=!0,oe.getState().initialize(a)}getRegistry(){return this.registry}isInitialized(){return this.initialized}async installPlugin(e,t){this.sourceCodes.set(e.id,t),oe.getState().addPlugin({id:e.id,name:e.name,version:e.version,state:X.INSTALLED,executionMode:"inline"})}async activateRemotePlugin(e,t){const n=oe.getState(),i=n.activePlugins.find(a=>a.id===e);if(!(i&&(i.state===X.ACTIVE||i.state===X.ACTIVATING))){n.updatePluginState(e,X.ACTIVATING);try{const a=`/plugins/${e}/frontend.js`,d=await fetch(a);if(!d.ok)throw new Error(`Failed to fetch frontend.js for plugin "${e}": HTTP ${d.status}`);let l=await d.text();window.HostSharedDeps&&(l=l.replace(/import\s+(\w+)\s+from\s+['"]react['"];?/g,"const $1 = window.HostSharedDeps.React;").replace(/import\s+\*\s+as\s+(\w+)\s+from\s+['"]react['"];?/g,"const $1 = window.HostSharedDeps.React;").replace(/import\s+\{\s*([^}]+)\s*\}\s+from\s+['"]react['"];?/g,(x,p)=>`const { ${p} } = window.HostSharedDeps.React;`).replace(/import\s+\{\s*([^}]+)\s*\}\s+from\s+['"]lucide-react['"];?/g,(x,p)=>`const { ${p} } = window.HostSharedDeps.LucideReact;`).replace(/import\s+\{\s*([^}]+)\s*\}\s+from\s+['"]recharts['"];?/g,(x,p)=>`const { ${p} } = window.HostSharedDeps.Recharts;`));const h=new Blob([l],{type:"text/javascript"}),f=URL.createObjectURL(h);let b;try{b=await import(f)}finally{URL.revokeObjectURL(f)}const v=b.default??b;if(typeof v.activate!="function")throw new Error("Invalid remote frontend plugin: missing activate function");const C=await this.buildContext(e,t);await Promise.race([v.activate(C),new Promise((x,p)=>setTimeout(()=>p(new Error("Activation timeout (5000ms)")),5e3))]),this.pluginModules.set(e,{manifest:t,activate:v.activate,deactivate:typeof v.deactivate=="function"?v.deactivate:void 0}),n.updatePluginState(e,X.ACTIVE)}catch(a){throw console.error(`[FrontendPluginHost] Failed to activate remote plugin "${e}":`,a),n.updatePluginState(e,X.ERROR),n.unregisterPluginExtensionPoints(e),a}}}async activatePlugin(e){const t=oe.getState(),n=t.activePlugins.find(i=>i.id===e);if(!n)throw new Error(`Plugin not found: ${e}`);if(n.executionMode==="worker")return this.activateWorkerPlugin(e,n);if(n.executionMode!=="inline")throw new Error(`Unsupported execution mode for activation: ${n.executionMode}`);t.updatePluginState(e,X.ACTIVATING);try{const i=this.sourceCodes.get(e);if(!i)throw new Error(`No source code found for plugin: ${e}`);const a=await this.moduleLoader(i),d=a.default??a,l=d.manifest??a.manifest,h=d.activate??a.activate,f=d.deactivate??a.deactivate;if(!l||typeof h!="function")throw new Error("Invalid plugin: missing manifest or activate function");if(l.id!==e)throw new Error(`Manifest id mismatch: expected "${e}", got "${l.id}"`);if(l.classroomTools)for(const v of l.classroomTools)t.registerExtensionPoint("classroom.tool",{id:v.id,label:v.name,icon:v.icon,component:()=>Promise.resolve({default:(()=>null)}),pluginId:e});const b=await this.buildContext(e,l);await Promise.race([h(b),new Promise((v,C)=>setTimeout(()=>C(new Error("Activation timeout (5000ms)")),5e3))]),this.pluginModules.set(e,{manifest:l,activate:h,deactivate:typeof f=="function"?f:void 0}),t.updatePluginState(e,X.ACTIVE)}catch(i){throw t.updatePluginState(e,X.ERROR),t.unregisterPluginExtensionPoints(e),i}}async activateWorkerPlugin(e,t){if(!this.workerManager)throw new Error(`Cannot activate plugin "${e}" in worker mode: BrowserWorkerManager not set. Call setWorkerManager() first.`);const n=oe.getState(),i=this.sourceCodes.get(e);if(!i)throw new Error(`No source code found for plugin: ${e}`);const a={id:e,name:t.name,version:t.version};n.updatePluginState(e,X.ACTIVATING);try{let d;if(this.registry)try{d=await this.registry.resolve("@openlearn/frontend:ISocketService")}catch{}const{serviceHost:l}=await this.workerManager.createWorker(e,a,i,$d,d);this.pluginModules.set(e,{manifest:a,activate:async()=>{},deactivate:async()=>{await this.workerManager.terminateWorker(e)}}),n.updatePluginState(e,X.ACTIVE)}catch(d){throw n.updatePluginState(e,X.ERROR),n.unregisterPluginExtensionPoints(e),d}}async deactivatePlugin(e){const t=oe.getState(),n=t.activePlugins.find(i=>i.id===e);if(!(!n||n.state!==X.ACTIVE)){t.updatePluginState(e,X.DEACTIVATING);try{const i=this.pluginModules.get(e);i?.deactivate&&await Promise.race([i.deactivate(),new Promise((a,d)=>setTimeout(()=>d(new Error("Deactivation timeout (5000ms)")),5e3))])}catch(i){console.error(`[FrontendPluginHost] Deactivation error for "${e}":`,i)}finally{t.unregisterPluginExtensionPoints(e),this.pluginModules.delete(e),t.updatePluginState(e,X.INACTIVE)}}}async uninstallPlugin(e){const t=oe.getState();t.activePlugins.find(i=>i.id===e)?.state===X.ACTIVE&&await this.deactivatePlugin(e);try{await fetch(`/api/plugins/${e}`,{method:"DELETE"})}catch(i){console.error(`[FrontendPluginHost] Failed to DELETE plugin "${e}" on server:`,i)}this.sourceCodes.delete(e),this.pluginModules.delete(e),t.removePlugin(e)}getExtensions(e){return oe.getState().getExtensions(e)}async defaultModuleLoader(e){const t=new Blob([e],{type:"text/javascript"}),n=URL.createObjectURL(t);try{return await import(n)}finally{URL.revokeObjectURL(n)}}async buildContext(e,t){if(!this.registry)throw new Error("FrontendPluginHost not initialized");const n=await this.registry.resolve(Qn),i=await this.registry.resolve(Jn),a=await this.registry.resolve(Zn),d=await this.registry.resolve(Kn);return{services:{frontendApi:n,socketService:i,uiService:a,storageService:d},pluginId:e,manifest:t,ui:{registerExtensionPoint:(l,h)=>{oe.getState().registerExtensionPoint(l,{...h,pluginId:e})},unregisterExtensionPoint:(l,h)=>{oe.getState().unregisterExtensionPoint(l,h)}},navigation:{getTeacherTab:()=>ge.getState().teacherTab,setTeacherTab:l=>ge.getState().setTeacherTab(l),subscribeTeacherTab:l=>{let h=ge.getState().teacherTab;return ge.subscribe(f=>{const b=f.teacherTab;b!==h&&(h=b,l(b))})}},invokeCommand:async(l,h)=>{if(!n)throw new Error(`Plugin "${e}" cannot invoke command: frontendApi is not available. Has FrontendPluginHost initialized?`);const f=Dd(l,t.id),b=await n.post("/api/plugins/execute-command",{type:f,payload:h});if(b.success&&b.result!==void 0)return b.result;throw new Error(b.error||"Command execution failed")},registerPanel:l=>{const h=l.slot||"teacher.dashboard.widget";oe.getState().registerExtensionPoint(h,{...l,pluginId:e})},registerMenu:l=>{const h=l.slot||"teacher.panel";oe.getState().registerExtensionPoint(h,{...l,pluginId:e})},registerToolbarButton:l=>{oe.getState().registerExtensionPoint("classroom.tool",{...l,pluginId:e})}}}}class Bd{constructor(e){this.frontendApi=e}async saveSemesterGrade(e,t,n){const i=await this.frontendApi.post("/api/grade-sync",{lessonId:e,studentId:t,grade:n});if(!i.success)throw new Error(i.error||"Failed to sync semester grade")}}window.React=or;window.ReactDOM=ar;window.HostSharedDeps={React:or,ReactDOM:ar,Recharts:xc,LucideReact:fc};const Vd=new Fd;Wa.createRoot(document.getElementById("root")).render(r.jsx(o.StrictMode,{children:r.jsx(zc,{host:Vd,children:r.jsx(Rd,{})})}));export{$u as C,Rc as D,Bu as E,Pc as P,K as a,Fu as b,Tc as c,Wu as d,Mc as g,Ht as l,Dd as r,oe as u};
|